2 * Copyright (C) 2005 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #define LOG_TAG "EventHub"
19 // #define LOG_NDEBUG 0
23 #include <hardware_legacy/power.h>
25 #include <cutils/properties.h>
26 #include <utils/Log.h>
27 #include <utils/Timers.h>
28 #include <utils/threads.h>
29 #include <utils/Errors.h>
39 #include <androidfw/KeyLayoutMap.h>
40 #include <androidfw/KeyCharacterMap.h>
41 #include <androidfw/VirtualKeyMap.h>
47 #include <sys/inotify.h>
48 #include <sys/epoll.h>
49 #include <sys/ioctl.h>
50 #include <sys/limits.h>
53 /* this macro is used to tell if "bit" is set in "array"
54 * it selects a byte from the array, and does a boolean AND
55 * operation with a byte that only has the relevant bit set.
56 * eg. to check for the 12th bit, we do (array[1] & 1<<4)
58 #define test_bit(bit, array) (array[bit/8] & (1<<(bit%8)))
60 /* this macro computes the number of bytes needed to represent a bit array of the specified size */
61 #define sizeof_bit_array(bits) ((bits + 7) / 8)
69 static const char *WAKE_LOCK_ID = "KeyEvents";
70 static const char *DEVICE_PATH = "/dev/input";
72 /* return the larger integer */
73 static inline int max(int v1, int v2)
75 return (v1 > v2) ? v1 : v2;
78 static inline const char* toString(bool value) {
79 return value ? "true" : "false";
82 static String8 sha1(const String8& in) {
85 SHA1Update(&ctx, reinterpret_cast<const u_char*>(in.string()), in.size());
86 u_char digest[SHA1_DIGEST_LENGTH];
87 SHA1Final(digest, &ctx);
90 for (size_t i = 0; i < SHA1_DIGEST_LENGTH; i++) {
91 out.appendFormat("%02x", digest[i]);
96 static void setDescriptor(InputDeviceIdentifier& identifier) {
97 // Compute a device descriptor that uniquely identifies the device.
98 // The descriptor is assumed to be a stable identifier. Its value should not
99 // change between reboots, reconnections, firmware updates or new releases of Android.
100 // Ideally, we also want the descriptor to be short and relatively opaque.
101 String8 rawDescriptor;
102 rawDescriptor.appendFormat(":%04x:%04x:", identifier.vendor, identifier.product);
103 if (!identifier.uniqueId.isEmpty()) {
104 rawDescriptor.append("uniqueId:");
105 rawDescriptor.append(identifier.uniqueId);
106 } if (identifier.vendor == 0 && identifier.product == 0) {
107 // If we don't know the vendor and product id, then the device is probably
108 // built-in so we need to rely on other information to uniquely identify
109 // the input device. Usually we try to avoid relying on the device name or
110 // location but for built-in input device, they are unlikely to ever change.
111 if (!identifier.name.isEmpty()) {
112 rawDescriptor.append("name:");
113 rawDescriptor.append(identifier.name);
114 } else if (!identifier.location.isEmpty()) {
115 rawDescriptor.append("location:");
116 rawDescriptor.append(identifier.location);
119 identifier.descriptor = sha1(rawDescriptor);
120 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.string(),
121 identifier.descriptor.string());
124 // --- Global Functions ---
126 uint32_t getAbsAxisUsage(int32_t axis, uint32_t deviceClasses) {
127 // Touch devices get dibs on touch-related axes.
128 if (deviceClasses & INPUT_DEVICE_CLASS_TOUCH) {
138 case ABS_MT_TOUCH_MAJOR:
139 case ABS_MT_TOUCH_MINOR:
140 case ABS_MT_WIDTH_MAJOR:
141 case ABS_MT_WIDTH_MINOR:
142 case ABS_MT_ORIENTATION:
143 case ABS_MT_POSITION_X:
144 case ABS_MT_POSITION_Y:
145 case ABS_MT_TOOL_TYPE:
147 case ABS_MT_TRACKING_ID:
148 case ABS_MT_PRESSURE:
149 case ABS_MT_DISTANCE:
150 return INPUT_DEVICE_CLASS_TOUCH;
154 // Joystick devices get the rest.
155 return deviceClasses & INPUT_DEVICE_CLASS_JOYSTICK;
158 // --- EventHub::Device ---
160 EventHub::Device::Device(int fd, int32_t id, const String8& path,
161 const InputDeviceIdentifier& identifier) :
163 fd(fd), id(id), path(path), identifier(identifier),
164 classes(0), configuration(NULL), virtualKeyMap(NULL),
165 ffEffectPlaying(false), ffEffectId(-1),
166 timestampOverrideSec(0), timestampOverrideUsec(0) {
167 memset(keyBitmask, 0, sizeof(keyBitmask));
168 memset(absBitmask, 0, sizeof(absBitmask));
169 memset(relBitmask, 0, sizeof(relBitmask));
170 memset(swBitmask, 0, sizeof(swBitmask));
171 memset(ledBitmask, 0, sizeof(ledBitmask));
172 memset(ffBitmask, 0, sizeof(ffBitmask));
173 memset(propBitmask, 0, sizeof(propBitmask));
176 EventHub::Device::~Device() {
178 delete configuration;
179 delete virtualKeyMap;
182 void EventHub::Device::close() {
192 const uint32_t EventHub::EPOLL_ID_INOTIFY;
193 const uint32_t EventHub::EPOLL_ID_WAKE;
194 const int EventHub::EPOLL_SIZE_HINT;
195 const int EventHub::EPOLL_MAX_EVENTS;
197 EventHub::EventHub(void) :
198 mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD), mNextDeviceId(1),
199 mOpeningDevices(0), mClosingDevices(0),
200 mNeedToSendFinishedDeviceScan(false),
201 mNeedToReopenDevices(false), mNeedToScanDevices(true),
202 mPendingEventCount(0), mPendingEventIndex(0), mPendingINotify(false) {
203 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
205 mEpollFd = epoll_create(EPOLL_SIZE_HINT);
206 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance. errno=%d", errno);
208 mINotifyFd = inotify_init();
209 int result = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
210 LOG_ALWAYS_FATAL_IF(result < 0, "Could not register INotify for %s. errno=%d",
213 struct epoll_event eventItem;
214 memset(&eventItem, 0, sizeof(eventItem));
215 eventItem.events = EPOLLIN;
216 eventItem.data.u32 = EPOLL_ID_INOTIFY;
217 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
218 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
221 result = pipe(wakeFds);
222 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
224 mWakeReadPipeFd = wakeFds[0];
225 mWakeWritePipeFd = wakeFds[1];
227 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
228 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
231 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
232 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
235 eventItem.data.u32 = EPOLL_ID_WAKE;
236 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
237 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
241 EventHub::~EventHub(void) {
242 closeAllDevicesLocked();
244 while (mClosingDevices) {
245 Device* device = mClosingDevices;
246 mClosingDevices = device->next;
252 ::close(mWakeReadPipeFd);
253 ::close(mWakeWritePipeFd);
255 release_wake_lock(WAKE_LOCK_ID);
258 InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
260 Device* device = getDeviceLocked(deviceId);
261 if (device == NULL) return InputDeviceIdentifier();
262 return device->identifier;
265 uint32_t EventHub::getDeviceClasses(int32_t deviceId) const {
267 Device* device = getDeviceLocked(deviceId);
268 if (device == NULL) return 0;
269 return device->classes;
272 void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
274 Device* device = getDeviceLocked(deviceId);
275 if (device && device->configuration) {
276 *outConfiguration = *device->configuration;
278 outConfiguration->clear();
282 status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
283 RawAbsoluteAxisInfo* outAxisInfo) const {
284 outAxisInfo->clear();
286 if (axis >= 0 && axis <= ABS_MAX) {
289 Device* device = getDeviceLocked(deviceId);
290 if (device && !device->isVirtual() && test_bit(axis, device->absBitmask)) {
291 struct input_absinfo info;
292 if(ioctl(device->fd, EVIOCGABS(axis), &info)) {
293 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d",
294 axis, device->identifier.name.string(), device->fd, errno);
298 if (info.minimum != info.maximum) {
299 outAxisInfo->valid = true;
300 outAxisInfo->minValue = info.minimum;
301 outAxisInfo->maxValue = info.maximum;
302 outAxisInfo->flat = info.flat;
303 outAxisInfo->fuzz = info.fuzz;
304 outAxisInfo->resolution = info.resolution;
312 bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
313 if (axis >= 0 && axis <= REL_MAX) {
316 Device* device = getDeviceLocked(deviceId);
318 return test_bit(axis, device->relBitmask);
324 bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
325 if (property >= 0 && property <= INPUT_PROP_MAX) {
328 Device* device = getDeviceLocked(deviceId);
330 return test_bit(property, device->propBitmask);
336 int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
337 if (scanCode >= 0 && scanCode <= KEY_MAX) {
340 Device* device = getDeviceLocked(deviceId);
341 if (device && !device->isVirtual() && test_bit(scanCode, device->keyBitmask)) {
342 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
343 memset(keyState, 0, sizeof(keyState));
344 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
345 return test_bit(scanCode, keyState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
349 return AKEY_STATE_UNKNOWN;
352 int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
355 Device* device = getDeviceLocked(deviceId);
356 if (device && !device->isVirtual() && device->keyMap.haveKeyLayout()) {
357 Vector<int32_t> scanCodes;
358 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode, &scanCodes);
359 if (scanCodes.size() != 0) {
360 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
361 memset(keyState, 0, sizeof(keyState));
362 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
363 for (size_t i = 0; i < scanCodes.size(); i++) {
364 int32_t sc = scanCodes.itemAt(i);
365 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, keyState)) {
366 return AKEY_STATE_DOWN;
369 return AKEY_STATE_UP;
373 return AKEY_STATE_UNKNOWN;
376 int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
377 if (sw >= 0 && sw <= SW_MAX) {
380 Device* device = getDeviceLocked(deviceId);
381 if (device && !device->isVirtual() && test_bit(sw, device->swBitmask)) {
382 uint8_t swState[sizeof_bit_array(SW_MAX + 1)];
383 memset(swState, 0, sizeof(swState));
384 if (ioctl(device->fd, EVIOCGSW(sizeof(swState)), swState) >= 0) {
385 return test_bit(sw, swState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
389 return AKEY_STATE_UNKNOWN;
392 status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
395 if (axis >= 0 && axis <= ABS_MAX) {
398 Device* device = getDeviceLocked(deviceId);
399 if (device && !device->isVirtual() && test_bit(axis, device->absBitmask)) {
400 struct input_absinfo info;
401 if(ioctl(device->fd, EVIOCGABS(axis), &info)) {
402 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d",
403 axis, device->identifier.name.string(), device->fd, errno);
407 *outValue = info.value;
414 bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes,
415 const int32_t* keyCodes, uint8_t* outFlags) const {
418 Device* device = getDeviceLocked(deviceId);
419 if (device && device->keyMap.haveKeyLayout()) {
420 Vector<int32_t> scanCodes;
421 for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) {
424 status_t err = device->keyMap.keyLayoutMap->findScanCodesForKey(
425 keyCodes[codeIndex], &scanCodes);
427 // check the possible scan codes identified by the layout map against the
428 // map of codes actually emitted by the driver
429 for (size_t sc = 0; sc < scanCodes.size(); sc++) {
430 if (test_bit(scanCodes[sc], device->keyBitmask)) {
431 outFlags[codeIndex] = 1;
442 status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode,
443 int32_t* outKeycode, uint32_t* outFlags) const {
445 Device* device = getDeviceLocked(deviceId);
448 // Check the key character map first.
449 sp<KeyCharacterMap> kcm = device->getKeyCharacterMap();
451 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
457 // Check the key layout next.
458 if (device->keyMap.haveKeyLayout()) {
459 if (!device->keyMap.keyLayoutMap->mapKey(
460 scanCode, usageCode, outKeycode, outFlags)) {
468 return NAME_NOT_FOUND;
471 status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
473 Device* device = getDeviceLocked(deviceId);
475 if (device && device->keyMap.haveKeyLayout()) {
476 status_t err = device->keyMap.keyLayoutMap->mapAxis(scanCode, outAxisInfo);
477 if (err == NO_ERROR) {
482 return NAME_NOT_FOUND;
485 void EventHub::setExcludedDevices(const Vector<String8>& devices) {
488 mExcludedDevices = devices;
491 bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
493 Device* device = getDeviceLocked(deviceId);
494 if (device && scanCode >= 0 && scanCode <= KEY_MAX) {
495 if (test_bit(scanCode, device->keyBitmask)) {
502 bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
504 Device* device = getDeviceLocked(deviceId);
505 if (device && led >= 0 && led <= LED_MAX) {
506 if (test_bit(led, device->ledBitmask)) {
513 void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
515 Device* device = getDeviceLocked(deviceId);
516 if (device && !device->isVirtual() && led >= 0 && led <= LED_MAX) {
517 struct input_event ev;
522 ev.value = on ? 1 : 0;
526 nWrite = write(device->fd, &ev, sizeof(struct input_event));
527 } while (nWrite == -1 && errno == EINTR);
531 void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
532 Vector<VirtualKeyDefinition>& outVirtualKeys) const {
533 outVirtualKeys.clear();
536 Device* device = getDeviceLocked(deviceId);
537 if (device && device->virtualKeyMap) {
538 outVirtualKeys.appendVector(device->virtualKeyMap->getVirtualKeys());
542 sp<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
544 Device* device = getDeviceLocked(deviceId);
546 return device->getKeyCharacterMap();
551 bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId,
552 const sp<KeyCharacterMap>& map) {
554 Device* device = getDeviceLocked(deviceId);
556 if (map != device->overlayKeyMap) {
557 device->overlayKeyMap = map;
558 device->combinedKeyMap = KeyCharacterMap::combine(
559 device->keyMap.keyCharacterMap, map);
566 void EventHub::vibrate(int32_t deviceId, nsecs_t duration) {
568 Device* device = getDeviceLocked(deviceId);
569 if (device && !device->isVirtual()) {
571 memset(&effect, 0, sizeof(effect));
572 effect.type = FF_RUMBLE;
573 effect.id = device->ffEffectId;
574 effect.u.rumble.strong_magnitude = 0xc000;
575 effect.u.rumble.weak_magnitude = 0xc000;
576 effect.replay.length = (duration + 999999LL) / 1000000LL;
577 effect.replay.delay = 0;
578 if (ioctl(device->fd, EVIOCSFF, &effect)) {
579 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
580 device->identifier.name.string(), errno);
583 device->ffEffectId = effect.id;
585 struct input_event ev;
589 ev.code = device->ffEffectId;
591 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
592 ALOGW("Could not start force feedback effect on device %s due to error %d.",
593 device->identifier.name.string(), errno);
596 device->ffEffectPlaying = true;
600 void EventHub::cancelVibrate(int32_t deviceId) {
602 Device* device = getDeviceLocked(deviceId);
603 if (device && !device->isVirtual()) {
604 if (device->ffEffectPlaying) {
605 device->ffEffectPlaying = false;
607 struct input_event ev;
611 ev.code = device->ffEffectId;
613 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
614 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
615 device->identifier.name.string(), errno);
622 EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
623 if (deviceId == BUILT_IN_KEYBOARD_ID) {
624 deviceId = mBuiltInKeyboardId;
626 ssize_t index = mDevices.indexOfKey(deviceId);
627 return index >= 0 ? mDevices.valueAt(index) : NULL;
630 EventHub::Device* EventHub::getDeviceByPathLocked(const char* devicePath) const {
631 for (size_t i = 0; i < mDevices.size(); i++) {
632 Device* device = mDevices.valueAt(i);
633 if (device->path == devicePath) {
640 size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
641 ALOG_ASSERT(bufferSize >= 1);
645 struct input_event readBuffer[bufferSize];
647 RawEvent* event = buffer;
648 size_t capacity = bufferSize;
651 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
653 // Reopen input devices if needed.
654 if (mNeedToReopenDevices) {
655 mNeedToReopenDevices = false;
657 ALOGI("Reopening all input devices due to a configuration change.");
659 closeAllDevicesLocked();
660 mNeedToScanDevices = true;
661 break; // return to the caller before we actually rescan
664 // Report any devices that had last been added/removed.
665 while (mClosingDevices) {
666 Device* device = mClosingDevices;
667 ALOGV("Reporting device closed: id=%d, name=%s\n",
668 device->id, device->path.string());
669 mClosingDevices = device->next;
671 event->deviceId = device->id == mBuiltInKeyboardId ? BUILT_IN_KEYBOARD_ID : device->id;
672 event->type = DEVICE_REMOVED;
675 mNeedToSendFinishedDeviceScan = true;
676 if (--capacity == 0) {
681 if (mNeedToScanDevices) {
682 mNeedToScanDevices = false;
684 mNeedToSendFinishedDeviceScan = true;
687 while (mOpeningDevices != NULL) {
688 Device* device = mOpeningDevices;
689 ALOGV("Reporting device opened: id=%d, name=%s\n",
690 device->id, device->path.string());
691 mOpeningDevices = device->next;
693 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
694 event->type = DEVICE_ADDED;
696 mNeedToSendFinishedDeviceScan = true;
697 if (--capacity == 0) {
702 if (mNeedToSendFinishedDeviceScan) {
703 mNeedToSendFinishedDeviceScan = false;
705 event->type = FINISHED_DEVICE_SCAN;
707 if (--capacity == 0) {
712 // Grab the next input event.
713 bool deviceChanged = false;
714 while (mPendingEventIndex < mPendingEventCount) {
715 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
716 if (eventItem.data.u32 == EPOLL_ID_INOTIFY) {
717 if (eventItem.events & EPOLLIN) {
718 mPendingINotify = true;
720 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
725 if (eventItem.data.u32 == EPOLL_ID_WAKE) {
726 if (eventItem.events & EPOLLIN) {
727 ALOGV("awoken after wake()");
732 nRead = read(mWakeReadPipeFd, buffer, sizeof(buffer));
733 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(buffer));
735 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
741 ssize_t deviceIndex = mDevices.indexOfKey(eventItem.data.u32);
742 if (deviceIndex < 0) {
743 ALOGW("Received unexpected epoll event 0x%08x for unknown device id %d.",
744 eventItem.events, eventItem.data.u32);
748 Device* device = mDevices.valueAt(deviceIndex);
749 if (eventItem.events & EPOLLIN) {
750 int32_t readSize = read(device->fd, readBuffer,
751 sizeof(struct input_event) * capacity);
752 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
753 // Device was removed before INotify noticed.
754 ALOGW("could not get event, removed? (fd: %d size: %d bufferSize: %d "
755 "capacity: %d errno: %d)\n",
756 device->fd, readSize, bufferSize, capacity, errno);
757 deviceChanged = true;
758 closeDeviceLocked(device);
759 } else if (readSize < 0) {
760 if (errno != EAGAIN && errno != EINTR) {
761 ALOGW("could not get event (errno=%d)", errno);
763 } else if ((readSize % sizeof(struct input_event)) != 0) {
764 ALOGE("could not get event (wrong size: %d)", readSize);
766 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
768 size_t count = size_t(readSize) / sizeof(struct input_event);
769 for (size_t i = 0; i < count; i++) {
770 struct input_event& iev = readBuffer[i];
771 ALOGV("%s got: time=%d.%06d, type=%d, code=%d, value=%d",
772 device->path.string(),
773 (int) iev.time.tv_sec, (int) iev.time.tv_usec,
774 iev.type, iev.code, iev.value);
776 // Some input devices may have a better concept of the time
777 // when an input event was actually generated than the kernel
778 // which simply timestamps all events on entry to evdev.
779 // This is a custom Android extension of the input protocol
780 // mainly intended for use with uinput based device drivers.
781 if (iev.type == EV_MSC) {
782 if (iev.code == MSC_ANDROID_TIME_SEC) {
783 device->timestampOverrideSec = iev.value;
785 } else if (iev.code == MSC_ANDROID_TIME_USEC) {
786 device->timestampOverrideUsec = iev.value;
790 if (device->timestampOverrideSec || device->timestampOverrideUsec) {
791 iev.time.tv_sec = device->timestampOverrideSec;
792 iev.time.tv_usec = device->timestampOverrideUsec;
793 if (iev.type == EV_SYN && iev.code == SYN_REPORT) {
794 device->timestampOverrideSec = 0;
795 device->timestampOverrideUsec = 0;
797 ALOGV("applied override time %d.%06d",
798 int(iev.time.tv_sec), int(iev.time.tv_usec));
801 #ifdef HAVE_POSIX_CLOCKS
802 // Use the time specified in the event instead of the current time
803 // so that downstream code can get more accurate estimates of
804 // event dispatch latency from the time the event is enqueued onto
805 // the evdev client buffer.
807 // The event's timestamp fortuitously uses the same monotonic clock
808 // time base as the rest of Android. The kernel event device driver
809 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
810 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
811 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
812 // system call that also queries ktime_get_ts().
813 event->when = nsecs_t(iev.time.tv_sec) * 1000000000LL
814 + nsecs_t(iev.time.tv_usec) * 1000LL;
815 ALOGV("event time %lld, now %lld", event->when, now);
817 // Bug 7291243: Add a guard in case the kernel generates timestamps
818 // that appear to be far into the future because they were generated
819 // using the wrong clock source.
821 // This can happen because when the input device is initially opened
822 // it has a default clock source of CLOCK_REALTIME. Any input events
823 // enqueued right after the device is opened will have timestamps
824 // generated using CLOCK_REALTIME. We later set the clock source
825 // to CLOCK_MONOTONIC but it is already too late.
827 // Invalid input event timestamps can result in ANRs, crashes and
828 // and other issues that are hard to track down. We must not let them
829 // propagate through the system.
831 // Log a warning so that we notice the problem and recover gracefully.
832 if (event->when >= now + 10 * 1000000000LL) {
833 // Double-check. Time may have moved on.
834 nsecs_t time = systemTime(SYSTEM_TIME_MONOTONIC);
835 if (event->when > time) {
836 ALOGW("An input event from %s has a timestamp that appears to "
837 "have been generated using the wrong clock source "
838 "(expected CLOCK_MONOTONIC): "
839 "event time %lld, current time %lld, call time %lld. "
840 "Using current time instead.",
841 device->path.string(), event->when, time, now);
844 ALOGV("Event time is ok but failed the fast path and required "
845 "an extra call to systemTime: "
846 "event time %lld, current time %lld, call time %lld.",
847 event->when, time, now);
853 event->deviceId = deviceId;
854 event->type = iev.type;
855 event->code = iev.code;
856 event->value = iev.value;
861 // The result buffer is full. Reset the pending event index
862 // so we will try to read the device again on the next iteration.
863 mPendingEventIndex -= 1;
867 } else if (eventItem.events & EPOLLHUP) {
868 ALOGI("Removing device %s due to epoll hang-up event.",
869 device->identifier.name.string());
870 deviceChanged = true;
871 closeDeviceLocked(device);
873 ALOGW("Received unexpected epoll event 0x%08x for device %s.",
874 eventItem.events, device->identifier.name.string());
878 // readNotify() will modify the list of devices so this must be done after
879 // processing all other events to ensure that we read all remaining events
880 // before closing the devices.
881 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
882 mPendingINotify = false;
884 deviceChanged = true;
887 // Report added or removed devices immediately.
892 // Return now if we have collected any events or if we were explicitly awoken.
893 if (event != buffer || awoken) {
897 // Poll for events. Mind the wake lock dance!
898 // We hold a wake lock at all times except during epoll_wait(). This works due to some
899 // subtle choreography. When a device driver has pending (unread) events, it acquires
900 // a kernel wake lock. However, once the last pending event has been read, the device
901 // driver will release the kernel wake lock. To prevent the system from going to sleep
902 // when this happens, the EventHub holds onto its own user wake lock while the client
903 // is processing events. Thus the system can only sleep if there are no events
904 // pending or currently being processed.
906 // The timeout is advisory only. If the device is asleep, it will not wake just to
907 // service the timeout.
908 mPendingEventIndex = 0;
910 mLock.unlock(); // release lock before poll, must be before release_wake_lock
911 release_wake_lock(WAKE_LOCK_ID);
913 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
915 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
916 mLock.lock(); // reacquire lock after poll, must be after acquire_wake_lock
918 if (pollResult == 0) {
920 mPendingEventCount = 0;
924 if (pollResult < 0) {
925 // An error occurred.
926 mPendingEventCount = 0;
928 // Sleep after errors to avoid locking up the system.
929 // Hopefully the error is transient.
930 if (errno != EINTR) {
931 ALOGW("poll failed (errno=%d)\n", errno);
935 // Some events occurred.
936 mPendingEventCount = size_t(pollResult);
940 // All done, return the number of events we read.
941 return event - buffer;
944 void EventHub::wake() {
945 ALOGV("wake() called");
949 nWrite = write(mWakeWritePipeFd, "W", 1);
950 } while (nWrite == -1 && errno == EINTR);
952 if (nWrite != 1 && errno != EAGAIN) {
953 ALOGW("Could not write wake signal, errno=%d", errno);
957 void EventHub::scanDevicesLocked() {
958 status_t res = scanDirLocked(DEVICE_PATH);
960 ALOGE("scan dir failed for %s\n", DEVICE_PATH);
962 if (mDevices.indexOfKey(VIRTUAL_KEYBOARD_ID) < 0) {
963 createVirtualKeyboardLocked();
967 // ----------------------------------------------------------------------------
969 static bool containsNonZeroByte(const uint8_t* array, uint32_t startIndex, uint32_t endIndex) {
970 const uint8_t* end = array + endIndex;
972 while (array != end) {
973 if (*(array++) != 0) {
980 static const int32_t GAMEPAD_KEYCODES[] = {
981 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C,
982 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z,
983 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1,
984 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2,
985 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR,
986 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE,
987 AKEYCODE_BUTTON_1, AKEYCODE_BUTTON_2, AKEYCODE_BUTTON_3, AKEYCODE_BUTTON_4,
988 AKEYCODE_BUTTON_5, AKEYCODE_BUTTON_6, AKEYCODE_BUTTON_7, AKEYCODE_BUTTON_8,
989 AKEYCODE_BUTTON_9, AKEYCODE_BUTTON_10, AKEYCODE_BUTTON_11, AKEYCODE_BUTTON_12,
990 AKEYCODE_BUTTON_13, AKEYCODE_BUTTON_14, AKEYCODE_BUTTON_15, AKEYCODE_BUTTON_16,
993 status_t EventHub::openDeviceLocked(const char *devicePath) {
996 ALOGV("Opening device: %s", devicePath);
998 int fd = open(devicePath, O_RDWR | O_CLOEXEC);
1000 ALOGE("could not open %s, %s\n", devicePath, strerror(errno));
1004 InputDeviceIdentifier identifier;
1007 if(ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
1008 //fprintf(stderr, "could not get device name for %s, %s\n", devicePath, strerror(errno));
1010 buffer[sizeof(buffer) - 1] = '\0';
1011 identifier.name.setTo(buffer);
1014 // Check to see if the device is on our excluded list
1015 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
1016 const String8& item = mExcludedDevices.itemAt(i);
1017 if (identifier.name == item) {
1018 ALOGI("ignoring event id %s driver %s\n", devicePath, item.string());
1024 // Get device driver version.
1026 if(ioctl(fd, EVIOCGVERSION, &driverVersion)) {
1027 ALOGE("could not get driver version for %s, %s\n", devicePath, strerror(errno));
1032 // Get device identifier.
1033 struct input_id inputId;
1034 if(ioctl(fd, EVIOCGID, &inputId)) {
1035 ALOGE("could not get device input id for %s, %s\n", devicePath, strerror(errno));
1039 identifier.bus = inputId.bustype;
1040 identifier.product = inputId.product;
1041 identifier.vendor = inputId.vendor;
1042 identifier.version = inputId.version;
1044 // Get device physical location.
1045 if(ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
1046 //fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
1048 buffer[sizeof(buffer) - 1] = '\0';
1049 identifier.location.setTo(buffer);
1052 // Get device unique id.
1053 if(ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
1054 //fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
1056 buffer[sizeof(buffer) - 1] = '\0';
1057 identifier.uniqueId.setTo(buffer);
1060 // Fill in the descriptor.
1061 setDescriptor(identifier);
1063 // Make file descriptor non-blocking for use with poll().
1064 if (fcntl(fd, F_SETFL, O_NONBLOCK)) {
1065 ALOGE("Error %d making device file descriptor non-blocking.", errno);
1070 // Allocate device. (The device object takes ownership of the fd at this point.)
1071 int32_t deviceId = mNextDeviceId++;
1072 Device* device = new Device(fd, deviceId, String8(devicePath), identifier);
1074 ALOGV("add device %d: %s\n", deviceId, devicePath);
1075 ALOGV(" bus: %04x\n"
1079 identifier.bus, identifier.vendor, identifier.product, identifier.version);
1080 ALOGV(" name: \"%s\"\n", identifier.name.string());
1081 ALOGV(" location: \"%s\"\n", identifier.location.string());
1082 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.string());
1083 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.string());
1084 ALOGV(" driver: v%d.%d.%d\n",
1085 driverVersion >> 16, (driverVersion >> 8) & 0xff, driverVersion & 0xff);
1087 // Load the configuration file for the device.
1088 loadConfigurationLocked(device);
1090 // Figure out the kinds of events the device reports.
1091 ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(device->keyBitmask)), device->keyBitmask);
1092 ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(device->absBitmask)), device->absBitmask);
1093 ioctl(fd, EVIOCGBIT(EV_REL, sizeof(device->relBitmask)), device->relBitmask);
1094 ioctl(fd, EVIOCGBIT(EV_SW, sizeof(device->swBitmask)), device->swBitmask);
1095 ioctl(fd, EVIOCGBIT(EV_LED, sizeof(device->ledBitmask)), device->ledBitmask);
1096 ioctl(fd, EVIOCGBIT(EV_FF, sizeof(device->ffBitmask)), device->ffBitmask);
1097 ioctl(fd, EVIOCGPROP(sizeof(device->propBitmask)), device->propBitmask);
1099 // See if this is a keyboard. Ignore everything in the button range except for
1100 // joystick and gamepad buttons which are handled like keyboards for the most part.
1101 bool haveKeyboardKeys = containsNonZeroByte(device->keyBitmask, 0, sizeof_bit_array(BTN_MISC))
1102 || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(KEY_OK),
1103 sizeof_bit_array(KEY_MAX + 1));
1104 bool haveGamepadButtons = containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_MISC),
1105 sizeof_bit_array(BTN_MOUSE))
1106 || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_JOYSTICK),
1107 sizeof_bit_array(BTN_DIGI));
1108 if (haveKeyboardKeys || haveGamepadButtons) {
1109 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1112 // See if this is a cursor device such as a trackball or mouse.
1113 if (test_bit(BTN_MOUSE, device->keyBitmask)
1114 && test_bit(REL_X, device->relBitmask)
1115 && test_bit(REL_Y, device->relBitmask)) {
1116 device->classes |= INPUT_DEVICE_CLASS_CURSOR;
1119 // See if this is a touch pad.
1120 // Is this a new modern multi-touch driver?
1121 if (test_bit(ABS_MT_POSITION_X, device->absBitmask)
1122 && test_bit(ABS_MT_POSITION_Y, device->absBitmask)) {
1123 // Some joysticks such as the PS3 controller report axes that conflict
1124 // with the ABS_MT range. Try to confirm that the device really is
1126 if (test_bit(BTN_TOUCH, device->keyBitmask) || !haveGamepadButtons) {
1127 device->classes |= INPUT_DEVICE_CLASS_TOUCH | INPUT_DEVICE_CLASS_TOUCH_MT;
1129 // Is this an old style single-touch driver?
1130 } else if (test_bit(BTN_TOUCH, device->keyBitmask)
1131 && test_bit(ABS_X, device->absBitmask)
1132 && test_bit(ABS_Y, device->absBitmask)) {
1133 device->classes |= INPUT_DEVICE_CLASS_TOUCH;
1136 // See if this device is a joystick.
1137 // Assumes that joysticks always have gamepad buttons in order to distinguish them
1138 // from other devices such as accelerometers that also have absolute axes.
1139 if (haveGamepadButtons) {
1140 uint32_t assumedClasses = device->classes | INPUT_DEVICE_CLASS_JOYSTICK;
1141 for (int i = 0; i <= ABS_MAX; i++) {
1142 if (test_bit(i, device->absBitmask)
1143 && (getAbsAxisUsage(i, assumedClasses) & INPUT_DEVICE_CLASS_JOYSTICK)) {
1144 device->classes = assumedClasses;
1150 // Check whether this device has switches.
1151 for (int i = 0; i <= SW_MAX; i++) {
1152 if (test_bit(i, device->swBitmask)) {
1153 device->classes |= INPUT_DEVICE_CLASS_SWITCH;
1158 // Check whether this device supports the vibrator.
1159 if (test_bit(FF_RUMBLE, device->ffBitmask)) {
1160 device->classes |= INPUT_DEVICE_CLASS_VIBRATOR;
1163 // Configure virtual keys.
1164 if ((device->classes & INPUT_DEVICE_CLASS_TOUCH)) {
1165 // Load the virtual keys for the touch screen, if any.
1166 // We do this now so that we can make sure to load the keymap if necessary.
1167 status_t status = loadVirtualKeyMapLocked(device);
1169 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1173 // Load the key map.
1174 // We need to do this for joysticks too because the key layout may specify axes.
1175 status_t keyMapStatus = NAME_NOT_FOUND;
1176 if (device->classes & (INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_JOYSTICK)) {
1177 // Load the keymap for the device.
1178 keyMapStatus = loadKeyMapLocked(device);
1181 // Configure the keyboard, gamepad or virtual keyboard.
1182 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1183 // Register the keyboard as a built-in keyboard if it is eligible.
1185 && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD
1186 && isEligibleBuiltInKeyboard(device->identifier,
1187 device->configuration, &device->keyMap)) {
1188 mBuiltInKeyboardId = device->id;
1191 // See if this device has a DPAD.
1192 if (hasKeycodeLocked(device, AKEYCODE_DPAD_UP) &&
1193 hasKeycodeLocked(device, AKEYCODE_DPAD_DOWN) &&
1194 hasKeycodeLocked(device, AKEYCODE_DPAD_LEFT) &&
1195 hasKeycodeLocked(device, AKEYCODE_DPAD_RIGHT) &&
1196 hasKeycodeLocked(device, AKEYCODE_DPAD_CENTER)) {
1197 device->classes |= INPUT_DEVICE_CLASS_DPAD;
1200 // See if this device has a gamepad.
1201 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES)/sizeof(GAMEPAD_KEYCODES[0]); i++) {
1202 if (hasKeycodeLocked(device, GAMEPAD_KEYCODES[i])) {
1203 device->classes |= INPUT_DEVICE_CLASS_GAMEPAD;
1208 // 'Q' key support = cheap test of whether this is an alpha-capable kbd. Many gamepads will
1209 // report a broader set of HID usages than they need, however, so we only want to mark this
1210 // device as a keyboard if it is not a gamepad.
1211 if (hasKeycodeLocked(device, AKEYCODE_Q) &&
1212 !(device->classes & INPUT_DEVICE_CLASS_GAMEPAD)) {
1213 device->classes |= INPUT_DEVICE_CLASS_ALPHAKEY;
1216 // Disable kernel key repeat since we handle it ourselves
1217 unsigned int repeatRate[] = {0,0};
1218 if (ioctl(fd, EVIOCSREP, repeatRate)) {
1219 ALOGW("Unable to disable kernel key repeat for %s: %s", devicePath, strerror(errno));
1223 // If the device isn't recognized as something we handle, don't monitor it.
1224 if (device->classes == 0) {
1225 ALOGV("Dropping device: id=%d, path='%s', name='%s'",
1226 deviceId, devicePath, device->identifier.name.string());
1231 // Determine whether the device is external or internal.
1232 if (isExternalDeviceLocked(device)) {
1233 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL;
1236 // Register with epoll.
1237 struct epoll_event eventItem;
1238 memset(&eventItem, 0, sizeof(eventItem));
1239 eventItem.events = EPOLLIN;
1240 eventItem.data.u32 = deviceId;
1241 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1242 ALOGE("Could not add device fd to epoll instance. errno=%d", errno);
1247 // Enable wake-lock behavior on kernels that support it.
1248 // TODO: Only need this for devices that can really wake the system.
1249 bool usingSuspendBlockIoctl = !ioctl(fd, EVIOCSSUSPENDBLOCK, 1);
1251 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
1252 // associated with input events. This is important because the input system
1253 // uses the timestamps extensively and assumes they were recorded using the monotonic
1256 // In older kernel, before Linux 3.4, there was no way to tell the kernel which
1257 // clock to use to input event timestamps. The standard kernel behavior was to
1258 // record a real time timestamp, which isn't what we want. Android kernels therefore
1259 // contained a patch to the evdev_event() function in drivers/input/evdev.c to
1260 // replace the call to do_gettimeofday() with ktime_get_ts() to cause the monotonic
1261 // clock to be used instead of the real time clock.
1263 // As of Linux 3.4, there is a new EVIOCSCLOCKID ioctl to set the desired clock.
1264 // Therefore, we no longer require the Android-specific kernel patch described above
1265 // as long as we make sure to set select the monotonic clock. We do that here.
1266 int clockId = CLOCK_MONOTONIC;
1267 bool usingClockIoctl = !ioctl(fd, EVIOCSCLOCKID, &clockId);
1269 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=0x%x, "
1270 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, "
1271 "usingSuspendBlockIoctl=%s, usingClockIoctl=%s",
1272 deviceId, fd, devicePath, device->identifier.name.string(),
1274 device->configurationFile.string(),
1275 device->keyMap.keyLayoutFile.string(),
1276 device->keyMap.keyCharacterMapFile.string(),
1277 toString(mBuiltInKeyboardId == deviceId),
1278 toString(usingSuspendBlockIoctl), toString(usingClockIoctl));
1280 addDeviceLocked(device);
1284 void EventHub::createVirtualKeyboardLocked() {
1285 InputDeviceIdentifier identifier;
1286 identifier.name = "Virtual";
1287 identifier.uniqueId = "<virtual>";
1288 setDescriptor(identifier);
1290 Device* device = new Device(-1, VIRTUAL_KEYBOARD_ID, String8("<virtual>"), identifier);
1291 device->classes = INPUT_DEVICE_CLASS_KEYBOARD
1292 | INPUT_DEVICE_CLASS_ALPHAKEY
1293 | INPUT_DEVICE_CLASS_DPAD
1294 | INPUT_DEVICE_CLASS_VIRTUAL;
1295 loadKeyMapLocked(device);
1296 addDeviceLocked(device);
1299 void EventHub::addDeviceLocked(Device* device) {
1300 mDevices.add(device->id, device);
1301 device->next = mOpeningDevices;
1302 mOpeningDevices = device;
1305 void EventHub::loadConfigurationLocked(Device* device) {
1306 device->configurationFile = getInputDeviceConfigurationFilePathByDeviceIdentifier(
1307 device->identifier, INPUT_DEVICE_CONFIGURATION_FILE_TYPE_CONFIGURATION);
1308 if (device->configurationFile.isEmpty()) {
1309 ALOGD("No input device configuration file found for device '%s'.",
1310 device->identifier.name.string());
1312 status_t status = PropertyMap::load(device->configurationFile,
1313 &device->configuration);
1315 ALOGE("Error loading input device configuration file for device '%s'. "
1316 "Using default configuration.",
1317 device->identifier.name.string());
1322 status_t EventHub::loadVirtualKeyMapLocked(Device* device) {
1323 // The virtual key map is supplied by the kernel as a system board property file.
1325 path.append("/sys/board_properties/virtualkeys.");
1326 path.append(device->identifier.name);
1327 if (access(path.string(), R_OK)) {
1328 return NAME_NOT_FOUND;
1330 return VirtualKeyMap::load(path, &device->virtualKeyMap);
1333 status_t EventHub::loadKeyMapLocked(Device* device) {
1334 return device->keyMap.load(device->identifier, device->configuration);
1337 bool EventHub::isExternalDeviceLocked(Device* device) {
1338 if (device->configuration) {
1340 if (device->configuration->tryGetProperty(String8("device.internal"), value)) {
1344 return device->identifier.bus == BUS_USB || device->identifier.bus == BUS_BLUETOOTH;
1347 bool EventHub::hasKeycodeLocked(Device* device, int keycode) const {
1348 if (!device->keyMap.haveKeyLayout() || !device->keyBitmask) {
1352 Vector<int32_t> scanCodes;
1353 device->keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes);
1354 const size_t N = scanCodes.size();
1355 for (size_t i=0; i<N && i<=KEY_MAX; i++) {
1356 int32_t sc = scanCodes.itemAt(i);
1357 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, device->keyBitmask)) {
1365 status_t EventHub::closeDeviceByPathLocked(const char *devicePath) {
1366 Device* device = getDeviceByPathLocked(devicePath);
1368 closeDeviceLocked(device);
1371 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath);
1375 void EventHub::closeAllDevicesLocked() {
1376 while (mDevices.size() > 0) {
1377 closeDeviceLocked(mDevices.valueAt(mDevices.size() - 1));
1381 void EventHub::closeDeviceLocked(Device* device) {
1382 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=0x%x\n",
1383 device->path.string(), device->identifier.name.string(), device->id,
1384 device->fd, device->classes);
1386 if (device->id == mBuiltInKeyboardId) {
1387 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
1388 device->path.string(), mBuiltInKeyboardId);
1389 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
1392 if (!device->isVirtual()) {
1393 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, device->fd, NULL)) {
1394 ALOGW("Could not remove device fd from epoll instance. errno=%d", errno);
1398 mDevices.removeItem(device->id);
1401 // Unlink for opening devices list if it is present.
1402 Device* pred = NULL;
1404 for (Device* entry = mOpeningDevices; entry != NULL; ) {
1405 if (entry == device) {
1410 entry = entry->next;
1413 // Unlink the device from the opening devices list then delete it.
1414 // We don't need to tell the client that the device was closed because
1415 // it does not even know it was opened in the first place.
1416 ALOGI("Device %s was immediately closed after opening.", device->path.string());
1418 pred->next = device->next;
1420 mOpeningDevices = device->next;
1424 // Link into closing devices list.
1425 // The device will be deleted later after we have informed the client.
1426 device->next = mClosingDevices;
1427 mClosingDevices = device;
1431 status_t EventHub::readNotifyLocked() {
1433 char devname[PATH_MAX];
1435 char event_buf[512];
1438 struct inotify_event *event;
1440 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
1441 res = read(mINotifyFd, event_buf, sizeof(event_buf));
1442 if(res < (int)sizeof(*event)) {
1445 ALOGW("could not get event, %s\n", strerror(errno));
1448 //printf("got %d bytes of event information\n", res);
1450 strcpy(devname, DEVICE_PATH);
1451 filename = devname + strlen(devname);
1454 while(res >= (int)sizeof(*event)) {
1455 event = (struct inotify_event *)(event_buf + event_pos);
1456 //printf("%d: %08x \"%s\"\n", event->wd, event->mask, event->len ? event->name : "");
1458 strcpy(filename, event->name);
1459 if(event->mask & IN_CREATE) {
1460 openDeviceLocked(devname);
1462 ALOGI("Removing device '%s' due to inotify event\n", devname);
1463 closeDeviceByPathLocked(devname);
1466 event_size = sizeof(*event) + event->len;
1468 event_pos += event_size;
1473 status_t EventHub::scanDirLocked(const char *dirname)
1475 char devname[PATH_MAX];
1479 dir = opendir(dirname);
1482 strcpy(devname, dirname);
1483 filename = devname + strlen(devname);
1485 while((de = readdir(dir))) {
1486 if(de->d_name[0] == '.' &&
1487 (de->d_name[1] == '\0' ||
1488 (de->d_name[1] == '.' && de->d_name[2] == '\0')))
1490 strcpy(filename, de->d_name);
1491 openDeviceLocked(devname);
1497 void EventHub::requestReopenDevices() {
1498 ALOGV("requestReopenDevices() called");
1500 AutoMutex _l(mLock);
1501 mNeedToReopenDevices = true;
1504 void EventHub::dump(String8& dump) {
1505 dump.append("Event Hub State:\n");
1508 AutoMutex _l(mLock);
1510 dump.appendFormat(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
1512 dump.append(INDENT "Devices:\n");
1514 for (size_t i = 0; i < mDevices.size(); i++) {
1515 const Device* device = mDevices.valueAt(i);
1516 if (mBuiltInKeyboardId == device->id) {
1517 dump.appendFormat(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
1518 device->id, device->identifier.name.string());
1520 dump.appendFormat(INDENT2 "%d: %s\n", device->id,
1521 device->identifier.name.string());
1523 dump.appendFormat(INDENT3 "Classes: 0x%08x\n", device->classes);
1524 dump.appendFormat(INDENT3 "Path: %s\n", device->path.string());
1525 dump.appendFormat(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.string());
1526 dump.appendFormat(INDENT3 "Location: %s\n", device->identifier.location.string());
1527 dump.appendFormat(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.string());
1528 dump.appendFormat(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
1529 "product=0x%04x, version=0x%04x\n",
1530 device->identifier.bus, device->identifier.vendor,
1531 device->identifier.product, device->identifier.version);
1532 dump.appendFormat(INDENT3 "KeyLayoutFile: %s\n",
1533 device->keyMap.keyLayoutFile.string());
1534 dump.appendFormat(INDENT3 "KeyCharacterMapFile: %s\n",
1535 device->keyMap.keyCharacterMapFile.string());
1536 dump.appendFormat(INDENT3 "ConfigurationFile: %s\n",
1537 device->configurationFile.string());
1538 dump.appendFormat(INDENT3 "HaveKeyboardLayoutOverlay: %s\n",
1539 toString(device->overlayKeyMap != NULL));
1544 void EventHub::monitor() {
1545 // Acquire and release the lock to ensure that the event hub has not deadlocked.
1551 }; // namespace android