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.
27 #include <sys/epoll.h>
28 #include <sys/limits.h>
29 #include <sys/inotify.h>
30 #include <sys/ioctl.h>
31 #include <sys/utsname.h>
34 #define LOG_TAG "EventHub"
36 // #define LOG_NDEBUG 0
40 #include <hardware_legacy/power.h>
42 #include <cutils/properties.h>
43 #include <openssl/sha.h>
44 #include <utils/Log.h>
45 #include <utils/Timers.h>
46 #include <utils/threads.h>
47 #include <utils/Errors.h>
49 #include <input/KeyLayoutMap.h>
50 #include <input/KeyCharacterMap.h>
51 #include <input/VirtualKeyMap.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)
71 static const char *WAKE_LOCK_ID = "KeyEvents";
72 static const char *DEVICE_PATH = "/dev/input";
74 /* return the larger integer */
75 static inline int max(int v1, int v2)
77 return (v1 > v2) ? v1 : v2;
80 static inline const char* toString(bool value) {
81 return value ? "true" : "false";
84 static String8 sha1(const String8& in) {
87 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.string()), in.size());
88 u_char digest[SHA_DIGEST_LENGTH];
89 SHA1_Final(digest, &ctx);
92 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
93 out.appendFormat("%02x", digest[i]);
98 static void getLinuxRelease(int* major, int* minor) {
100 if (uname(&info) || sscanf(info.release, "%d.%d", major, minor) <= 0) {
101 *major = 0, *minor = 0;
102 ALOGE("Could not get linux version: %s", strerror(errno));
106 // --- Global Functions ---
108 uint32_t getAbsAxisUsage(int32_t axis, uint32_t deviceClasses) {
109 // Touch devices get dibs on touch-related axes.
110 if (deviceClasses & INPUT_DEVICE_CLASS_TOUCH) {
120 case ABS_MT_TOUCH_MAJOR:
121 case ABS_MT_TOUCH_MINOR:
122 case ABS_MT_WIDTH_MAJOR:
123 case ABS_MT_WIDTH_MINOR:
124 case ABS_MT_ORIENTATION:
125 case ABS_MT_POSITION_X:
126 case ABS_MT_POSITION_Y:
127 case ABS_MT_TOOL_TYPE:
129 case ABS_MT_TRACKING_ID:
130 case ABS_MT_PRESSURE:
131 case ABS_MT_DISTANCE:
132 return INPUT_DEVICE_CLASS_TOUCH;
136 // External stylus gets the pressure axis
137 if (deviceClasses & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
138 if (axis == ABS_PRESSURE) {
139 return INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
143 // Joystick devices get the rest.
144 return deviceClasses & INPUT_DEVICE_CLASS_JOYSTICK;
147 // --- EventHub::Device ---
149 EventHub::Device::Device(int fd, int32_t id, const String8& path,
150 const InputDeviceIdentifier& identifier) :
152 fd(fd), id(id), path(path), identifier(identifier),
153 classes(0), configuration(NULL), virtualKeyMap(NULL),
154 ffEffectPlaying(false), ffEffectId(-1), controllerNumber(0),
155 timestampOverrideSec(0), timestampOverrideUsec(0), enabled(true),
157 memset(keyBitmask, 0, sizeof(keyBitmask));
158 memset(absBitmask, 0, sizeof(absBitmask));
159 memset(relBitmask, 0, sizeof(relBitmask));
160 memset(swBitmask, 0, sizeof(swBitmask));
161 memset(ledBitmask, 0, sizeof(ledBitmask));
162 memset(ffBitmask, 0, sizeof(ffBitmask));
163 memset(propBitmask, 0, sizeof(propBitmask));
166 EventHub::Device::~Device() {
168 delete configuration;
169 delete virtualKeyMap;
172 void EventHub::Device::close() {
179 status_t EventHub::Device::enable() {
180 fd = open(path, O_RDWR | O_CLOEXEC | O_NONBLOCK);
182 ALOGE("could not open %s, %s\n", path.string(), strerror(errno));
189 status_t EventHub::Device::disable() {
195 bool EventHub::Device::hasValidFd() {
196 return !isVirtual && enabled;
201 const uint32_t EventHub::EPOLL_ID_INOTIFY;
202 const uint32_t EventHub::EPOLL_ID_WAKE;
203 const int EventHub::EPOLL_SIZE_HINT;
204 const int EventHub::EPOLL_MAX_EVENTS;
206 EventHub::EventHub(void) :
207 mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD), mNextDeviceId(1), mControllerNumbers(),
208 mOpeningDevices(0), mClosingDevices(0),
209 mNeedToSendFinishedDeviceScan(false),
210 mNeedToReopenDevices(false), mNeedToScanDevices(true),
211 mPendingEventCount(0), mPendingEventIndex(0), mPendingINotify(false) {
212 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
214 mEpollFd = epoll_create(EPOLL_SIZE_HINT);
215 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance. errno=%d", errno);
217 mINotifyFd = inotify_init();
218 int result = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
219 LOG_ALWAYS_FATAL_IF(result < 0, "Could not register INotify for %s. errno=%d",
222 struct epoll_event eventItem;
223 memset(&eventItem, 0, sizeof(eventItem));
224 eventItem.events = EPOLLIN;
225 eventItem.data.u32 = EPOLL_ID_INOTIFY;
226 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
227 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
230 result = pipe(wakeFds);
231 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
233 mWakeReadPipeFd = wakeFds[0];
234 mWakeWritePipeFd = wakeFds[1];
236 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
237 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
240 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
241 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
244 eventItem.data.u32 = EPOLL_ID_WAKE;
245 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
246 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
250 getLinuxRelease(&major, &minor);
251 // EPOLLWAKEUP was introduced in kernel 3.5
252 mUsingEpollWakeup = major > 3 || (major == 3 && minor >= 5);
255 EventHub::~EventHub(void) {
256 closeAllDevicesLocked();
258 while (mClosingDevices) {
259 Device* device = mClosingDevices;
260 mClosingDevices = device->next;
266 ::close(mWakeReadPipeFd);
267 ::close(mWakeWritePipeFd);
269 release_wake_lock(WAKE_LOCK_ID);
272 InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
274 Device* device = getDeviceLocked(deviceId);
275 if (device == NULL) return InputDeviceIdentifier();
276 return device->identifier;
279 uint32_t EventHub::getDeviceClasses(int32_t deviceId) const {
281 Device* device = getDeviceLocked(deviceId);
282 if (device == NULL) return 0;
283 return device->classes;
286 int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
288 Device* device = getDeviceLocked(deviceId);
289 if (device == NULL) return 0;
290 return device->controllerNumber;
293 void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
295 Device* device = getDeviceLocked(deviceId);
296 if (device && device->configuration) {
297 *outConfiguration = *device->configuration;
299 outConfiguration->clear();
303 status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
304 RawAbsoluteAxisInfo* outAxisInfo) const {
305 outAxisInfo->clear();
307 if (axis >= 0 && axis <= ABS_MAX) {
310 Device* device = getDeviceLocked(deviceId);
311 if (device && device->hasValidFd() && test_bit(axis, device->absBitmask)) {
312 struct input_absinfo info;
313 if(ioctl(device->fd, EVIOCGABS(axis), &info)) {
314 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d",
315 axis, device->identifier.name.string(), device->fd, errno);
319 if (info.minimum != info.maximum) {
320 outAxisInfo->valid = true;
321 outAxisInfo->minValue = info.minimum;
322 outAxisInfo->maxValue = info.maximum;
323 outAxisInfo->flat = info.flat;
324 outAxisInfo->fuzz = info.fuzz;
325 outAxisInfo->resolution = info.resolution;
333 bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
334 if (axis >= 0 && axis <= REL_MAX) {
337 Device* device = getDeviceLocked(deviceId);
339 return test_bit(axis, device->relBitmask);
345 bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
346 if (property >= 0 && property <= INPUT_PROP_MAX) {
349 Device* device = getDeviceLocked(deviceId);
351 return test_bit(property, device->propBitmask);
357 int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
358 if (scanCode >= 0 && scanCode <= KEY_MAX) {
361 Device* device = getDeviceLocked(deviceId);
362 if (device && device->hasValidFd() && test_bit(scanCode, device->keyBitmask)) {
363 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
364 memset(keyState, 0, sizeof(keyState));
365 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
366 return test_bit(scanCode, keyState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
370 return AKEY_STATE_UNKNOWN;
373 int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
376 Device* device = getDeviceLocked(deviceId);
377 if (device && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
378 Vector<int32_t> scanCodes;
379 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode, &scanCodes);
380 if (scanCodes.size() != 0) {
381 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
382 memset(keyState, 0, sizeof(keyState));
383 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
384 for (size_t i = 0; i < scanCodes.size(); i++) {
385 int32_t sc = scanCodes.itemAt(i);
386 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, keyState)) {
387 return AKEY_STATE_DOWN;
390 return AKEY_STATE_UP;
394 return AKEY_STATE_UNKNOWN;
397 int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
398 if (sw >= 0 && sw <= SW_MAX) {
401 Device* device = getDeviceLocked(deviceId);
402 if (device && device->hasValidFd() && test_bit(sw, device->swBitmask)) {
403 uint8_t swState[sizeof_bit_array(SW_MAX + 1)];
404 memset(swState, 0, sizeof(swState));
405 if (ioctl(device->fd, EVIOCGSW(sizeof(swState)), swState) >= 0) {
406 return test_bit(sw, swState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
410 return AKEY_STATE_UNKNOWN;
413 status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
416 if (axis >= 0 && axis <= ABS_MAX) {
419 Device* device = getDeviceLocked(deviceId);
420 if (device && device->hasValidFd() && test_bit(axis, device->absBitmask)) {
421 struct input_absinfo info;
422 if(ioctl(device->fd, EVIOCGABS(axis), &info)) {
423 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d",
424 axis, device->identifier.name.string(), device->fd, errno);
428 *outValue = info.value;
435 bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes,
436 const int32_t* keyCodes, uint8_t* outFlags) const {
439 Device* device = getDeviceLocked(deviceId);
440 if (device && device->keyMap.haveKeyLayout()) {
441 Vector<int32_t> scanCodes;
442 for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) {
445 status_t err = device->keyMap.keyLayoutMap->findScanCodesForKey(
446 keyCodes[codeIndex], &scanCodes);
448 // check the possible scan codes identified by the layout map against the
449 // map of codes actually emitted by the driver
450 for (size_t sc = 0; sc < scanCodes.size(); sc++) {
451 if (test_bit(scanCodes[sc], device->keyBitmask)) {
452 outFlags[codeIndex] = 1;
463 status_t EventHub::mapKey(int32_t deviceId,
464 int32_t scanCode, int32_t usageCode, int32_t metaState,
465 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
467 Device* device = getDeviceLocked(deviceId);
468 status_t status = NAME_NOT_FOUND;
471 // Check the key character map first.
472 sp<KeyCharacterMap> kcm = device->getKeyCharacterMap();
474 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
480 // Check the key layout next.
481 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
482 if (!device->keyMap.keyLayoutMap->mapKey(
483 scanCode, usageCode, outKeycode, outFlags)) {
488 if (status == NO_ERROR) {
490 kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState);
492 *outMetaState = metaState;
497 if (status != NO_ERROR) {
500 *outMetaState = metaState;
506 status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
508 Device* device = getDeviceLocked(deviceId);
510 if (device && device->keyMap.haveKeyLayout()) {
511 status_t err = device->keyMap.keyLayoutMap->mapAxis(scanCode, outAxisInfo);
512 if (err == NO_ERROR) {
517 return NAME_NOT_FOUND;
520 void EventHub::setExcludedDevices(const Vector<String8>& devices) {
523 mExcludedDevices = devices;
526 bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
528 Device* device = getDeviceLocked(deviceId);
529 if (device && scanCode >= 0 && scanCode <= KEY_MAX) {
530 if (test_bit(scanCode, device->keyBitmask)) {
537 bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
539 Device* device = getDeviceLocked(deviceId);
541 if (device && mapLed(device, led, &sc) == NO_ERROR) {
542 if (test_bit(sc, device->ledBitmask)) {
549 void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
551 Device* device = getDeviceLocked(deviceId);
552 setLedStateLocked(device, led, on);
555 void EventHub::setLedStateLocked(Device* device, int32_t led, bool on) {
557 if (device && device->hasValidFd() && mapLed(device, led, &sc) != NAME_NOT_FOUND) {
558 struct input_event ev;
563 ev.value = on ? 1 : 0;
567 nWrite = write(device->fd, &ev, sizeof(struct input_event));
568 } while (nWrite == -1 && errno == EINTR);
572 void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
573 Vector<VirtualKeyDefinition>& outVirtualKeys) const {
574 outVirtualKeys.clear();
577 Device* device = getDeviceLocked(deviceId);
578 if (device && device->virtualKeyMap) {
579 outVirtualKeys.appendVector(device->virtualKeyMap->getVirtualKeys());
583 sp<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
585 Device* device = getDeviceLocked(deviceId);
587 return device->getKeyCharacterMap();
592 bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId,
593 const sp<KeyCharacterMap>& map) {
595 Device* device = getDeviceLocked(deviceId);
597 if (map != device->overlayKeyMap) {
598 device->overlayKeyMap = map;
599 device->combinedKeyMap = KeyCharacterMap::combine(
600 device->keyMap.keyCharacterMap, map);
607 static String8 generateDescriptor(InputDeviceIdentifier& identifier) {
608 String8 rawDescriptor;
609 rawDescriptor.appendFormat(":%04x:%04x:", identifier.vendor,
611 // TODO add handling for USB devices to not uniqueify kbs that show up twice
612 if (!identifier.uniqueId.isEmpty()) {
613 rawDescriptor.append("uniqueId:");
614 rawDescriptor.append(identifier.uniqueId);
615 } else if (identifier.nonce != 0) {
616 rawDescriptor.appendFormat("nonce:%04x", identifier.nonce);
619 if (identifier.vendor == 0 && identifier.product == 0) {
620 // If we don't know the vendor and product id, then the device is probably
621 // built-in so we need to rely on other information to uniquely identify
622 // the input device. Usually we try to avoid relying on the device name or
623 // location but for built-in input device, they are unlikely to ever change.
624 if (!identifier.name.isEmpty()) {
625 rawDescriptor.append("name:");
626 rawDescriptor.append(identifier.name);
627 } else if (!identifier.location.isEmpty()) {
628 rawDescriptor.append("location:");
629 rawDescriptor.append(identifier.location);
632 identifier.descriptor = sha1(rawDescriptor);
633 return rawDescriptor;
636 void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
637 // Compute a device descriptor that uniquely identifies the device.
638 // The descriptor is assumed to be a stable identifier. Its value should not
639 // change between reboots, reconnections, firmware updates or new releases
640 // of Android. In practice we sometimes get devices that cannot be uniquely
641 // identified. In this case we enforce uniqueness between connected devices.
642 // Ideally, we also want the descriptor to be short and relatively opaque.
644 identifier.nonce = 0;
645 String8 rawDescriptor = generateDescriptor(identifier);
646 if (identifier.uniqueId.isEmpty()) {
647 // If it didn't have a unique id check for conflicts and enforce
648 // uniqueness if necessary.
649 while(getDeviceByDescriptorLocked(identifier.descriptor) != NULL) {
651 rawDescriptor = generateDescriptor(identifier);
654 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.string(),
655 identifier.descriptor.string());
658 void EventHub::vibrate(int32_t deviceId, nsecs_t duration) {
660 Device* device = getDeviceLocked(deviceId);
661 if (device && device->hasValidFd()) {
663 memset(&effect, 0, sizeof(effect));
664 effect.type = FF_RUMBLE;
665 effect.id = device->ffEffectId;
666 effect.u.rumble.strong_magnitude = 0xc000;
667 effect.u.rumble.weak_magnitude = 0xc000;
668 effect.replay.length = (duration + 999999LL) / 1000000LL;
669 effect.replay.delay = 0;
670 if (ioctl(device->fd, EVIOCSFF, &effect)) {
671 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
672 device->identifier.name.string(), errno);
675 device->ffEffectId = effect.id;
677 struct input_event ev;
681 ev.code = device->ffEffectId;
683 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
684 ALOGW("Could not start force feedback effect on device %s due to error %d.",
685 device->identifier.name.string(), errno);
688 device->ffEffectPlaying = true;
692 void EventHub::cancelVibrate(int32_t deviceId) {
694 Device* device = getDeviceLocked(deviceId);
695 if (device && device->hasValidFd()) {
696 if (device->ffEffectPlaying) {
697 device->ffEffectPlaying = false;
699 struct input_event ev;
703 ev.code = device->ffEffectId;
705 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
706 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
707 device->identifier.name.string(), errno);
714 EventHub::Device* EventHub::getDeviceByDescriptorLocked(String8& descriptor) const {
715 size_t size = mDevices.size();
716 for (size_t i = 0; i < size; i++) {
717 Device* device = mDevices.valueAt(i);
718 if (descriptor.compare(device->identifier.descriptor) == 0) {
725 EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
726 if (deviceId == BUILT_IN_KEYBOARD_ID) {
727 deviceId = mBuiltInKeyboardId;
729 ssize_t index = mDevices.indexOfKey(deviceId);
730 return index >= 0 ? mDevices.valueAt(index) : NULL;
733 EventHub::Device* EventHub::getDeviceByPathLocked(const char* devicePath) const {
734 for (size_t i = 0; i < mDevices.size(); i++) {
735 Device* device = mDevices.valueAt(i);
736 if (device->path == devicePath) {
743 size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
744 ALOG_ASSERT(bufferSize >= 1);
748 struct input_event readBuffer[bufferSize];
750 RawEvent* event = buffer;
751 size_t capacity = bufferSize;
754 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
756 // Reopen input devices if needed.
757 if (mNeedToReopenDevices) {
758 mNeedToReopenDevices = false;
760 ALOGI("Reopening all input devices due to a configuration change.");
762 closeAllDevicesLocked();
763 mNeedToScanDevices = true;
764 break; // return to the caller before we actually rescan
767 // Report any devices that had last been added/removed.
768 while (mClosingDevices) {
769 Device* device = mClosingDevices;
770 ALOGV("Reporting device closed: id=%d, name=%s\n",
771 device->id, device->path.string());
772 mClosingDevices = device->next;
774 event->deviceId = device->id == mBuiltInKeyboardId ? BUILT_IN_KEYBOARD_ID : device->id;
775 event->type = DEVICE_REMOVED;
778 mNeedToSendFinishedDeviceScan = true;
779 if (--capacity == 0) {
784 if (mNeedToScanDevices) {
785 mNeedToScanDevices = false;
787 mNeedToSendFinishedDeviceScan = true;
790 while (mOpeningDevices != NULL) {
791 Device* device = mOpeningDevices;
792 ALOGV("Reporting device opened: id=%d, name=%s\n",
793 device->id, device->path.string());
794 mOpeningDevices = device->next;
796 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
797 event->type = DEVICE_ADDED;
799 mNeedToSendFinishedDeviceScan = true;
800 if (--capacity == 0) {
805 if (mNeedToSendFinishedDeviceScan) {
806 mNeedToSendFinishedDeviceScan = false;
808 event->type = FINISHED_DEVICE_SCAN;
810 if (--capacity == 0) {
815 #ifdef CONSOLE_MANAGER
817 int fd_vt = open("/dev/tty0", O_RDWR | O_SYNC);
819 ioctl(fd_vt, VT_GETSTATE, &vs);
823 // Grab the next input event.
824 bool deviceChanged = false;
825 while (mPendingEventIndex < mPendingEventCount) {
826 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
827 if (eventItem.data.u32 == EPOLL_ID_INOTIFY) {
828 if (eventItem.events & EPOLLIN) {
829 mPendingINotify = true;
831 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
836 if (eventItem.data.u32 == EPOLL_ID_WAKE) {
837 if (eventItem.events & EPOLLIN) {
838 ALOGV("awoken after wake()");
843 nRead = read(mWakeReadPipeFd, buffer, sizeof(buffer));
844 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(buffer));
846 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
852 ssize_t deviceIndex = mDevices.indexOfKey(eventItem.data.u32);
853 if (deviceIndex < 0) {
854 ALOGW("Received unexpected epoll event 0x%08x for unknown device id %d.",
855 eventItem.events, eventItem.data.u32);
859 Device* device = mDevices.valueAt(deviceIndex);
860 if (eventItem.events & EPOLLIN) {
861 int32_t readSize = read(device->fd, readBuffer,
862 sizeof(struct input_event) * capacity);
863 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
864 // Device was removed before INotify noticed.
865 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
866 " bufferSize: %zu capacity: %zu errno: %d)\n",
867 device->fd, readSize, bufferSize, capacity, errno);
868 deviceChanged = true;
869 closeDeviceLocked(device);
870 } else if (readSize < 0) {
871 if (errno != EAGAIN && errno != EINTR) {
872 ALOGW("could not get event (errno=%d)", errno);
874 } else if ((readSize % sizeof(struct input_event)) != 0) {
875 ALOGE("could not get event (wrong size: %d)", readSize);
877 #ifdef CONSOLE_MANAGER
878 if (vs.v_active != ANDROID_VT) {
879 ALOGV("Skip a non Android VT event");
883 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
885 size_t count = size_t(readSize) / sizeof(struct input_event);
886 for (size_t i = 0; i < count; i++) {
887 struct input_event& iev = readBuffer[i];
888 ALOGV("%s got: time=%d.%06d, type=%d, code=%d, value=%d",
889 device->path.string(),
890 (int) iev.time.tv_sec, (int) iev.time.tv_usec,
891 iev.type, iev.code, iev.value);
893 // Some input devices may have a better concept of the time
894 // when an input event was actually generated than the kernel
895 // which simply timestamps all events on entry to evdev.
896 // This is a custom Android extension of the input protocol
897 // mainly intended for use with uinput based device drivers.
898 if (iev.type == EV_MSC) {
899 if (iev.code == MSC_ANDROID_TIME_SEC) {
900 device->timestampOverrideSec = iev.value;
902 } else if (iev.code == MSC_ANDROID_TIME_USEC) {
903 device->timestampOverrideUsec = iev.value;
907 if (device->timestampOverrideSec || device->timestampOverrideUsec) {
908 iev.time.tv_sec = device->timestampOverrideSec;
909 iev.time.tv_usec = device->timestampOverrideUsec;
910 if (iev.type == EV_SYN && iev.code == SYN_REPORT) {
911 device->timestampOverrideSec = 0;
912 device->timestampOverrideUsec = 0;
914 ALOGV("applied override time %d.%06d",
915 int(iev.time.tv_sec), int(iev.time.tv_usec));
918 // Use the time specified in the event instead of the current time
919 // so that downstream code can get more accurate estimates of
920 // event dispatch latency from the time the event is enqueued onto
921 // the evdev client buffer.
923 // The event's timestamp fortuitously uses the same monotonic clock
924 // time base as the rest of Android. The kernel event device driver
925 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
926 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
927 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
928 // system call that also queries ktime_get_ts().
929 event->when = nsecs_t(iev.time.tv_sec) * 1000000000LL
930 + nsecs_t(iev.time.tv_usec) * 1000LL;
931 ALOGV("event time %" PRId64 ", now %" PRId64, event->when, now);
933 // Bug 7291243: Add a guard in case the kernel generates timestamps
934 // that appear to be far into the future because they were generated
935 // using the wrong clock source.
937 // This can happen because when the input device is initially opened
938 // it has a default clock source of CLOCK_REALTIME. Any input events
939 // enqueued right after the device is opened will have timestamps
940 // generated using CLOCK_REALTIME. We later set the clock source
941 // to CLOCK_MONOTONIC but it is already too late.
943 // Invalid input event timestamps can result in ANRs, crashes and
944 // and other issues that are hard to track down. We must not let them
945 // propagate through the system.
947 // Log a warning so that we notice the problem and recover gracefully.
948 if (event->when >= now + 10 * 1000000000LL) {
949 // Double-check. Time may have moved on.
950 nsecs_t time = systemTime(SYSTEM_TIME_MONOTONIC);
951 if (event->when > time) {
952 ALOGW("An input event from %s has a timestamp that appears to "
953 "have been generated using the wrong clock source "
954 "(expected CLOCK_MONOTONIC): "
955 "event time %" PRId64 ", current time %" PRId64
956 ", call time %" PRId64 ". "
957 "Using current time instead.",
958 device->path.string(), event->when, time, now);
961 ALOGV("Event time is ok but failed the fast path and required "
962 "an extra call to systemTime: "
963 "event time %" PRId64 ", current time %" PRId64
964 ", call time %" PRId64 ".",
965 event->when, time, now);
968 event->deviceId = deviceId;
969 event->type = iev.type;
970 event->code = iev.code;
971 event->value = iev.value;
976 // The result buffer is full. Reset the pending event index
977 // so we will try to read the device again on the next iteration.
978 mPendingEventIndex -= 1;
982 } else if (eventItem.events & EPOLLHUP) {
983 ALOGI("Removing device %s due to epoll hang-up event.",
984 device->identifier.name.string());
985 deviceChanged = true;
986 closeDeviceLocked(device);
988 ALOGW("Received unexpected epoll event 0x%08x for device %s.",
989 eventItem.events, device->identifier.name.string());
993 // readNotify() will modify the list of devices so this must be done after
994 // processing all other events to ensure that we read all remaining events
995 // before closing the devices.
996 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
997 mPendingINotify = false;
999 deviceChanged = true;
1002 // Report added or removed devices immediately.
1003 if (deviceChanged) {
1007 // Return now if we have collected any events or if we were explicitly awoken.
1008 if (event != buffer || awoken) {
1012 // Poll for events. Mind the wake lock dance!
1013 // We hold a wake lock at all times except during epoll_wait(). This works due to some
1014 // subtle choreography. When a device driver has pending (unread) events, it acquires
1015 // a kernel wake lock. However, once the last pending event has been read, the device
1016 // driver will release the kernel wake lock. To prevent the system from going to sleep
1017 // when this happens, the EventHub holds onto its own user wake lock while the client
1018 // is processing events. Thus the system can only sleep if there are no events
1019 // pending or currently being processed.
1021 // The timeout is advisory only. If the device is asleep, it will not wake just to
1022 // service the timeout.
1023 mPendingEventIndex = 0;
1025 mLock.unlock(); // release lock before poll, must be before release_wake_lock
1026 release_wake_lock(WAKE_LOCK_ID);
1028 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1030 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
1031 mLock.lock(); // reacquire lock after poll, must be after acquire_wake_lock
1033 if (pollResult == 0) {
1035 mPendingEventCount = 0;
1039 if (pollResult < 0) {
1040 // An error occurred.
1041 mPendingEventCount = 0;
1043 // Sleep after errors to avoid locking up the system.
1044 // Hopefully the error is transient.
1045 if (errno != EINTR) {
1046 ALOGW("poll failed (errno=%d)\n", errno);
1050 // Some events occurred.
1051 mPendingEventCount = size_t(pollResult);
1055 // All done, return the number of events we read.
1056 return event - buffer;
1059 void EventHub::wake() {
1060 ALOGV("wake() called");
1064 nWrite = write(mWakeWritePipeFd, "W", 1);
1065 } while (nWrite == -1 && errno == EINTR);
1067 if (nWrite != 1 && errno != EAGAIN) {
1068 ALOGW("Could not write wake signal, errno=%d", errno);
1072 void EventHub::scanDevicesLocked() {
1073 status_t res = scanDirLocked(DEVICE_PATH);
1075 ALOGE("scan dir failed for %s\n", DEVICE_PATH);
1077 if (mDevices.indexOfKey(VIRTUAL_KEYBOARD_ID) < 0) {
1078 createVirtualKeyboardLocked();
1082 // ----------------------------------------------------------------------------
1084 static bool containsNonZeroByte(const uint8_t* array, uint32_t startIndex, uint32_t endIndex) {
1085 const uint8_t* end = array + endIndex;
1086 array += startIndex;
1087 while (array != end) {
1088 if (*(array++) != 0) {
1095 static const int32_t GAMEPAD_KEYCODES[] = {
1096 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C,
1097 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z,
1098 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1,
1099 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2,
1100 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR,
1101 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE,
1104 status_t EventHub::registerDeviceForEpollLocked(Device* device) {
1105 struct epoll_event eventItem;
1106 memset(&eventItem, 0, sizeof(eventItem));
1107 eventItem.events = EPOLLIN;
1108 if (mUsingEpollWakeup) {
1109 eventItem.events |= EPOLLWAKEUP;
1111 eventItem.data.u32 = device->id;
1112 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, device->fd, &eventItem)) {
1113 ALOGE("Could not add device fd to epoll instance. errno=%d", errno);
1119 status_t EventHub::unregisterDeviceFromEpollLocked(Device* device) {
1120 if (device->hasValidFd()) {
1121 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, device->fd, NULL)) {
1122 ALOGW("Could not remove device fd from epoll instance. errno=%d", errno);
1129 status_t EventHub::openDeviceLocked(const char *devicePath) {
1130 return openDeviceLocked(devicePath, false);
1133 status_t EventHub::openDeviceLocked(const char *devicePath, bool ignoreAlreadyOpened) {
1136 if (ignoreAlreadyOpened && (getDeviceByPathLocked(devicePath) != 0)) {
1137 ALOGV("Ignoring device '%s' that has already been opened.", devicePath);
1141 ALOGV("Opening device: %s", devicePath);
1143 int fd = open(devicePath, O_RDWR | O_CLOEXEC | O_NONBLOCK);
1145 ALOGE("could not open %s, %s\n", devicePath, strerror(errno));
1149 InputDeviceIdentifier identifier;
1152 if(ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
1153 //fprintf(stderr, "could not get device name for %s, %s\n", devicePath, strerror(errno));
1155 buffer[sizeof(buffer) - 1] = '\0';
1156 identifier.name.setTo(buffer);
1159 // Check to see if the device is on our excluded list
1160 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
1161 const String8& item = mExcludedDevices.itemAt(i);
1162 if (identifier.name == item) {
1163 ALOGI("ignoring event id %s driver %s\n", devicePath, item.string());
1169 // Get device driver version.
1171 if(ioctl(fd, EVIOCGVERSION, &driverVersion)) {
1172 ALOGE("could not get driver version for %s, %s\n", devicePath, strerror(errno));
1177 // Get device identifier.
1178 struct input_id inputId;
1179 if(ioctl(fd, EVIOCGID, &inputId)) {
1180 ALOGE("could not get device input id for %s, %s\n", devicePath, strerror(errno));
1184 identifier.bus = inputId.bustype;
1185 identifier.product = inputId.product;
1186 identifier.vendor = inputId.vendor;
1187 identifier.version = inputId.version;
1189 // Get device physical location.
1190 if(ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
1191 //fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
1193 buffer[sizeof(buffer) - 1] = '\0';
1194 identifier.location.setTo(buffer);
1197 // Get device unique id.
1198 if(ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
1199 //fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
1201 buffer[sizeof(buffer) - 1] = '\0';
1202 identifier.uniqueId.setTo(buffer);
1205 // Fill in the descriptor.
1206 assignDescriptorLocked(identifier);
1208 // Allocate device. (The device object takes ownership of the fd at this point.)
1209 int32_t deviceId = mNextDeviceId++;
1210 Device* device = new Device(fd, deviceId, String8(devicePath), identifier);
1212 ALOGV("add device %d: %s\n", deviceId, devicePath);
1213 ALOGV(" bus: %04x\n"
1217 identifier.bus, identifier.vendor, identifier.product, identifier.version);
1218 ALOGV(" name: \"%s\"\n", identifier.name.string());
1219 ALOGV(" location: \"%s\"\n", identifier.location.string());
1220 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.string());
1221 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.string());
1222 ALOGV(" driver: v%d.%d.%d\n",
1223 driverVersion >> 16, (driverVersion >> 8) & 0xff, driverVersion & 0xff);
1225 // Load the configuration file for the device.
1226 loadConfigurationLocked(device);
1228 // Figure out the kinds of events the device reports.
1229 ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(device->keyBitmask)), device->keyBitmask);
1230 ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(device->absBitmask)), device->absBitmask);
1231 ioctl(fd, EVIOCGBIT(EV_REL, sizeof(device->relBitmask)), device->relBitmask);
1232 ioctl(fd, EVIOCGBIT(EV_SW, sizeof(device->swBitmask)), device->swBitmask);
1233 ioctl(fd, EVIOCGBIT(EV_LED, sizeof(device->ledBitmask)), device->ledBitmask);
1234 ioctl(fd, EVIOCGBIT(EV_FF, sizeof(device->ffBitmask)), device->ffBitmask);
1235 ioctl(fd, EVIOCGPROP(sizeof(device->propBitmask)), device->propBitmask);
1237 // See if this is a keyboard. Ignore everything in the button range except for
1238 // joystick and gamepad buttons which are handled like keyboards for the most part.
1239 bool haveKeyboardKeys = containsNonZeroByte(device->keyBitmask, 0, sizeof_bit_array(BTN_MISC))
1240 || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(KEY_OK),
1241 sizeof_bit_array(KEY_MAX + 1));
1242 bool haveGamepadButtons = containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_MISC),
1243 sizeof_bit_array(BTN_MOUSE))
1244 || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_JOYSTICK),
1245 sizeof_bit_array(BTN_DIGI));
1246 if (haveKeyboardKeys || haveGamepadButtons) {
1247 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1250 // See if this is a cursor device such as a trackball or mouse.
1251 if (test_bit(BTN_MOUSE, device->keyBitmask)
1252 && test_bit(REL_X, device->relBitmask)
1253 && test_bit(REL_Y, device->relBitmask)) {
1254 device->classes |= INPUT_DEVICE_CLASS_CURSOR;
1257 // See if this is a rotary encoder type device.
1258 String8 deviceType = String8();
1259 if (device->configuration &&
1260 device->configuration->tryGetProperty(String8("device.type"), deviceType)) {
1261 if (!deviceType.compare(String8("rotaryEncoder"))) {
1262 device->classes |= INPUT_DEVICE_CLASS_ROTARY_ENCODER;
1266 // See if this is a touch pad.
1267 // Is this a new modern multi-touch driver?
1268 if (test_bit(ABS_MT_POSITION_X, device->absBitmask)
1269 && test_bit(ABS_MT_POSITION_Y, device->absBitmask)) {
1270 // Some joysticks such as the PS3 controller report axes that conflict
1271 // with the ABS_MT range. Try to confirm that the device really is
1273 if (test_bit(BTN_TOUCH, device->keyBitmask) || !haveGamepadButtons) {
1274 device->classes |= INPUT_DEVICE_CLASS_TOUCH | INPUT_DEVICE_CLASS_TOUCH_MT;
1276 // Is this an old style single-touch driver?
1277 } else if ((test_bit(BTN_TOUCH, device->keyBitmask) || test_bit(BTN_LEFT, device->keyBitmask))
1278 && test_bit(ABS_X, device->absBitmask)
1279 && test_bit(ABS_Y, device->absBitmask)) {
1280 device->classes |= INPUT_DEVICE_CLASS_TOUCH;
1281 // Is this a BT stylus?
1282 } else if ((test_bit(ABS_PRESSURE, device->absBitmask) ||
1283 test_bit(BTN_TOUCH, device->keyBitmask))
1284 && !test_bit(ABS_X, device->absBitmask)
1285 && !test_bit(ABS_Y, device->absBitmask)) {
1286 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
1287 // Keyboard will try to claim some of the buttons but we really want to reserve those so we
1288 // can fuse it with the touch screen data, so just take them back. Note this means an
1289 // external stylus cannot also be a keyboard device.
1290 device->classes &= ~INPUT_DEVICE_CLASS_KEYBOARD;
1293 // See if this device is a joystick.
1294 // Assumes that joysticks always have gamepad buttons in order to distinguish them
1295 // from other devices such as accelerometers that also have absolute axes.
1296 if (haveGamepadButtons) {
1297 uint32_t assumedClasses = device->classes | INPUT_DEVICE_CLASS_JOYSTICK;
1298 for (int i = 0; i <= ABS_MAX; i++) {
1299 if (test_bit(i, device->absBitmask)
1300 && (getAbsAxisUsage(i, assumedClasses) & INPUT_DEVICE_CLASS_JOYSTICK)) {
1301 device->classes = assumedClasses;
1307 // Check whether this device has switches.
1308 for (int i = 0; i <= SW_MAX; i++) {
1309 if (test_bit(i, device->swBitmask)) {
1310 device->classes |= INPUT_DEVICE_CLASS_SWITCH;
1315 // Check whether this device supports the vibrator.
1316 if (test_bit(FF_RUMBLE, device->ffBitmask)) {
1317 device->classes |= INPUT_DEVICE_CLASS_VIBRATOR;
1320 // Configure virtual keys.
1321 if ((device->classes & INPUT_DEVICE_CLASS_TOUCH)) {
1322 // Load the virtual keys for the touch screen, if any.
1323 // We do this now so that we can make sure to load the keymap if necessary.
1324 status_t status = loadVirtualKeyMapLocked(device);
1326 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1330 // Load the key map.
1331 // We need to do this for joysticks too because the key layout may specify axes.
1332 status_t keyMapStatus = NAME_NOT_FOUND;
1333 if (device->classes & (INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_JOYSTICK)) {
1334 // Load the keymap for the device.
1335 keyMapStatus = loadKeyMapLocked(device);
1338 // Configure the keyboard, gamepad or virtual keyboard.
1339 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1340 // Register the keyboard as a built-in keyboard if it is eligible.
1342 && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD
1343 && isEligibleBuiltInKeyboard(device->identifier,
1344 device->configuration, &device->keyMap)) {
1345 mBuiltInKeyboardId = device->id;
1348 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
1349 if (hasKeycodeLocked(device, AKEYCODE_Q)) {
1350 char value[PROPERTY_VALUE_MAX];
1351 property_get("ro.ignore_atkbd", value, "0");
1352 if ((device->identifier.name != "AT Translated Set 2 keyboard") || (!atoi(value))) {
1353 device->classes |= INPUT_DEVICE_CLASS_ALPHAKEY;
1357 // See if this device has a DPAD.
1358 if (hasKeycodeLocked(device, AKEYCODE_DPAD_UP) &&
1359 hasKeycodeLocked(device, AKEYCODE_DPAD_DOWN) &&
1360 hasKeycodeLocked(device, AKEYCODE_DPAD_LEFT) &&
1361 hasKeycodeLocked(device, AKEYCODE_DPAD_RIGHT) &&
1362 hasKeycodeLocked(device, AKEYCODE_DPAD_CENTER)) {
1363 device->classes |= INPUT_DEVICE_CLASS_DPAD;
1366 // See if this device has a gamepad.
1367 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES)/sizeof(GAMEPAD_KEYCODES[0]); i++) {
1368 if (hasKeycodeLocked(device, GAMEPAD_KEYCODES[i])) {
1369 device->classes |= INPUT_DEVICE_CLASS_GAMEPAD;
1375 // If the device isn't recognized as something we handle, don't monitor it.
1376 if (device->classes == 0) {
1377 ALOGV("Dropping device: id=%d, path='%s', name='%s'",
1378 deviceId, devicePath, device->identifier.name.string());
1383 // Determine whether the device has a mic.
1384 if (deviceHasMicLocked(device)) {
1385 device->classes |= INPUT_DEVICE_CLASS_MIC;
1388 // Determine whether the device is external or internal.
1389 if (isExternalDeviceLocked(device)) {
1390 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL;
1393 if (device->classes & (INPUT_DEVICE_CLASS_JOYSTICK | INPUT_DEVICE_CLASS_DPAD)
1394 && device->classes & INPUT_DEVICE_CLASS_GAMEPAD) {
1395 device->controllerNumber = getNextControllerNumberLocked(device);
1396 setLedForControllerLocked(device);
1400 if (registerDeviceForEpollLocked(device) != OK) {
1405 configureFd(device);
1407 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=0x%x, "
1408 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
1409 deviceId, fd, devicePath, device->identifier.name.string(),
1411 device->configurationFile.string(),
1412 device->keyMap.keyLayoutFile.string(),
1413 device->keyMap.keyCharacterMapFile.string(),
1414 toString(mBuiltInKeyboardId == deviceId));
1416 addDeviceLocked(device);
1420 void EventHub::configureFd(Device* device) {
1421 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
1422 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1423 // Disable kernel key repeat since we handle it ourselves
1424 unsigned int repeatRate[] = {0, 0};
1425 if (ioctl(device->fd, EVIOCSREP, repeatRate)) {
1426 ALOGW("Unable to disable kernel key repeat for %s: %s",
1427 device->path.string(), strerror(errno));
1431 String8 wakeMechanism("EPOLLWAKEUP");
1432 if (!mUsingEpollWakeup) {
1433 #ifndef EVIOCSSUSPENDBLOCK
1434 // uapi headers don't include EVIOCSSUSPENDBLOCK, and future kernels
1435 // will use an epoll flag instead, so as long as we want to support
1436 // this feature, we need to be prepared to define the ioctl ourselves.
1437 #define EVIOCSSUSPENDBLOCK _IOW('E', 0x91, int)
1439 if (ioctl(device->fd, EVIOCSSUSPENDBLOCK, 1)) {
1440 wakeMechanism = "<none>";
1442 wakeMechanism = "EVIOCSSUSPENDBLOCK";
1445 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
1446 // associated with input events. This is important because the input system
1447 // uses the timestamps extensively and assumes they were recorded using the monotonic
1449 int clockId = CLOCK_MONOTONIC;
1450 bool usingClockIoctl = !ioctl(device->fd, EVIOCSCLOCKID, &clockId);
1451 ALOGI("wakeMechanism=%s, usingClockIoctl=%s", wakeMechanism.string(),
1452 toString(usingClockIoctl));
1455 bool EventHub::isDeviceEnabled(int32_t deviceId) {
1456 AutoMutex _l(mLock);
1457 Device* device = getDeviceLocked(deviceId);
1458 if (device == NULL) {
1459 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1462 return device->enabled;
1465 status_t EventHub::enableDevice(int32_t deviceId) {
1466 AutoMutex _l(mLock);
1467 Device* device = getDeviceLocked(deviceId);
1468 if (device == NULL) {
1469 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1472 if (device->enabled) {
1473 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
1476 status_t result = device->enable();
1478 ALOGE("Failed to enable device %" PRId32, deviceId);
1482 configureFd(device);
1484 return registerDeviceForEpollLocked(device);
1487 status_t EventHub::disableDevice(int32_t deviceId) {
1488 AutoMutex _l(mLock);
1489 Device* device = getDeviceLocked(deviceId);
1490 if (device == NULL) {
1491 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1494 if (!device->enabled) {
1495 ALOGW("Duplicate call to %s, input device already disabled", __func__);
1498 unregisterDeviceFromEpollLocked(device);
1499 return device->disable();
1502 void EventHub::createVirtualKeyboardLocked() {
1503 InputDeviceIdentifier identifier;
1504 identifier.name = "Virtual";
1505 identifier.uniqueId = "<virtual>";
1506 assignDescriptorLocked(identifier);
1508 Device* device = new Device(-1, VIRTUAL_KEYBOARD_ID, String8("<virtual>"), identifier);
1509 device->classes = INPUT_DEVICE_CLASS_KEYBOARD
1510 | INPUT_DEVICE_CLASS_ALPHAKEY
1511 | INPUT_DEVICE_CLASS_DPAD
1512 | INPUT_DEVICE_CLASS_VIRTUAL;
1513 loadKeyMapLocked(device);
1514 addDeviceLocked(device);
1517 void EventHub::addDeviceLocked(Device* device) {
1518 mDevices.add(device->id, device);
1519 device->next = mOpeningDevices;
1520 mOpeningDevices = device;
1523 void EventHub::loadConfigurationLocked(Device* device) {
1524 device->configurationFile = getInputDeviceConfigurationFilePathByDeviceIdentifier(
1525 device->identifier, INPUT_DEVICE_CONFIGURATION_FILE_TYPE_CONFIGURATION);
1526 if (device->configurationFile.isEmpty()) {
1527 ALOGD("No input device configuration file found for device '%s'.",
1528 device->identifier.name.string());
1530 status_t status = PropertyMap::load(device->configurationFile,
1531 &device->configuration);
1533 ALOGE("Error loading input device configuration file for device '%s'. "
1534 "Using default configuration.",
1535 device->identifier.name.string());
1540 status_t EventHub::loadVirtualKeyMapLocked(Device* device) {
1541 // The virtual key map is supplied by the kernel as a system board property file.
1543 path.append("/sys/board_properties/virtualkeys.");
1544 path.append(device->identifier.name);
1545 if (access(path.string(), R_OK)) {
1546 return NAME_NOT_FOUND;
1548 return VirtualKeyMap::load(path, &device->virtualKeyMap);
1551 status_t EventHub::loadKeyMapLocked(Device* device) {
1552 return device->keyMap.load(device->identifier, device->configuration);
1555 bool EventHub::isExternalDeviceLocked(Device* device) {
1556 if (device->configuration) {
1558 if (device->configuration->tryGetProperty(String8("device.internal"), value)) {
1562 return device->identifier.bus == BUS_USB || device->identifier.bus == BUS_BLUETOOTH;
1565 bool EventHub::deviceHasMicLocked(Device* device) {
1566 if (device->configuration) {
1568 if (device->configuration->tryGetProperty(String8("audio.mic"), value)) {
1575 int32_t EventHub::getNextControllerNumberLocked(Device* device) {
1576 if (mControllerNumbers.isFull()) {
1577 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
1578 device->identifier.name.string());
1581 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
1583 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
1586 void EventHub::releaseControllerNumberLocked(Device* device) {
1587 int32_t num = device->controllerNumber;
1588 device->controllerNumber= 0;
1592 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
1595 void EventHub::setLedForControllerLocked(Device* device) {
1596 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
1597 setLedStateLocked(device, ALED_CONTROLLER_1 + i, device->controllerNumber == i + 1);
1601 bool EventHub::hasKeycodeLocked(Device* device, int keycode) const {
1602 if (!device->keyMap.haveKeyLayout()) {
1606 Vector<int32_t> scanCodes;
1607 device->keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes);
1608 const size_t N = scanCodes.size();
1609 for (size_t i=0; i<N && i<=KEY_MAX; i++) {
1610 int32_t sc = scanCodes.itemAt(i);
1611 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, device->keyBitmask)) {
1619 status_t EventHub::mapLed(Device* device, int32_t led, int32_t* outScanCode) const {
1620 if (!device->keyMap.haveKeyLayout()) {
1621 return NAME_NOT_FOUND;
1625 if(device->keyMap.keyLayoutMap->findScanCodeForLed(led, &scanCode) != NAME_NOT_FOUND) {
1626 if(scanCode >= 0 && scanCode <= LED_MAX && test_bit(scanCode, device->ledBitmask)) {
1627 *outScanCode = scanCode;
1631 return NAME_NOT_FOUND;
1634 status_t EventHub::closeDeviceByPathLocked(const char *devicePath) {
1635 Device* device = getDeviceByPathLocked(devicePath);
1637 closeDeviceLocked(device);
1640 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath);
1644 void EventHub::closeAllDevicesLocked() {
1645 while (mDevices.size() > 0) {
1646 closeDeviceLocked(mDevices.valueAt(mDevices.size() - 1));
1650 void EventHub::closeDeviceLocked(Device* device) {
1651 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=0x%x\n",
1652 device->path.string(), device->identifier.name.string(), device->id,
1653 device->fd, device->classes);
1655 if (device->id == mBuiltInKeyboardId) {
1656 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
1657 device->path.string(), mBuiltInKeyboardId);
1658 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
1661 unregisterDeviceFromEpollLocked(device);
1663 releaseControllerNumberLocked(device);
1665 mDevices.removeItem(device->id);
1668 // Unlink for opening devices list if it is present.
1669 Device* pred = NULL;
1671 for (Device* entry = mOpeningDevices; entry != NULL; ) {
1672 if (entry == device) {
1677 entry = entry->next;
1680 // Unlink the device from the opening devices list then delete it.
1681 // We don't need to tell the client that the device was closed because
1682 // it does not even know it was opened in the first place.
1683 ALOGI("Device %s was immediately closed after opening.", device->path.string());
1685 pred->next = device->next;
1687 mOpeningDevices = device->next;
1691 // Link into closing devices list.
1692 // The device will be deleted later after we have informed the client.
1693 device->next = mClosingDevices;
1694 mClosingDevices = device;
1698 status_t EventHub::readNotifyLocked() {
1700 char devname[PATH_MAX];
1702 char event_buf[512];
1705 struct inotify_event *event;
1707 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
1708 res = read(mINotifyFd, event_buf, sizeof(event_buf));
1709 if(res < (int)sizeof(*event)) {
1712 ALOGW("could not get event, %s\n", strerror(errno));
1715 //printf("got %d bytes of event information\n", res);
1717 strcpy(devname, DEVICE_PATH);
1718 filename = devname + strlen(devname);
1721 while(res >= (int)sizeof(*event)) {
1722 event = (struct inotify_event *)(event_buf + event_pos);
1723 //printf("%d: %08x \"%s\"\n", event->wd, event->mask, event->len ? event->name : "");
1725 strcpy(filename, event->name);
1726 if(event->mask & IN_CREATE) {
1727 openDeviceLocked(devname, true);
1729 ALOGI("Removing device '%s' due to inotify event\n", devname);
1730 closeDeviceByPathLocked(devname);
1733 event_size = sizeof(*event) + event->len;
1735 event_pos += event_size;
1740 status_t EventHub::scanDirLocked(const char *dirname)
1742 char devname[PATH_MAX];
1746 dir = opendir(dirname);
1749 strcpy(devname, dirname);
1750 filename = devname + strlen(devname);
1752 while((de = readdir(dir))) {
1753 if(de->d_name[0] == '.' &&
1754 (de->d_name[1] == '\0' ||
1755 (de->d_name[1] == '.' && de->d_name[2] == '\0')))
1757 strcpy(filename, de->d_name);
1758 openDeviceLocked(devname);
1764 void EventHub::requestReopenDevices() {
1765 ALOGV("requestReopenDevices() called");
1767 AutoMutex _l(mLock);
1768 mNeedToReopenDevices = true;
1771 void EventHub::dump(String8& dump) {
1772 dump.append("Event Hub State:\n");
1775 AutoMutex _l(mLock);
1777 dump.appendFormat(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
1779 dump.append(INDENT "Devices:\n");
1781 for (size_t i = 0; i < mDevices.size(); i++) {
1782 const Device* device = mDevices.valueAt(i);
1783 if (mBuiltInKeyboardId == device->id) {
1784 dump.appendFormat(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
1785 device->id, device->identifier.name.string());
1787 dump.appendFormat(INDENT2 "%d: %s\n", device->id,
1788 device->identifier.name.string());
1790 dump.appendFormat(INDENT3 "Classes: 0x%08x\n", device->classes);
1791 dump.appendFormat(INDENT3 "Path: %s\n", device->path.string());
1792 dump.appendFormat(INDENT3 "Enabled: %s\n", toString(device->enabled));
1793 dump.appendFormat(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.string());
1794 dump.appendFormat(INDENT3 "Location: %s\n", device->identifier.location.string());
1795 dump.appendFormat(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
1796 dump.appendFormat(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.string());
1797 dump.appendFormat(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
1798 "product=0x%04x, version=0x%04x\n",
1799 device->identifier.bus, device->identifier.vendor,
1800 device->identifier.product, device->identifier.version);
1801 dump.appendFormat(INDENT3 "KeyLayoutFile: %s\n",
1802 device->keyMap.keyLayoutFile.string());
1803 dump.appendFormat(INDENT3 "KeyCharacterMapFile: %s\n",
1804 device->keyMap.keyCharacterMapFile.string());
1805 dump.appendFormat(INDENT3 "ConfigurationFile: %s\n",
1806 device->configurationFile.string());
1807 dump.appendFormat(INDENT3 "HaveKeyboardLayoutOverlay: %s\n",
1808 toString(device->overlayKeyMap != NULL));
1813 void EventHub::monitor() {
1814 // Acquire and release the lock to ensure that the event hub has not deadlocked.
1820 }; // namespace android