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>
55 /* this macro is used to tell if "bit" is set in "array"
56 * it selects a byte from the array, and does a boolean AND
57 * operation with a byte that only has the relevant bit set.
58 * eg. to check for the 12th bit, we do (array[1] & 1<<4)
60 #define test_bit(bit, array) (array[bit/8] & (1<<(bit%8)))
62 /* this macro computes the number of bytes needed to represent a bit array of the specified size */
63 #define sizeof_bit_array(bits) ((bits + 7) / 8)
73 static const char *WAKE_LOCK_ID = "KeyEvents";
74 static const char *DEVICE_PATH = "/dev/input";
76 /* return the larger integer */
77 static inline int max(int v1, int v2)
79 return (v1 > v2) ? v1 : v2;
82 static inline const char* toString(bool value) {
83 return value ? "true" : "false";
86 static String8 sha1(const String8& in) {
89 SHA1Update(&ctx, reinterpret_cast<const u_char*>(in.string()), in.size());
90 u_char digest[SHA1_DIGEST_LENGTH];
91 SHA1Final(digest, &ctx);
94 for (size_t i = 0; i < SHA1_DIGEST_LENGTH; i++) {
95 out.appendFormat("%02x", digest[i]);
100 static void setDescriptor(InputDeviceIdentifier& identifier) {
101 // Compute a device descriptor that uniquely identifies the device.
102 // The descriptor is assumed to be a stable identifier. Its value should not
103 // change between reboots, reconnections, firmware updates or new releases of Android.
104 // Ideally, we also want the descriptor to be short and relatively opaque.
105 String8 rawDescriptor;
106 rawDescriptor.appendFormat(":%04x:%04x:", identifier.vendor, identifier.product);
107 if (!identifier.uniqueId.isEmpty()) {
108 rawDescriptor.append("uniqueId:");
109 rawDescriptor.append(identifier.uniqueId);
110 } if (identifier.vendor == 0 && identifier.product == 0) {
111 // If we don't know the vendor and product id, then the device is probably
112 // built-in so we need to rely on other information to uniquely identify
113 // the input device. Usually we try to avoid relying on the device name or
114 // location but for built-in input device, they are unlikely to ever change.
115 if (!identifier.name.isEmpty()) {
116 rawDescriptor.append("name:");
117 rawDescriptor.append(identifier.name);
118 } else if (!identifier.location.isEmpty()) {
119 rawDescriptor.append("location:");
120 rawDescriptor.append(identifier.location);
123 identifier.descriptor = sha1(rawDescriptor);
124 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.string(),
125 identifier.descriptor.string());
128 // --- Global Functions ---
130 uint32_t getAbsAxisUsage(int32_t axis, uint32_t deviceClasses) {
131 // Touch devices get dibs on touch-related axes.
132 if (deviceClasses & INPUT_DEVICE_CLASS_TOUCH) {
142 case ABS_MT_TOUCH_MAJOR:
143 case ABS_MT_TOUCH_MINOR:
144 case ABS_MT_WIDTH_MAJOR:
145 case ABS_MT_WIDTH_MINOR:
146 case ABS_MT_ORIENTATION:
147 case ABS_MT_POSITION_X:
148 case ABS_MT_POSITION_Y:
149 case ABS_MT_TOOL_TYPE:
151 case ABS_MT_TRACKING_ID:
152 case ABS_MT_PRESSURE:
153 case ABS_MT_DISTANCE:
154 return INPUT_DEVICE_CLASS_TOUCH;
158 // Joystick devices get the rest.
159 return deviceClasses & INPUT_DEVICE_CLASS_JOYSTICK;
162 // --- EventHub::Device ---
164 EventHub::Device::Device(int fd, int32_t id, const String8& path,
165 const InputDeviceIdentifier& identifier) :
167 fd(fd), id(id), path(path), identifier(identifier),
168 classes(0), configuration(NULL), virtualKeyMap(NULL),
169 ffEffectPlaying(false), ffEffectId(-1),
170 timestampOverrideSec(0), timestampOverrideUsec(0) {
171 memset(keyBitmask, 0, sizeof(keyBitmask));
172 memset(absBitmask, 0, sizeof(absBitmask));
173 memset(relBitmask, 0, sizeof(relBitmask));
174 memset(swBitmask, 0, sizeof(swBitmask));
175 memset(ledBitmask, 0, sizeof(ledBitmask));
176 memset(ffBitmask, 0, sizeof(ffBitmask));
177 memset(propBitmask, 0, sizeof(propBitmask));
180 EventHub::Device::~Device() {
182 delete configuration;
183 delete virtualKeyMap;
186 void EventHub::Device::close() {
196 const uint32_t EventHub::EPOLL_ID_INOTIFY;
197 const uint32_t EventHub::EPOLL_ID_WAKE;
198 const int EventHub::EPOLL_SIZE_HINT;
199 const int EventHub::EPOLL_MAX_EVENTS;
201 EventHub::EventHub(void) :
202 mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD), mNextDeviceId(1),
203 mOpeningDevices(0), mClosingDevices(0),
204 mNeedToSendFinishedDeviceScan(false),
205 mNeedToReopenDevices(false), mNeedToScanDevices(true),
206 mPendingEventCount(0), mPendingEventIndex(0), mPendingINotify(false) {
207 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
209 mEpollFd = epoll_create(EPOLL_SIZE_HINT);
210 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance. errno=%d", errno);
212 mINotifyFd = inotify_init();
213 int result = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
214 LOG_ALWAYS_FATAL_IF(result < 0, "Could not register INotify for %s. errno=%d",
217 struct epoll_event eventItem;
218 memset(&eventItem, 0, sizeof(eventItem));
219 eventItem.events = EPOLLIN;
220 eventItem.data.u32 = EPOLL_ID_INOTIFY;
221 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
222 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
225 result = pipe(wakeFds);
226 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
228 mWakeReadPipeFd = wakeFds[0];
229 mWakeWritePipeFd = wakeFds[1];
231 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
232 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
235 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
236 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
239 eventItem.data.u32 = EPOLL_ID_WAKE;
240 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
241 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
245 EventHub::~EventHub(void) {
246 closeAllDevicesLocked();
248 while (mClosingDevices) {
249 Device* device = mClosingDevices;
250 mClosingDevices = device->next;
256 ::close(mWakeReadPipeFd);
257 ::close(mWakeWritePipeFd);
259 release_wake_lock(WAKE_LOCK_ID);
262 InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
264 Device* device = getDeviceLocked(deviceId);
265 if (device == NULL) return InputDeviceIdentifier();
266 return device->identifier;
269 uint32_t EventHub::getDeviceClasses(int32_t deviceId) const {
271 Device* device = getDeviceLocked(deviceId);
272 if (device == NULL) return 0;
273 return device->classes;
276 void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
278 Device* device = getDeviceLocked(deviceId);
279 if (device && device->configuration) {
280 *outConfiguration = *device->configuration;
282 outConfiguration->clear();
286 status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
287 RawAbsoluteAxisInfo* outAxisInfo) const {
288 outAxisInfo->clear();
290 if (axis >= 0 && axis <= ABS_MAX) {
293 Device* device = getDeviceLocked(deviceId);
294 if (device && !device->isVirtual() && test_bit(axis, device->absBitmask)) {
295 struct input_absinfo info;
296 if(ioctl(device->fd, EVIOCGABS(axis), &info)) {
297 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d",
298 axis, device->identifier.name.string(), device->fd, errno);
302 if (info.minimum != info.maximum) {
303 outAxisInfo->valid = true;
304 outAxisInfo->minValue = info.minimum;
305 outAxisInfo->maxValue = info.maximum;
306 outAxisInfo->flat = info.flat;
307 outAxisInfo->fuzz = info.fuzz;
308 outAxisInfo->resolution = info.resolution;
316 bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
317 if (axis >= 0 && axis <= REL_MAX) {
320 Device* device = getDeviceLocked(deviceId);
322 return test_bit(axis, device->relBitmask);
328 bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
329 if (property >= 0 && property <= INPUT_PROP_MAX) {
332 Device* device = getDeviceLocked(deviceId);
334 return test_bit(property, device->propBitmask);
340 int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
341 if (scanCode >= 0 && scanCode <= KEY_MAX) {
344 Device* device = getDeviceLocked(deviceId);
345 if (device && !device->isVirtual() && test_bit(scanCode, device->keyBitmask)) {
346 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
347 memset(keyState, 0, sizeof(keyState));
348 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
349 return test_bit(scanCode, keyState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
353 return AKEY_STATE_UNKNOWN;
356 int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
359 Device* device = getDeviceLocked(deviceId);
360 if (device && !device->isVirtual() && device->keyMap.haveKeyLayout()) {
361 Vector<int32_t> scanCodes;
362 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode, &scanCodes);
363 if (scanCodes.size() != 0) {
364 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
365 memset(keyState, 0, sizeof(keyState));
366 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
367 for (size_t i = 0; i < scanCodes.size(); i++) {
368 int32_t sc = scanCodes.itemAt(i);
369 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, keyState)) {
370 return AKEY_STATE_DOWN;
373 return AKEY_STATE_UP;
377 return AKEY_STATE_UNKNOWN;
380 int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
381 if (sw >= 0 && sw <= SW_MAX) {
384 Device* device = getDeviceLocked(deviceId);
385 if (device && !device->isVirtual() && test_bit(sw, device->swBitmask)) {
386 uint8_t swState[sizeof_bit_array(SW_MAX + 1)];
387 memset(swState, 0, sizeof(swState));
388 if (ioctl(device->fd, EVIOCGSW(sizeof(swState)), swState) >= 0) {
389 return test_bit(sw, swState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
393 return AKEY_STATE_UNKNOWN;
396 status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
399 if (axis >= 0 && axis <= ABS_MAX) {
402 Device* device = getDeviceLocked(deviceId);
403 if (device && !device->isVirtual() && test_bit(axis, device->absBitmask)) {
404 struct input_absinfo info;
405 if(ioctl(device->fd, EVIOCGABS(axis), &info)) {
406 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d",
407 axis, device->identifier.name.string(), device->fd, errno);
411 *outValue = info.value;
418 bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes,
419 const int32_t* keyCodes, uint8_t* outFlags) const {
422 Device* device = getDeviceLocked(deviceId);
423 if (device && device->keyMap.haveKeyLayout()) {
424 Vector<int32_t> scanCodes;
425 for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) {
428 status_t err = device->keyMap.keyLayoutMap->findScanCodesForKey(
429 keyCodes[codeIndex], &scanCodes);
431 // check the possible scan codes identified by the layout map against the
432 // map of codes actually emitted by the driver
433 for (size_t sc = 0; sc < scanCodes.size(); sc++) {
434 if (test_bit(scanCodes[sc], device->keyBitmask)) {
435 outFlags[codeIndex] = 1;
446 status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode,
447 int32_t* outKeycode, uint32_t* outFlags) const {
449 Device* device = getDeviceLocked(deviceId);
452 // Check the key character map first.
453 sp<KeyCharacterMap> kcm = device->getKeyCharacterMap();
455 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
461 // Check the key layout next.
462 if (device->keyMap.haveKeyLayout()) {
463 if (!device->keyMap.keyLayoutMap->mapKey(
464 scanCode, usageCode, outKeycode, outFlags)) {
472 return NAME_NOT_FOUND;
475 status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
477 Device* device = getDeviceLocked(deviceId);
479 if (device && device->keyMap.haveKeyLayout()) {
480 status_t err = device->keyMap.keyLayoutMap->mapAxis(scanCode, outAxisInfo);
481 if (err == NO_ERROR) {
486 return NAME_NOT_FOUND;
489 void EventHub::setExcludedDevices(const Vector<String8>& devices) {
492 mExcludedDevices = devices;
495 bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
497 Device* device = getDeviceLocked(deviceId);
498 if (device && scanCode >= 0 && scanCode <= KEY_MAX) {
499 if (test_bit(scanCode, device->keyBitmask)) {
506 bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
508 Device* device = getDeviceLocked(deviceId);
509 if (device && led >= 0 && led <= LED_MAX) {
510 if (test_bit(led, device->ledBitmask)) {
517 void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
519 Device* device = getDeviceLocked(deviceId);
520 if (device && !device->isVirtual() && led >= 0 && led <= LED_MAX) {
521 struct input_event ev;
526 ev.value = on ? 1 : 0;
530 nWrite = write(device->fd, &ev, sizeof(struct input_event));
531 } while (nWrite == -1 && errno == EINTR);
535 void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
536 Vector<VirtualKeyDefinition>& outVirtualKeys) const {
537 outVirtualKeys.clear();
540 Device* device = getDeviceLocked(deviceId);
541 if (device && device->virtualKeyMap) {
542 outVirtualKeys.appendVector(device->virtualKeyMap->getVirtualKeys());
546 sp<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
548 Device* device = getDeviceLocked(deviceId);
550 return device->getKeyCharacterMap();
555 bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId,
556 const sp<KeyCharacterMap>& map) {
558 Device* device = getDeviceLocked(deviceId);
560 if (map != device->overlayKeyMap) {
561 device->overlayKeyMap = map;
562 device->combinedKeyMap = KeyCharacterMap::combine(
563 device->keyMap.keyCharacterMap, map);
570 void EventHub::vibrate(int32_t deviceId, nsecs_t duration) {
572 Device* device = getDeviceLocked(deviceId);
573 if (device && !device->isVirtual()) {
575 memset(&effect, 0, sizeof(effect));
576 effect.type = FF_RUMBLE;
577 effect.id = device->ffEffectId;
578 effect.u.rumble.strong_magnitude = 0xc000;
579 effect.u.rumble.weak_magnitude = 0xc000;
580 effect.replay.length = (duration + 999999LL) / 1000000LL;
581 effect.replay.delay = 0;
582 if (ioctl(device->fd, EVIOCSFF, &effect)) {
583 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
584 device->identifier.name.string(), errno);
587 device->ffEffectId = effect.id;
589 struct input_event ev;
593 ev.code = device->ffEffectId;
595 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
596 ALOGW("Could not start force feedback effect on device %s due to error %d.",
597 device->identifier.name.string(), errno);
600 device->ffEffectPlaying = true;
604 void EventHub::cancelVibrate(int32_t deviceId) {
606 Device* device = getDeviceLocked(deviceId);
607 if (device && !device->isVirtual()) {
608 if (device->ffEffectPlaying) {
609 device->ffEffectPlaying = false;
611 struct input_event ev;
615 ev.code = device->ffEffectId;
617 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
618 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
619 device->identifier.name.string(), errno);
626 EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
627 if (deviceId == BUILT_IN_KEYBOARD_ID) {
628 deviceId = mBuiltInKeyboardId;
630 ssize_t index = mDevices.indexOfKey(deviceId);
631 return index >= 0 ? mDevices.valueAt(index) : NULL;
634 EventHub::Device* EventHub::getDeviceByPathLocked(const char* devicePath) const {
635 for (size_t i = 0; i < mDevices.size(); i++) {
636 Device* device = mDevices.valueAt(i);
637 if (device->path == devicePath) {
644 size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
645 ALOG_ASSERT(bufferSize >= 1);
649 struct input_event readBuffer[bufferSize];
651 RawEvent* event = buffer;
652 size_t capacity = bufferSize;
655 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
657 // Reopen input devices if needed.
658 if (mNeedToReopenDevices) {
659 mNeedToReopenDevices = false;
661 ALOGI("Reopening all input devices due to a configuration change.");
663 closeAllDevicesLocked();
664 mNeedToScanDevices = true;
665 break; // return to the caller before we actually rescan
668 // Report any devices that had last been added/removed.
669 while (mClosingDevices) {
670 Device* device = mClosingDevices;
671 ALOGV("Reporting device closed: id=%d, name=%s\n",
672 device->id, device->path.string());
673 mClosingDevices = device->next;
675 event->deviceId = device->id == mBuiltInKeyboardId ? BUILT_IN_KEYBOARD_ID : device->id;
676 event->type = DEVICE_REMOVED;
679 mNeedToSendFinishedDeviceScan = true;
680 if (--capacity == 0) {
685 if (mNeedToScanDevices) {
686 mNeedToScanDevices = false;
688 mNeedToSendFinishedDeviceScan = true;
691 while (mOpeningDevices != NULL) {
692 Device* device = mOpeningDevices;
693 ALOGV("Reporting device opened: id=%d, name=%s\n",
694 device->id, device->path.string());
695 mOpeningDevices = device->next;
697 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
698 event->type = DEVICE_ADDED;
700 mNeedToSendFinishedDeviceScan = true;
701 if (--capacity == 0) {
706 if (mNeedToSendFinishedDeviceScan) {
707 mNeedToSendFinishedDeviceScan = false;
709 event->type = FINISHED_DEVICE_SCAN;
711 if (--capacity == 0) {
718 int fd_vt = open("/dev/tty0", O_RDWR | O_SYNC);
720 ioctl(fd_vt, VT_GETSTATE, &vs);
724 // Grab the next input event.
725 bool deviceChanged = false;
726 while (mPendingEventIndex < mPendingEventCount) {
727 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
728 if (eventItem.data.u32 == EPOLL_ID_INOTIFY) {
729 if (eventItem.events & EPOLLIN) {
730 mPendingINotify = true;
732 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
737 if (eventItem.data.u32 == EPOLL_ID_WAKE) {
738 if (eventItem.events & EPOLLIN) {
739 ALOGV("awoken after wake()");
744 nRead = read(mWakeReadPipeFd, buffer, sizeof(buffer));
745 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(buffer));
747 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
753 ssize_t deviceIndex = mDevices.indexOfKey(eventItem.data.u32);
754 if (deviceIndex < 0) {
755 ALOGW("Received unexpected epoll event 0x%08x for unknown device id %d.",
756 eventItem.events, eventItem.data.u32);
760 Device* device = mDevices.valueAt(deviceIndex);
761 if (eventItem.events & EPOLLIN) {
762 int32_t readSize = read(device->fd, readBuffer,
763 sizeof(struct input_event) * capacity);
764 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
765 // Device was removed before INotify noticed.
766 ALOGW("could not get event, removed? (fd: %d size: %d bufferSize: %d "
767 "capacity: %d errno: %d)\n",
768 device->fd, readSize, bufferSize, capacity, errno);
769 deviceChanged = true;
770 closeDeviceLocked(device);
771 } else if (readSize < 0) {
772 if (errno != EAGAIN && errno != EINTR) {
773 ALOGW("could not get event (errno=%d)", errno);
775 } else if ((readSize % sizeof(struct input_event)) != 0) {
776 ALOGE("could not get event (wrong size: %d)", readSize);
779 if (vs.v_active != android_vt) {
780 ALOGV("Skip a non Android VT event");
784 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
786 size_t count = size_t(readSize) / sizeof(struct input_event);
787 for (size_t i = 0; i < count; i++) {
788 struct input_event& iev = readBuffer[i];
789 ALOGV("%s got: time=%d.%06d, type=%d, code=%d, value=%d",
790 device->path.string(),
791 (int) iev.time.tv_sec, (int) iev.time.tv_usec,
792 iev.type, iev.code, iev.value);
794 // Some input devices may have a better concept of the time
795 // when an input event was actually generated than the kernel
796 // which simply timestamps all events on entry to evdev.
797 // This is a custom Android extension of the input protocol
798 // mainly intended for use with uinput based device drivers.
799 if (iev.type == EV_MSC) {
800 if (iev.code == MSC_ANDROID_TIME_SEC) {
801 device->timestampOverrideSec = iev.value;
803 } else if (iev.code == MSC_ANDROID_TIME_USEC) {
804 device->timestampOverrideUsec = iev.value;
808 if (device->timestampOverrideSec || device->timestampOverrideUsec) {
809 iev.time.tv_sec = device->timestampOverrideSec;
810 iev.time.tv_usec = device->timestampOverrideUsec;
811 if (iev.type == EV_SYN && iev.code == SYN_REPORT) {
812 device->timestampOverrideSec = 0;
813 device->timestampOverrideUsec = 0;
815 ALOGV("applied override time %d.%06d",
816 int(iev.time.tv_sec), int(iev.time.tv_usec));
819 #ifdef HAVE_POSIX_CLOCKS
820 // Use the time specified in the event instead of the current time
821 // so that downstream code can get more accurate estimates of
822 // event dispatch latency from the time the event is enqueued onto
823 // the evdev client buffer.
825 // The event's timestamp fortuitously uses the same monotonic clock
826 // time base as the rest of Android. The kernel event device driver
827 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
828 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
829 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
830 // system call that also queries ktime_get_ts().
831 event->when = nsecs_t(iev.time.tv_sec) * 1000000000LL
832 + nsecs_t(iev.time.tv_usec) * 1000LL;
833 ALOGV("event time %lld, now %lld", event->when, now);
835 // Bug 7291243: Add a guard in case the kernel generates timestamps
836 // that appear to be far into the future because they were generated
837 // using the wrong clock source.
839 // This can happen because when the input device is initially opened
840 // it has a default clock source of CLOCK_REALTIME. Any input events
841 // enqueued right after the device is opened will have timestamps
842 // generated using CLOCK_REALTIME. We later set the clock source
843 // to CLOCK_MONOTONIC but it is already too late.
845 // Invalid input event timestamps can result in ANRs, crashes and
846 // and other issues that are hard to track down. We must not let them
847 // propagate through the system.
849 // Log a warning so that we notice the problem and recover gracefully.
850 if (event->when >= now + 10 * 1000000000LL) {
851 // Double-check. Time may have moved on.
852 nsecs_t time = systemTime(SYSTEM_TIME_MONOTONIC);
853 if (event->when > time) {
854 ALOGW("An input event from %s has a timestamp that appears to "
855 "have been generated using the wrong clock source "
856 "(expected CLOCK_MONOTONIC): "
857 "event time %lld, current time %lld, call time %lld. "
858 "Using current time instead.",
859 device->path.string(), event->when, time, now);
862 ALOGV("Event time is ok but failed the fast path and required "
863 "an extra call to systemTime: "
864 "event time %lld, current time %lld, call time %lld.",
865 event->when, time, now);
871 event->deviceId = deviceId;
872 event->type = iev.type;
873 event->code = iev.code;
874 event->value = iev.value;
879 // The result buffer is full. Reset the pending event index
880 // so we will try to read the device again on the next iteration.
881 mPendingEventIndex -= 1;
885 } else if (eventItem.events & EPOLLHUP) {
886 ALOGI("Removing device %s due to epoll hang-up event.",
887 device->identifier.name.string());
888 deviceChanged = true;
889 closeDeviceLocked(device);
891 ALOGW("Received unexpected epoll event 0x%08x for device %s.",
892 eventItem.events, device->identifier.name.string());
896 // readNotify() will modify the list of devices so this must be done after
897 // processing all other events to ensure that we read all remaining events
898 // before closing the devices.
899 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
900 mPendingINotify = false;
902 deviceChanged = true;
905 // Report added or removed devices immediately.
910 // Return now if we have collected any events or if we were explicitly awoken.
911 if (event != buffer || awoken) {
915 // Poll for events. Mind the wake lock dance!
916 // We hold a wake lock at all times except during epoll_wait(). This works due to some
917 // subtle choreography. When a device driver has pending (unread) events, it acquires
918 // a kernel wake lock. However, once the last pending event has been read, the device
919 // driver will release the kernel wake lock. To prevent the system from going to sleep
920 // when this happens, the EventHub holds onto its own user wake lock while the client
921 // is processing events. Thus the system can only sleep if there are no events
922 // pending or currently being processed.
924 // The timeout is advisory only. If the device is asleep, it will not wake just to
925 // service the timeout.
926 mPendingEventIndex = 0;
928 mLock.unlock(); // release lock before poll, must be before release_wake_lock
929 release_wake_lock(WAKE_LOCK_ID);
931 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
933 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
934 mLock.lock(); // reacquire lock after poll, must be after acquire_wake_lock
936 if (pollResult == 0) {
938 mPendingEventCount = 0;
942 if (pollResult < 0) {
943 // An error occurred.
944 mPendingEventCount = 0;
946 // Sleep after errors to avoid locking up the system.
947 // Hopefully the error is transient.
948 if (errno != EINTR) {
949 ALOGW("poll failed (errno=%d)\n", errno);
953 // Some events occurred.
954 mPendingEventCount = size_t(pollResult);
958 // All done, return the number of events we read.
959 return event - buffer;
962 void EventHub::wake() {
963 ALOGV("wake() called");
967 nWrite = write(mWakeWritePipeFd, "W", 1);
968 } while (nWrite == -1 && errno == EINTR);
970 if (nWrite != 1 && errno != EAGAIN) {
971 ALOGW("Could not write wake signal, errno=%d", errno);
975 void EventHub::scanDevicesLocked() {
976 status_t res = scanDirLocked(DEVICE_PATH);
978 ALOGE("scan dir failed for %s\n", DEVICE_PATH);
980 if (mDevices.indexOfKey(VIRTUAL_KEYBOARD_ID) < 0) {
981 createVirtualKeyboardLocked();
985 // ----------------------------------------------------------------------------
987 static bool containsNonZeroByte(const uint8_t* array, uint32_t startIndex, uint32_t endIndex) {
988 const uint8_t* end = array + endIndex;
990 while (array != end) {
991 if (*(array++) != 0) {
998 static const int32_t GAMEPAD_KEYCODES[] = {
999 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C,
1000 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z,
1001 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1,
1002 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2,
1003 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR,
1004 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE,
1005 AKEYCODE_BUTTON_1, AKEYCODE_BUTTON_2, AKEYCODE_BUTTON_3, AKEYCODE_BUTTON_4,
1006 AKEYCODE_BUTTON_5, AKEYCODE_BUTTON_6, AKEYCODE_BUTTON_7, AKEYCODE_BUTTON_8,
1007 AKEYCODE_BUTTON_9, AKEYCODE_BUTTON_10, AKEYCODE_BUTTON_11, AKEYCODE_BUTTON_12,
1008 AKEYCODE_BUTTON_13, AKEYCODE_BUTTON_14, AKEYCODE_BUTTON_15, AKEYCODE_BUTTON_16,
1011 status_t EventHub::openDeviceLocked(const char *devicePath) {
1014 ALOGV("Opening device: %s", devicePath);
1016 int fd = open(devicePath, O_RDWR | O_CLOEXEC);
1018 ALOGE("could not open %s, %s\n", devicePath, strerror(errno));
1022 InputDeviceIdentifier identifier;
1025 if(ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
1026 //fprintf(stderr, "could not get device name for %s, %s\n", devicePath, strerror(errno));
1028 buffer[sizeof(buffer) - 1] = '\0';
1029 identifier.name.setTo(buffer);
1032 // Check to see if the device is on our excluded list
1033 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
1034 const String8& item = mExcludedDevices.itemAt(i);
1035 if (identifier.name == item) {
1036 ALOGI("ignoring event id %s driver %s\n", devicePath, item.string());
1042 // Get device driver version.
1044 if(ioctl(fd, EVIOCGVERSION, &driverVersion)) {
1045 ALOGE("could not get driver version for %s, %s\n", devicePath, strerror(errno));
1050 // Get device identifier.
1051 struct input_id inputId;
1052 if(ioctl(fd, EVIOCGID, &inputId)) {
1053 ALOGE("could not get device input id for %s, %s\n", devicePath, strerror(errno));
1057 identifier.bus = inputId.bustype;
1058 identifier.product = inputId.product;
1059 identifier.vendor = inputId.vendor;
1060 identifier.version = inputId.version;
1062 // Get device physical location.
1063 if(ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
1064 //fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
1066 buffer[sizeof(buffer) - 1] = '\0';
1067 identifier.location.setTo(buffer);
1070 // Get device unique id.
1071 if(ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
1072 //fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
1074 buffer[sizeof(buffer) - 1] = '\0';
1075 identifier.uniqueId.setTo(buffer);
1078 // Fill in the descriptor.
1079 setDescriptor(identifier);
1081 // Make file descriptor non-blocking for use with poll().
1082 if (fcntl(fd, F_SETFL, O_NONBLOCK)) {
1083 ALOGE("Error %d making device file descriptor non-blocking.", errno);
1088 // Allocate device. (The device object takes ownership of the fd at this point.)
1089 int32_t deviceId = mNextDeviceId++;
1090 Device* device = new Device(fd, deviceId, String8(devicePath), identifier);
1092 ALOGV("add device %d: %s\n", deviceId, devicePath);
1093 ALOGV(" bus: %04x\n"
1097 identifier.bus, identifier.vendor, identifier.product, identifier.version);
1098 ALOGV(" name: \"%s\"\n", identifier.name.string());
1099 ALOGV(" location: \"%s\"\n", identifier.location.string());
1100 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.string());
1101 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.string());
1102 ALOGV(" driver: v%d.%d.%d\n",
1103 driverVersion >> 16, (driverVersion >> 8) & 0xff, driverVersion & 0xff);
1105 // Load the configuration file for the device.
1106 loadConfigurationLocked(device);
1108 // Figure out the kinds of events the device reports.
1109 ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(device->keyBitmask)), device->keyBitmask);
1110 ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(device->absBitmask)), device->absBitmask);
1111 ioctl(fd, EVIOCGBIT(EV_REL, sizeof(device->relBitmask)), device->relBitmask);
1112 ioctl(fd, EVIOCGBIT(EV_SW, sizeof(device->swBitmask)), device->swBitmask);
1113 ioctl(fd, EVIOCGBIT(EV_LED, sizeof(device->ledBitmask)), device->ledBitmask);
1114 ioctl(fd, EVIOCGBIT(EV_FF, sizeof(device->ffBitmask)), device->ffBitmask);
1115 ioctl(fd, EVIOCGPROP(sizeof(device->propBitmask)), device->propBitmask);
1117 // See if this is a keyboard. Ignore everything in the button range except for
1118 // joystick and gamepad buttons which are handled like keyboards for the most part.
1119 bool haveKeyboardKeys = containsNonZeroByte(device->keyBitmask, 0, sizeof_bit_array(BTN_MISC))
1120 || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(KEY_OK),
1121 sizeof_bit_array(KEY_MAX + 1));
1122 bool haveGamepadButtons = containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_MISC),
1123 sizeof_bit_array(BTN_MOUSE))
1124 || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_JOYSTICK),
1125 sizeof_bit_array(BTN_DIGI));
1126 if (haveKeyboardKeys || haveGamepadButtons) {
1127 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1130 // See if this is a cursor device such as a trackball or mouse.
1131 if (test_bit(BTN_MOUSE, device->keyBitmask)
1132 && test_bit(REL_X, device->relBitmask)
1133 && test_bit(REL_Y, device->relBitmask)) {
1134 device->classes |= INPUT_DEVICE_CLASS_CURSOR;
1137 // See if this is a touch pad.
1138 // Is this a new modern multi-touch driver?
1139 if (test_bit(ABS_MT_POSITION_X, device->absBitmask)
1140 && test_bit(ABS_MT_POSITION_Y, device->absBitmask)) {
1141 // Some joysticks such as the PS3 controller report axes that conflict
1142 // with the ABS_MT range. Try to confirm that the device really is
1144 if (test_bit(BTN_TOUCH, device->keyBitmask) || !haveGamepadButtons) {
1145 device->classes |= INPUT_DEVICE_CLASS_TOUCH | INPUT_DEVICE_CLASS_TOUCH_MT;
1147 // Is this an old style single-touch driver?
1148 } else if (test_bit(BTN_TOUCH, device->keyBitmask)
1149 && test_bit(ABS_X, device->absBitmask)
1150 && test_bit(ABS_Y, device->absBitmask)) {
1151 device->classes |= INPUT_DEVICE_CLASS_TOUCH;
1154 // See if this device is a joystick.
1155 // Assumes that joysticks always have gamepad buttons in order to distinguish them
1156 // from other devices such as accelerometers that also have absolute axes.
1157 if (haveGamepadButtons) {
1158 uint32_t assumedClasses = device->classes | INPUT_DEVICE_CLASS_JOYSTICK;
1159 for (int i = 0; i <= ABS_MAX; i++) {
1160 if (test_bit(i, device->absBitmask)
1161 && (getAbsAxisUsage(i, assumedClasses) & INPUT_DEVICE_CLASS_JOYSTICK)) {
1162 device->classes = assumedClasses;
1168 // Check whether this device has switches.
1169 for (int i = 0; i <= SW_MAX; i++) {
1170 if (test_bit(i, device->swBitmask)) {
1171 device->classes |= INPUT_DEVICE_CLASS_SWITCH;
1176 // Check whether this device supports the vibrator.
1177 if (test_bit(FF_RUMBLE, device->ffBitmask)) {
1178 device->classes |= INPUT_DEVICE_CLASS_VIBRATOR;
1181 // Configure virtual keys.
1182 if ((device->classes & INPUT_DEVICE_CLASS_TOUCH)) {
1183 // Load the virtual keys for the touch screen, if any.
1184 // We do this now so that we can make sure to load the keymap if necessary.
1185 status_t status = loadVirtualKeyMapLocked(device);
1187 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1191 // Load the key map.
1192 // We need to do this for joysticks too because the key layout may specify axes.
1193 status_t keyMapStatus = NAME_NOT_FOUND;
1194 if (device->classes & (INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_JOYSTICK)) {
1195 // Load the keymap for the device.
1196 keyMapStatus = loadKeyMapLocked(device);
1199 // Configure the keyboard, gamepad or virtual keyboard.
1200 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1201 // Register the keyboard as a built-in keyboard if it is eligible.
1203 && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD
1204 && isEligibleBuiltInKeyboard(device->identifier,
1205 device->configuration, &device->keyMap)) {
1206 mBuiltInKeyboardId = device->id;
1209 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
1210 if (hasKeycodeLocked(device, AKEYCODE_Q)) {
1211 device->classes |= INPUT_DEVICE_CLASS_ALPHAKEY;
1214 // See if this device has a DPAD.
1215 if (hasKeycodeLocked(device, AKEYCODE_DPAD_UP) &&
1216 hasKeycodeLocked(device, AKEYCODE_DPAD_DOWN) &&
1217 hasKeycodeLocked(device, AKEYCODE_DPAD_LEFT) &&
1218 hasKeycodeLocked(device, AKEYCODE_DPAD_RIGHT) &&
1219 hasKeycodeLocked(device, AKEYCODE_DPAD_CENTER)) {
1220 device->classes |= INPUT_DEVICE_CLASS_DPAD;
1223 // See if this device has a gamepad.
1224 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES)/sizeof(GAMEPAD_KEYCODES[0]); i++) {
1225 if (hasKeycodeLocked(device, GAMEPAD_KEYCODES[i])) {
1226 device->classes |= INPUT_DEVICE_CLASS_GAMEPAD;
1231 // Disable kernel key repeat since we handle it ourselves
1232 unsigned int repeatRate[] = {0,0};
1233 if (ioctl(fd, EVIOCSREP, repeatRate)) {
1234 ALOGW("Unable to disable kernel key repeat for %s: %s", devicePath, strerror(errno));
1238 // If the device isn't recognized as something we handle, don't monitor it.
1239 if (device->classes == 0) {
1240 ALOGV("Dropping device: id=%d, path='%s', name='%s'",
1241 deviceId, devicePath, device->identifier.name.string());
1246 // Determine whether the device is external or internal.
1247 if (isExternalDeviceLocked(device)) {
1248 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL;
1251 // Register with epoll.
1252 struct epoll_event eventItem;
1253 memset(&eventItem, 0, sizeof(eventItem));
1254 eventItem.events = EPOLLIN;
1255 eventItem.data.u32 = deviceId;
1256 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1257 ALOGE("Could not add device fd to epoll instance. errno=%d", errno);
1262 // Enable wake-lock behavior on kernels that support it.
1263 // TODO: Only need this for devices that can really wake the system.
1264 bool usingSuspendBlockIoctl = !ioctl(fd, EVIOCSSUSPENDBLOCK, 1);
1266 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
1267 // associated with input events. This is important because the input system
1268 // uses the timestamps extensively and assumes they were recorded using the monotonic
1271 // In older kernel, before Linux 3.4, there was no way to tell the kernel which
1272 // clock to use to input event timestamps. The standard kernel behavior was to
1273 // record a real time timestamp, which isn't what we want. Android kernels therefore
1274 // contained a patch to the evdev_event() function in drivers/input/evdev.c to
1275 // replace the call to do_gettimeofday() with ktime_get_ts() to cause the monotonic
1276 // clock to be used instead of the real time clock.
1278 // As of Linux 3.4, there is a new EVIOCSCLOCKID ioctl to set the desired clock.
1279 // Therefore, we no longer require the Android-specific kernel patch described above
1280 // as long as we make sure to set select the monotonic clock. We do that here.
1281 int clockId = CLOCK_MONOTONIC;
1282 bool usingClockIoctl = !ioctl(fd, EVIOCSCLOCKID, &clockId);
1284 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=0x%x, "
1285 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, "
1286 "usingSuspendBlockIoctl=%s, usingClockIoctl=%s",
1287 deviceId, fd, devicePath, device->identifier.name.string(),
1289 device->configurationFile.string(),
1290 device->keyMap.keyLayoutFile.string(),
1291 device->keyMap.keyCharacterMapFile.string(),
1292 toString(mBuiltInKeyboardId == deviceId),
1293 toString(usingSuspendBlockIoctl), toString(usingClockIoctl));
1295 addDeviceLocked(device);
1299 void EventHub::createVirtualKeyboardLocked() {
1300 InputDeviceIdentifier identifier;
1301 identifier.name = "Virtual";
1302 identifier.uniqueId = "<virtual>";
1303 setDescriptor(identifier);
1305 Device* device = new Device(-1, VIRTUAL_KEYBOARD_ID, String8("<virtual>"), identifier);
1306 device->classes = INPUT_DEVICE_CLASS_KEYBOARD
1307 | INPUT_DEVICE_CLASS_ALPHAKEY
1308 | INPUT_DEVICE_CLASS_DPAD
1309 | INPUT_DEVICE_CLASS_VIRTUAL;
1310 loadKeyMapLocked(device);
1311 addDeviceLocked(device);
1314 void EventHub::addDeviceLocked(Device* device) {
1315 mDevices.add(device->id, device);
1316 device->next = mOpeningDevices;
1317 mOpeningDevices = device;
1320 void EventHub::loadConfigurationLocked(Device* device) {
1321 device->configurationFile = getInputDeviceConfigurationFilePathByDeviceIdentifier(
1322 device->identifier, INPUT_DEVICE_CONFIGURATION_FILE_TYPE_CONFIGURATION);
1323 if (device->configurationFile.isEmpty()) {
1324 ALOGD("No input device configuration file found for device '%s'.",
1325 device->identifier.name.string());
1327 status_t status = PropertyMap::load(device->configurationFile,
1328 &device->configuration);
1330 ALOGE("Error loading input device configuration file for device '%s'. "
1331 "Using default configuration.",
1332 device->identifier.name.string());
1337 status_t EventHub::loadVirtualKeyMapLocked(Device* device) {
1338 // The virtual key map is supplied by the kernel as a system board property file.
1340 path.append("/sys/board_properties/virtualkeys.");
1341 path.append(device->identifier.name);
1342 if (access(path.string(), R_OK)) {
1343 return NAME_NOT_FOUND;
1345 return VirtualKeyMap::load(path, &device->virtualKeyMap);
1348 status_t EventHub::loadKeyMapLocked(Device* device) {
1349 return device->keyMap.load(device->identifier, device->configuration);
1352 bool EventHub::isExternalDeviceLocked(Device* device) {
1353 if (device->configuration) {
1355 if (device->configuration->tryGetProperty(String8("device.internal"), value)) {
1359 return device->identifier.bus == BUS_USB || device->identifier.bus == BUS_BLUETOOTH;
1362 bool EventHub::hasKeycodeLocked(Device* device, int keycode) const {
1363 if (!device->keyMap.haveKeyLayout() || !device->keyBitmask) {
1367 Vector<int32_t> scanCodes;
1368 device->keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes);
1369 const size_t N = scanCodes.size();
1370 for (size_t i=0; i<N && i<=KEY_MAX; i++) {
1371 int32_t sc = scanCodes.itemAt(i);
1372 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, device->keyBitmask)) {
1380 status_t EventHub::closeDeviceByPathLocked(const char *devicePath) {
1381 Device* device = getDeviceByPathLocked(devicePath);
1383 closeDeviceLocked(device);
1386 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath);
1390 void EventHub::closeAllDevicesLocked() {
1391 while (mDevices.size() > 0) {
1392 closeDeviceLocked(mDevices.valueAt(mDevices.size() - 1));
1396 void EventHub::closeDeviceLocked(Device* device) {
1397 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=0x%x\n",
1398 device->path.string(), device->identifier.name.string(), device->id,
1399 device->fd, device->classes);
1401 if (device->id == mBuiltInKeyboardId) {
1402 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
1403 device->path.string(), mBuiltInKeyboardId);
1404 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
1407 if (!device->isVirtual()) {
1408 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, device->fd, NULL)) {
1409 ALOGW("Could not remove device fd from epoll instance. errno=%d", errno);
1413 mDevices.removeItem(device->id);
1416 // Unlink for opening devices list if it is present.
1417 Device* pred = NULL;
1419 for (Device* entry = mOpeningDevices; entry != NULL; ) {
1420 if (entry == device) {
1425 entry = entry->next;
1428 // Unlink the device from the opening devices list then delete it.
1429 // We don't need to tell the client that the device was closed because
1430 // it does not even know it was opened in the first place.
1431 ALOGI("Device %s was immediately closed after opening.", device->path.string());
1433 pred->next = device->next;
1435 mOpeningDevices = device->next;
1439 // Link into closing devices list.
1440 // The device will be deleted later after we have informed the client.
1441 device->next = mClosingDevices;
1442 mClosingDevices = device;
1446 status_t EventHub::readNotifyLocked() {
1448 char devname[PATH_MAX];
1450 char event_buf[512];
1453 struct inotify_event *event;
1455 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
1456 res = read(mINotifyFd, event_buf, sizeof(event_buf));
1457 if(res < (int)sizeof(*event)) {
1460 ALOGW("could not get event, %s\n", strerror(errno));
1463 //printf("got %d bytes of event information\n", res);
1465 strcpy(devname, DEVICE_PATH);
1466 filename = devname + strlen(devname);
1469 while(res >= (int)sizeof(*event)) {
1470 event = (struct inotify_event *)(event_buf + event_pos);
1471 //printf("%d: %08x \"%s\"\n", event->wd, event->mask, event->len ? event->name : "");
1473 strcpy(filename, event->name);
1474 if(event->mask & IN_CREATE) {
1475 openDeviceLocked(devname);
1477 ALOGI("Removing device '%s' due to inotify event\n", devname);
1478 closeDeviceByPathLocked(devname);
1481 event_size = sizeof(*event) + event->len;
1483 event_pos += event_size;
1488 status_t EventHub::scanDirLocked(const char *dirname)
1490 char devname[PATH_MAX];
1494 dir = opendir(dirname);
1497 strcpy(devname, dirname);
1498 filename = devname + strlen(devname);
1500 while((de = readdir(dir))) {
1501 if(de->d_name[0] == '.' &&
1502 (de->d_name[1] == '\0' ||
1503 (de->d_name[1] == '.' && de->d_name[2] == '\0')))
1505 strcpy(filename, de->d_name);
1506 openDeviceLocked(devname);
1512 void EventHub::requestReopenDevices() {
1513 ALOGV("requestReopenDevices() called");
1515 AutoMutex _l(mLock);
1516 mNeedToReopenDevices = true;
1519 void EventHub::dump(String8& dump) {
1520 dump.append("Event Hub State:\n");
1523 AutoMutex _l(mLock);
1525 dump.appendFormat(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
1527 dump.append(INDENT "Devices:\n");
1529 for (size_t i = 0; i < mDevices.size(); i++) {
1530 const Device* device = mDevices.valueAt(i);
1531 if (mBuiltInKeyboardId == device->id) {
1532 dump.appendFormat(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
1533 device->id, device->identifier.name.string());
1535 dump.appendFormat(INDENT2 "%d: %s\n", device->id,
1536 device->identifier.name.string());
1538 dump.appendFormat(INDENT3 "Classes: 0x%08x\n", device->classes);
1539 dump.appendFormat(INDENT3 "Path: %s\n", device->path.string());
1540 dump.appendFormat(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.string());
1541 dump.appendFormat(INDENT3 "Location: %s\n", device->identifier.location.string());
1542 dump.appendFormat(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.string());
1543 dump.appendFormat(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
1544 "product=0x%04x, version=0x%04x\n",
1545 device->identifier.bus, device->identifier.vendor,
1546 device->identifier.product, device->identifier.version);
1547 dump.appendFormat(INDENT3 "KeyLayoutFile: %s\n",
1548 device->keyMap.keyLayoutFile.string());
1549 dump.appendFormat(INDENT3 "KeyCharacterMapFile: %s\n",
1550 device->keyMap.keyCharacterMapFile.string());
1551 dump.appendFormat(INDENT3 "ConfigurationFile: %s\n",
1552 device->configurationFile.string());
1553 dump.appendFormat(INDENT3 "HaveKeyboardLayoutOverlay: %s\n",
1554 toString(device->overlayKeyMap != NULL));
1559 void EventHub::monitor() {
1560 // Acquire and release the lock to ensure that the event hub has not deadlocked.
1566 }; // namespace android