EventHub.cpp revision 49ccac530b5a798e3c4a79b66b51b8546a0deed1
1/*
2 * Copyright (C) 2005 The Android Open Source Project
3 *
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
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
15 */
16
17#define LOG_TAG "EventHub"
18
19// #define LOG_NDEBUG 0
20
21#include "EventHub.h"
22
23#include <hardware_legacy/power.h>
24
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>
30
31#include <stdlib.h>
32#include <stdio.h>
33#include <unistd.h>
34#include <fcntl.h>
35#include <memory.h>
36#include <errno.h>
37#include <assert.h>
38
39#include <androidfw/KeyLayoutMap.h>
40#include <androidfw/KeyCharacterMap.h>
41#include <androidfw/VirtualKeyMap.h>
42
43#include <sha1.h>
44#include <string.h>
45#include <stdint.h>
46#include <dirent.h>
47
48#include <sys/inotify.h>
49#include <sys/epoll.h>
50#include <sys/ioctl.h>
51#include <sys/limits.h>
52
53/* this macro is used to tell if "bit" is set in "array"
54 * it selects a byte from the array, and does a boolean AND
55 * operation with a byte that only has the relevant bit set.
56 * eg. to check for the 12th bit, we do (array[1] & 1<<4)
57 */
58#define test_bit(bit, array)    (array[bit/8] & (1<<(bit%8)))
59
60/* this macro computes the number of bytes needed to represent a bit array of the specified size */
61#define sizeof_bit_array(bits)  ((bits + 7) / 8)
62
63#define INDENT "  "
64#define INDENT2 "    "
65#define INDENT3 "      "
66
67namespace android {
68
69static const char *WAKE_LOCK_ID = "KeyEvents";
70static const char *DEVICE_PATH = "/dev/input";
71
72/* return the larger integer */
73static inline int max(int v1, int v2)
74{
75    return (v1 > v2) ? v1 : v2;
76}
77
78static inline const char* toString(bool value) {
79    return value ? "true" : "false";
80}
81
82static String8 sha1(const String8& in) {
83    SHA1_CTX ctx;
84    SHA1Init(&ctx);
85    SHA1Update(&ctx, reinterpret_cast<const u_char*>(in.string()), in.size());
86    u_char digest[SHA1_DIGEST_LENGTH];
87    SHA1Final(digest, &ctx);
88
89    String8 out;
90    for (size_t i = 0; i < SHA1_DIGEST_LENGTH; i++) {
91        out.appendFormat("%02x", digest[i]);
92    }
93    return out;
94}
95
96static void setDescriptor(InputDeviceIdentifier& identifier) {
97    // Compute a device descriptor that uniquely identifies the device.
98    // The descriptor is assumed to be a stable identifier.  Its value should not
99    // change between reboots, reconnections, firmware updates or new releases of Android.
100    // Ideally, we also want the descriptor to be short and relatively opaque.
101    String8 rawDescriptor;
102    rawDescriptor.appendFormat(":%04x:%04x:", identifier.vendor, identifier.product);
103    if (!identifier.uniqueId.isEmpty()) {
104        rawDescriptor.append("uniqueId:");
105        rawDescriptor.append(identifier.uniqueId);
106    } if (identifier.vendor == 0 && identifier.product == 0) {
107        // If we don't know the vendor and product id, then the device is probably
108        // built-in so we need to rely on other information to uniquely identify
109        // the input device.  Usually we try to avoid relying on the device name or
110        // location but for built-in input device, they are unlikely to ever change.
111        if (!identifier.name.isEmpty()) {
112            rawDescriptor.append("name:");
113            rawDescriptor.append(identifier.name);
114        } else if (!identifier.location.isEmpty()) {
115            rawDescriptor.append("location:");
116            rawDescriptor.append(identifier.location);
117        }
118    }
119    identifier.descriptor = sha1(rawDescriptor);
120    ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.string(),
121            identifier.descriptor.string());
122}
123
124// --- Global Functions ---
125
126uint32_t getAbsAxisUsage(int32_t axis, uint32_t deviceClasses) {
127    // Touch devices get dibs on touch-related axes.
128    if (deviceClasses & INPUT_DEVICE_CLASS_TOUCH) {
129        switch (axis) {
130        case ABS_X:
131        case ABS_Y:
132        case ABS_PRESSURE:
133        case ABS_TOOL_WIDTH:
134        case ABS_DISTANCE:
135        case ABS_TILT_X:
136        case ABS_TILT_Y:
137        case ABS_MT_SLOT:
138        case ABS_MT_TOUCH_MAJOR:
139        case ABS_MT_TOUCH_MINOR:
140        case ABS_MT_WIDTH_MAJOR:
141        case ABS_MT_WIDTH_MINOR:
142        case ABS_MT_ORIENTATION:
143        case ABS_MT_POSITION_X:
144        case ABS_MT_POSITION_Y:
145        case ABS_MT_TOOL_TYPE:
146        case ABS_MT_BLOB_ID:
147        case ABS_MT_TRACKING_ID:
148        case ABS_MT_PRESSURE:
149        case ABS_MT_DISTANCE:
150            return INPUT_DEVICE_CLASS_TOUCH;
151        }
152    }
153
154    // Joystick devices get the rest.
155    return deviceClasses & INPUT_DEVICE_CLASS_JOYSTICK;
156}
157
158// --- EventHub::Device ---
159
160EventHub::Device::Device(int fd, int32_t id, const String8& path,
161        const InputDeviceIdentifier& identifier) :
162        next(NULL),
163        fd(fd), id(id), path(path), identifier(identifier),
164        classes(0), configuration(NULL), virtualKeyMap(NULL) {
165    memset(keyBitmask, 0, sizeof(keyBitmask));
166    memset(absBitmask, 0, sizeof(absBitmask));
167    memset(relBitmask, 0, sizeof(relBitmask));
168    memset(swBitmask, 0, sizeof(swBitmask));
169    memset(ledBitmask, 0, sizeof(ledBitmask));
170    memset(propBitmask, 0, sizeof(propBitmask));
171}
172
173EventHub::Device::~Device() {
174    close();
175    delete configuration;
176    delete virtualKeyMap;
177}
178
179void EventHub::Device::close() {
180    if (fd >= 0) {
181        ::close(fd);
182        fd = -1;
183    }
184}
185
186
187// --- EventHub ---
188
189const uint32_t EventHub::EPOLL_ID_INOTIFY;
190const uint32_t EventHub::EPOLL_ID_WAKE;
191const int EventHub::EPOLL_SIZE_HINT;
192const int EventHub::EPOLL_MAX_EVENTS;
193
194EventHub::EventHub(void) :
195        mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD), mNextDeviceId(1),
196        mOpeningDevices(0), mClosingDevices(0),
197        mNeedToSendFinishedDeviceScan(false),
198        mNeedToReopenDevices(false), mNeedToScanDevices(true),
199        mPendingEventCount(0), mPendingEventIndex(0), mPendingINotify(false) {
200    acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
201
202    mEpollFd = epoll_create(EPOLL_SIZE_HINT);
203    LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance.  errno=%d", errno);
204
205    mINotifyFd = inotify_init();
206    int result = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
207    LOG_ALWAYS_FATAL_IF(result < 0, "Could not register INotify for %s.  errno=%d",
208            DEVICE_PATH, errno);
209
210    struct epoll_event eventItem;
211    memset(&eventItem, 0, sizeof(eventItem));
212    eventItem.events = EPOLLIN;
213    eventItem.data.u32 = EPOLL_ID_INOTIFY;
214    result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
215    LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance.  errno=%d", errno);
216
217    int wakeFds[2];
218    result = pipe(wakeFds);
219    LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe.  errno=%d", errno);
220
221    mWakeReadPipeFd = wakeFds[0];
222    mWakeWritePipeFd = wakeFds[1];
223
224    result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
225    LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking.  errno=%d",
226            errno);
227
228    result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
229    LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking.  errno=%d",
230            errno);
231
232    eventItem.data.u32 = EPOLL_ID_WAKE;
233    result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
234    LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance.  errno=%d",
235            errno);
236}
237
238EventHub::~EventHub(void) {
239    closeAllDevicesLocked();
240
241    while (mClosingDevices) {
242        Device* device = mClosingDevices;
243        mClosingDevices = device->next;
244        delete device;
245    }
246
247    ::close(mEpollFd);
248    ::close(mINotifyFd);
249    ::close(mWakeReadPipeFd);
250    ::close(mWakeWritePipeFd);
251
252    release_wake_lock(WAKE_LOCK_ID);
253}
254
255InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
256    AutoMutex _l(mLock);
257    Device* device = getDeviceLocked(deviceId);
258    if (device == NULL) return InputDeviceIdentifier();
259    return device->identifier;
260}
261
262uint32_t EventHub::getDeviceClasses(int32_t deviceId) const {
263    AutoMutex _l(mLock);
264    Device* device = getDeviceLocked(deviceId);
265    if (device == NULL) return 0;
266    return device->classes;
267}
268
269void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
270    AutoMutex _l(mLock);
271    Device* device = getDeviceLocked(deviceId);
272    if (device && device->configuration) {
273        *outConfiguration = *device->configuration;
274    } else {
275        outConfiguration->clear();
276    }
277}
278
279status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
280        RawAbsoluteAxisInfo* outAxisInfo) const {
281    outAxisInfo->clear();
282
283    if (axis >= 0 && axis <= ABS_MAX) {
284        AutoMutex _l(mLock);
285
286        Device* device = getDeviceLocked(deviceId);
287        if (device && !device->isVirtual() && test_bit(axis, device->absBitmask)) {
288            struct input_absinfo info;
289            if(ioctl(device->fd, EVIOCGABS(axis), &info)) {
290                ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d",
291                     axis, device->identifier.name.string(), device->fd, errno);
292                return -errno;
293            }
294
295            if (info.minimum != info.maximum) {
296                outAxisInfo->valid = true;
297                outAxisInfo->minValue = info.minimum;
298                outAxisInfo->maxValue = info.maximum;
299                outAxisInfo->flat = info.flat;
300                outAxisInfo->fuzz = info.fuzz;
301                outAxisInfo->resolution = info.resolution;
302            }
303            return OK;
304        }
305    }
306    return -1;
307}
308
309bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
310    if (axis >= 0 && axis <= REL_MAX) {
311        AutoMutex _l(mLock);
312
313        Device* device = getDeviceLocked(deviceId);
314        if (device) {
315            return test_bit(axis, device->relBitmask);
316        }
317    }
318    return false;
319}
320
321bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
322    if (property >= 0 && property <= INPUT_PROP_MAX) {
323        AutoMutex _l(mLock);
324
325        Device* device = getDeviceLocked(deviceId);
326        if (device) {
327            return test_bit(property, device->propBitmask);
328        }
329    }
330    return false;
331}
332
333int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
334    if (scanCode >= 0 && scanCode <= KEY_MAX) {
335        AutoMutex _l(mLock);
336
337        Device* device = getDeviceLocked(deviceId);
338        if (device && !device->isVirtual() && test_bit(scanCode, device->keyBitmask)) {
339            uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
340            memset(keyState, 0, sizeof(keyState));
341            if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
342                return test_bit(scanCode, keyState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
343            }
344        }
345    }
346    return AKEY_STATE_UNKNOWN;
347}
348
349int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
350    AutoMutex _l(mLock);
351
352    Device* device = getDeviceLocked(deviceId);
353    if (device && !device->isVirtual() && device->keyMap.haveKeyLayout()) {
354        Vector<int32_t> scanCodes;
355        device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode, &scanCodes);
356        if (scanCodes.size() != 0) {
357            uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
358            memset(keyState, 0, sizeof(keyState));
359            if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
360                for (size_t i = 0; i < scanCodes.size(); i++) {
361                    int32_t sc = scanCodes.itemAt(i);
362                    if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, keyState)) {
363                        return AKEY_STATE_DOWN;
364                    }
365                }
366                return AKEY_STATE_UP;
367            }
368        }
369    }
370    return AKEY_STATE_UNKNOWN;
371}
372
373int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
374    if (sw >= 0 && sw <= SW_MAX) {
375        AutoMutex _l(mLock);
376
377        Device* device = getDeviceLocked(deviceId);
378        if (device && !device->isVirtual() && test_bit(sw, device->swBitmask)) {
379            uint8_t swState[sizeof_bit_array(SW_MAX + 1)];
380            memset(swState, 0, sizeof(swState));
381            if (ioctl(device->fd, EVIOCGSW(sizeof(swState)), swState) >= 0) {
382                return test_bit(sw, swState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
383            }
384        }
385    }
386    return AKEY_STATE_UNKNOWN;
387}
388
389status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
390    *outValue = 0;
391
392    if (axis >= 0 && axis <= ABS_MAX) {
393        AutoMutex _l(mLock);
394
395        Device* device = getDeviceLocked(deviceId);
396        if (device && !device->isVirtual() && test_bit(axis, device->absBitmask)) {
397            struct input_absinfo info;
398            if(ioctl(device->fd, EVIOCGABS(axis), &info)) {
399                ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d",
400                     axis, device->identifier.name.string(), device->fd, errno);
401                return -errno;
402            }
403
404            *outValue = info.value;
405            return OK;
406        }
407    }
408    return -1;
409}
410
411bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes,
412        const int32_t* keyCodes, uint8_t* outFlags) const {
413    AutoMutex _l(mLock);
414
415    Device* device = getDeviceLocked(deviceId);
416    if (device && device->keyMap.haveKeyLayout()) {
417        Vector<int32_t> scanCodes;
418        for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) {
419            scanCodes.clear();
420
421            status_t err = device->keyMap.keyLayoutMap->findScanCodesForKey(
422                    keyCodes[codeIndex], &scanCodes);
423            if (! err) {
424                // check the possible scan codes identified by the layout map against the
425                // map of codes actually emitted by the driver
426                for (size_t sc = 0; sc < scanCodes.size(); sc++) {
427                    if (test_bit(scanCodes[sc], device->keyBitmask)) {
428                        outFlags[codeIndex] = 1;
429                        break;
430                    }
431                }
432            }
433        }
434        return true;
435    }
436    return false;
437}
438
439status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode,
440        int32_t* outKeycode, uint32_t* outFlags) const {
441    AutoMutex _l(mLock);
442    Device* device = getDeviceLocked(deviceId);
443
444    if (device && device->keyMap.haveKeyLayout()) {
445        status_t err = device->keyMap.keyLayoutMap->mapKey(
446                scanCode, usageCode, outKeycode, outFlags);
447        if (err == NO_ERROR) {
448            return NO_ERROR;
449        }
450    }
451
452    *outKeycode = 0;
453    *outFlags = 0;
454    return NAME_NOT_FOUND;
455}
456
457status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
458    AutoMutex _l(mLock);
459    Device* device = getDeviceLocked(deviceId);
460
461    if (device && device->keyMap.haveKeyLayout()) {
462        status_t err = device->keyMap.keyLayoutMap->mapAxis(scanCode, outAxisInfo);
463        if (err == NO_ERROR) {
464            return NO_ERROR;
465        }
466    }
467
468    return NAME_NOT_FOUND;
469}
470
471void EventHub::setExcludedDevices(const Vector<String8>& devices) {
472    AutoMutex _l(mLock);
473
474    mExcludedDevices = devices;
475}
476
477bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
478    AutoMutex _l(mLock);
479    Device* device = getDeviceLocked(deviceId);
480    if (device && scanCode >= 0 && scanCode <= KEY_MAX) {
481        if (test_bit(scanCode, device->keyBitmask)) {
482            return true;
483        }
484    }
485    return false;
486}
487
488bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
489    AutoMutex _l(mLock);
490    Device* device = getDeviceLocked(deviceId);
491    if (device && led >= 0 && led <= LED_MAX) {
492        if (test_bit(led, device->ledBitmask)) {
493            return true;
494        }
495    }
496    return false;
497}
498
499void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
500    AutoMutex _l(mLock);
501    Device* device = getDeviceLocked(deviceId);
502    if (device && !device->isVirtual() && led >= 0 && led <= LED_MAX) {
503        struct input_event ev;
504        ev.time.tv_sec = 0;
505        ev.time.tv_usec = 0;
506        ev.type = EV_LED;
507        ev.code = led;
508        ev.value = on ? 1 : 0;
509
510        ssize_t nWrite;
511        do {
512            nWrite = write(device->fd, &ev, sizeof(struct input_event));
513        } while (nWrite == -1 && errno == EINTR);
514    }
515}
516
517void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
518        Vector<VirtualKeyDefinition>& outVirtualKeys) const {
519    outVirtualKeys.clear();
520
521    AutoMutex _l(mLock);
522    Device* device = getDeviceLocked(deviceId);
523    if (device && device->virtualKeyMap) {
524        outVirtualKeys.appendVector(device->virtualKeyMap->getVirtualKeys());
525    }
526}
527
528sp<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
529    AutoMutex _l(mLock);
530    Device* device = getDeviceLocked(deviceId);
531    if (device) {
532        return device->keyMap.keyCharacterMap;
533    }
534    return NULL;
535}
536
537EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
538    if (deviceId == BUILT_IN_KEYBOARD_ID) {
539        deviceId = mBuiltInKeyboardId;
540    }
541    ssize_t index = mDevices.indexOfKey(deviceId);
542    return index >= 0 ? mDevices.valueAt(index) : NULL;
543}
544
545EventHub::Device* EventHub::getDeviceByPathLocked(const char* devicePath) const {
546    for (size_t i = 0; i < mDevices.size(); i++) {
547        Device* device = mDevices.valueAt(i);
548        if (device->path == devicePath) {
549            return device;
550        }
551    }
552    return NULL;
553}
554
555size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
556    ALOG_ASSERT(bufferSize >= 1);
557
558    AutoMutex _l(mLock);
559
560    struct input_event readBuffer[bufferSize];
561
562    RawEvent* event = buffer;
563    size_t capacity = bufferSize;
564    bool awoken = false;
565    for (;;) {
566        nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
567
568        // Reopen input devices if needed.
569        if (mNeedToReopenDevices) {
570            mNeedToReopenDevices = false;
571
572            ALOGI("Reopening all input devices due to a configuration change.");
573
574            closeAllDevicesLocked();
575            mNeedToScanDevices = true;
576            break; // return to the caller before we actually rescan
577        }
578
579        // Report any devices that had last been added/removed.
580        while (mClosingDevices) {
581            Device* device = mClosingDevices;
582            ALOGV("Reporting device closed: id=%d, name=%s\n",
583                 device->id, device->path.string());
584            mClosingDevices = device->next;
585            event->when = now;
586            event->deviceId = device->id == mBuiltInKeyboardId ? BUILT_IN_KEYBOARD_ID : device->id;
587            event->type = DEVICE_REMOVED;
588            event += 1;
589            delete device;
590            mNeedToSendFinishedDeviceScan = true;
591            if (--capacity == 0) {
592                break;
593            }
594        }
595
596        if (mNeedToScanDevices) {
597            mNeedToScanDevices = false;
598            scanDevicesLocked();
599            mNeedToSendFinishedDeviceScan = true;
600        }
601
602        while (mOpeningDevices != NULL) {
603            Device* device = mOpeningDevices;
604            ALOGV("Reporting device opened: id=%d, name=%s\n",
605                 device->id, device->path.string());
606            mOpeningDevices = device->next;
607            event->when = now;
608            event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
609            event->type = DEVICE_ADDED;
610            event += 1;
611            mNeedToSendFinishedDeviceScan = true;
612            if (--capacity == 0) {
613                break;
614            }
615        }
616
617        if (mNeedToSendFinishedDeviceScan) {
618            mNeedToSendFinishedDeviceScan = false;
619            event->when = now;
620            event->type = FINISHED_DEVICE_SCAN;
621            event += 1;
622            if (--capacity == 0) {
623                break;
624            }
625        }
626
627        // Grab the next input event.
628        bool deviceChanged = false;
629        while (mPendingEventIndex < mPendingEventCount) {
630            const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
631            if (eventItem.data.u32 == EPOLL_ID_INOTIFY) {
632                if (eventItem.events & EPOLLIN) {
633                    mPendingINotify = true;
634                } else {
635                    ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
636                }
637                continue;
638            }
639
640            if (eventItem.data.u32 == EPOLL_ID_WAKE) {
641                if (eventItem.events & EPOLLIN) {
642                    ALOGV("awoken after wake()");
643                    awoken = true;
644                    char buffer[16];
645                    ssize_t nRead;
646                    do {
647                        nRead = read(mWakeReadPipeFd, buffer, sizeof(buffer));
648                    } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(buffer));
649                } else {
650                    ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
651                            eventItem.events);
652                }
653                continue;
654            }
655
656            ssize_t deviceIndex = mDevices.indexOfKey(eventItem.data.u32);
657            if (deviceIndex < 0) {
658                ALOGW("Received unexpected epoll event 0x%08x for unknown device id %d.",
659                        eventItem.events, eventItem.data.u32);
660                continue;
661            }
662
663            Device* device = mDevices.valueAt(deviceIndex);
664            if (eventItem.events & EPOLLIN) {
665                int32_t readSize = read(device->fd, readBuffer,
666                        sizeof(struct input_event) * capacity);
667                if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
668                    // Device was removed before INotify noticed.
669                    ALOGW("could not get event, removed? (fd: %d size: %d bufferSize: %d "
670                            "capacity: %d errno: %d)\n",
671                            device->fd, readSize, bufferSize, capacity, errno);
672                    deviceChanged = true;
673                    closeDeviceLocked(device);
674                } else if (readSize < 0) {
675                    if (errno != EAGAIN && errno != EINTR) {
676                        ALOGW("could not get event (errno=%d)", errno);
677                    }
678                } else if ((readSize % sizeof(struct input_event)) != 0) {
679                    ALOGE("could not get event (wrong size: %d)", readSize);
680                } else {
681                    int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
682
683                    size_t count = size_t(readSize) / sizeof(struct input_event);
684                    for (size_t i = 0; i < count; i++) {
685                        const struct input_event& iev = readBuffer[i];
686                        ALOGV("%s got: t0=%d, t1=%d, type=%d, code=%d, value=%d",
687                                device->path.string(),
688                                (int) iev.time.tv_sec, (int) iev.time.tv_usec,
689                                iev.type, iev.code, iev.value);
690
691#ifdef HAVE_POSIX_CLOCKS
692                        // Use the time specified in the event instead of the current time
693                        // so that downstream code can get more accurate estimates of
694                        // event dispatch latency from the time the event is enqueued onto
695                        // the evdev client buffer.
696                        //
697                        // The event's timestamp fortuitously uses the same monotonic clock
698                        // time base as the rest of Android.  The kernel event device driver
699                        // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
700                        // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
701                        // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
702                        // system call that also queries ktime_get_ts().
703                        event->when = nsecs_t(iev.time.tv_sec) * 1000000000LL
704                                + nsecs_t(iev.time.tv_usec) * 1000LL;
705                        ALOGV("event time %lld, now %lld", event->when, now);
706#else
707                        event->when = now;
708#endif
709                        event->deviceId = deviceId;
710                        event->type = iev.type;
711                        event->code = iev.code;
712                        event->value = iev.value;
713                        event += 1;
714                    }
715                    capacity -= count;
716                    if (capacity == 0) {
717                        // The result buffer is full.  Reset the pending event index
718                        // so we will try to read the device again on the next iteration.
719                        mPendingEventIndex -= 1;
720                        break;
721                    }
722                }
723            } else {
724                ALOGW("Received unexpected epoll event 0x%08x for device %s.",
725                        eventItem.events, device->identifier.name.string());
726            }
727        }
728
729        // readNotify() will modify the list of devices so this must be done after
730        // processing all other events to ensure that we read all remaining events
731        // before closing the devices.
732        if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
733            mPendingINotify = false;
734            readNotifyLocked();
735            deviceChanged = true;
736        }
737
738        // Report added or removed devices immediately.
739        if (deviceChanged) {
740            continue;
741        }
742
743        // Return now if we have collected any events or if we were explicitly awoken.
744        if (event != buffer || awoken) {
745            break;
746        }
747
748        // Poll for events.  Mind the wake lock dance!
749        // We hold a wake lock at all times except during epoll_wait().  This works due to some
750        // subtle choreography.  When a device driver has pending (unread) events, it acquires
751        // a kernel wake lock.  However, once the last pending event has been read, the device
752        // driver will release the kernel wake lock.  To prevent the system from going to sleep
753        // when this happens, the EventHub holds onto its own user wake lock while the client
754        // is processing events.  Thus the system can only sleep if there are no events
755        // pending or currently being processed.
756        //
757        // The timeout is advisory only.  If the device is asleep, it will not wake just to
758        // service the timeout.
759        mPendingEventIndex = 0;
760
761        mLock.unlock(); // release lock before poll, must be before release_wake_lock
762        release_wake_lock(WAKE_LOCK_ID);
763
764        int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
765
766        acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
767        mLock.lock(); // reacquire lock after poll, must be after acquire_wake_lock
768
769        if (pollResult == 0) {
770            // Timed out.
771            mPendingEventCount = 0;
772            break;
773        }
774
775        if (pollResult < 0) {
776            // An error occurred.
777            mPendingEventCount = 0;
778
779            // Sleep after errors to avoid locking up the system.
780            // Hopefully the error is transient.
781            if (errno != EINTR) {
782                ALOGW("poll failed (errno=%d)\n", errno);
783                usleep(100000);
784            }
785        } else {
786            // Some events occurred.
787            mPendingEventCount = size_t(pollResult);
788        }
789    }
790
791    // All done, return the number of events we read.
792    return event - buffer;
793}
794
795void EventHub::wake() {
796    ALOGV("wake() called");
797
798    ssize_t nWrite;
799    do {
800        nWrite = write(mWakeWritePipeFd, "W", 1);
801    } while (nWrite == -1 && errno == EINTR);
802
803    if (nWrite != 1 && errno != EAGAIN) {
804        ALOGW("Could not write wake signal, errno=%d", errno);
805    }
806}
807
808void EventHub::scanDevicesLocked() {
809    status_t res = scanDirLocked(DEVICE_PATH);
810    if(res < 0) {
811        ALOGE("scan dir failed for %s\n", DEVICE_PATH);
812    }
813    if (mDevices.indexOfKey(VIRTUAL_KEYBOARD_ID) < 0) {
814        createVirtualKeyboardLocked();
815    }
816}
817
818// ----------------------------------------------------------------------------
819
820static bool containsNonZeroByte(const uint8_t* array, uint32_t startIndex, uint32_t endIndex) {
821    const uint8_t* end = array + endIndex;
822    array += startIndex;
823    while (array != end) {
824        if (*(array++) != 0) {
825            return true;
826        }
827    }
828    return false;
829}
830
831static const int32_t GAMEPAD_KEYCODES[] = {
832        AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C,
833        AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z,
834        AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1,
835        AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2,
836        AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR,
837        AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE,
838        AKEYCODE_BUTTON_1, AKEYCODE_BUTTON_2, AKEYCODE_BUTTON_3, AKEYCODE_BUTTON_4,
839        AKEYCODE_BUTTON_5, AKEYCODE_BUTTON_6, AKEYCODE_BUTTON_7, AKEYCODE_BUTTON_8,
840        AKEYCODE_BUTTON_9, AKEYCODE_BUTTON_10, AKEYCODE_BUTTON_11, AKEYCODE_BUTTON_12,
841        AKEYCODE_BUTTON_13, AKEYCODE_BUTTON_14, AKEYCODE_BUTTON_15, AKEYCODE_BUTTON_16,
842};
843
844status_t EventHub::openDeviceLocked(const char *devicePath) {
845    char buffer[80];
846
847    ALOGV("Opening device: %s", devicePath);
848
849    int fd = open(devicePath, O_RDWR | O_CLOEXEC);
850    if(fd < 0) {
851        ALOGE("could not open %s, %s\n", devicePath, strerror(errno));
852        return -1;
853    }
854
855    InputDeviceIdentifier identifier;
856
857    // Get device name.
858    if(ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
859        //fprintf(stderr, "could not get device name for %s, %s\n", devicePath, strerror(errno));
860    } else {
861        buffer[sizeof(buffer) - 1] = '\0';
862        identifier.name.setTo(buffer);
863    }
864
865    // Check to see if the device is on our excluded list
866    for (size_t i = 0; i < mExcludedDevices.size(); i++) {
867        const String8& item = mExcludedDevices.itemAt(i);
868        if (identifier.name == item) {
869            ALOGI("ignoring event id %s driver %s\n", devicePath, item.string());
870            close(fd);
871            return -1;
872        }
873    }
874
875    // Get device driver version.
876    int driverVersion;
877    if(ioctl(fd, EVIOCGVERSION, &driverVersion)) {
878        ALOGE("could not get driver version for %s, %s\n", devicePath, strerror(errno));
879        close(fd);
880        return -1;
881    }
882
883    // Get device identifier.
884    struct input_id inputId;
885    if(ioctl(fd, EVIOCGID, &inputId)) {
886        ALOGE("could not get device input id for %s, %s\n", devicePath, strerror(errno));
887        close(fd);
888        return -1;
889    }
890    identifier.bus = inputId.bustype;
891    identifier.product = inputId.product;
892    identifier.vendor = inputId.vendor;
893    identifier.version = inputId.version;
894
895    // Get device physical location.
896    if(ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
897        //fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
898    } else {
899        buffer[sizeof(buffer) - 1] = '\0';
900        identifier.location.setTo(buffer);
901    }
902
903    // Get device unique id.
904    if(ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
905        //fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
906    } else {
907        buffer[sizeof(buffer) - 1] = '\0';
908        identifier.uniqueId.setTo(buffer);
909    }
910
911    // Fill in the descriptor.
912    setDescriptor(identifier);
913
914    // Make file descriptor non-blocking for use with poll().
915    if (fcntl(fd, F_SETFL, O_NONBLOCK)) {
916        ALOGE("Error %d making device file descriptor non-blocking.", errno);
917        close(fd);
918        return -1;
919    }
920
921    // Allocate device.  (The device object takes ownership of the fd at this point.)
922    int32_t deviceId = mNextDeviceId++;
923    Device* device = new Device(fd, deviceId, String8(devicePath), identifier);
924
925    ALOGV("add device %d: %s\n", deviceId, devicePath);
926    ALOGV("  bus:        %04x\n"
927         "  vendor      %04x\n"
928         "  product     %04x\n"
929         "  version     %04x\n",
930        identifier.bus, identifier.vendor, identifier.product, identifier.version);
931    ALOGV("  name:       \"%s\"\n", identifier.name.string());
932    ALOGV("  location:   \"%s\"\n", identifier.location.string());
933    ALOGV("  unique id:  \"%s\"\n", identifier.uniqueId.string());
934    ALOGV("  descriptor: \"%s\"\n", identifier.descriptor.string());
935    ALOGV("  driver:     v%d.%d.%d\n",
936        driverVersion >> 16, (driverVersion >> 8) & 0xff, driverVersion & 0xff);
937
938    // Load the configuration file for the device.
939    loadConfigurationLocked(device);
940
941    // Figure out the kinds of events the device reports.
942    ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(device->keyBitmask)), device->keyBitmask);
943    ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(device->absBitmask)), device->absBitmask);
944    ioctl(fd, EVIOCGBIT(EV_REL, sizeof(device->relBitmask)), device->relBitmask);
945    ioctl(fd, EVIOCGBIT(EV_SW, sizeof(device->swBitmask)), device->swBitmask);
946    ioctl(fd, EVIOCGBIT(EV_LED, sizeof(device->ledBitmask)), device->ledBitmask);
947    ioctl(fd, EVIOCGPROP(sizeof(device->propBitmask)), device->propBitmask);
948
949    // See if this is a keyboard.  Ignore everything in the button range except for
950    // joystick and gamepad buttons which are handled like keyboards for the most part.
951    bool haveKeyboardKeys = containsNonZeroByte(device->keyBitmask, 0, sizeof_bit_array(BTN_MISC))
952            || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(KEY_OK),
953                    sizeof_bit_array(KEY_MAX + 1));
954    bool haveGamepadButtons = containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_MISC),
955                    sizeof_bit_array(BTN_MOUSE))
956            || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_JOYSTICK),
957                    sizeof_bit_array(BTN_DIGI));
958    if (haveKeyboardKeys || haveGamepadButtons) {
959        device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
960    }
961
962    // See if this is a cursor device such as a trackball or mouse.
963    if (test_bit(BTN_MOUSE, device->keyBitmask)
964            && test_bit(REL_X, device->relBitmask)
965            && test_bit(REL_Y, device->relBitmask)) {
966        device->classes |= INPUT_DEVICE_CLASS_CURSOR;
967    }
968
969    // See if this is a touch pad.
970    // Is this a new modern multi-touch driver?
971    if (test_bit(ABS_MT_POSITION_X, device->absBitmask)
972            && test_bit(ABS_MT_POSITION_Y, device->absBitmask)) {
973        // Some joysticks such as the PS3 controller report axes that conflict
974        // with the ABS_MT range.  Try to confirm that the device really is
975        // a touch screen.
976        if (test_bit(BTN_TOUCH, device->keyBitmask) || !haveGamepadButtons) {
977            device->classes |= INPUT_DEVICE_CLASS_TOUCH | INPUT_DEVICE_CLASS_TOUCH_MT;
978        }
979    // Is this an old style single-touch driver?
980    } else if (test_bit(BTN_TOUCH, device->keyBitmask)
981            && test_bit(ABS_X, device->absBitmask)
982            && test_bit(ABS_Y, device->absBitmask)) {
983        device->classes |= INPUT_DEVICE_CLASS_TOUCH;
984    }
985
986    // See if this device is a joystick.
987    // Assumes that joysticks always have gamepad buttons in order to distinguish them
988    // from other devices such as accelerometers that also have absolute axes.
989    if (haveGamepadButtons) {
990        uint32_t assumedClasses = device->classes | INPUT_DEVICE_CLASS_JOYSTICK;
991        for (int i = 0; i <= ABS_MAX; i++) {
992            if (test_bit(i, device->absBitmask)
993                    && (getAbsAxisUsage(i, assumedClasses) & INPUT_DEVICE_CLASS_JOYSTICK)) {
994                device->classes = assumedClasses;
995                break;
996            }
997        }
998    }
999
1000    // Check whether this device has switches.
1001    for (int i = 0; i <= SW_MAX; i++) {
1002        if (test_bit(i, device->swBitmask)) {
1003            device->classes |= INPUT_DEVICE_CLASS_SWITCH;
1004            break;
1005        }
1006    }
1007
1008    // Configure virtual keys.
1009    if ((device->classes & INPUT_DEVICE_CLASS_TOUCH)) {
1010        // Load the virtual keys for the touch screen, if any.
1011        // We do this now so that we can make sure to load the keymap if necessary.
1012        status_t status = loadVirtualKeyMapLocked(device);
1013        if (!status) {
1014            device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1015        }
1016    }
1017
1018    // Load the key map.
1019    // We need to do this for joysticks too because the key layout may specify axes.
1020    status_t keyMapStatus = NAME_NOT_FOUND;
1021    if (device->classes & (INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_JOYSTICK)) {
1022        // Load the keymap for the device.
1023        keyMapStatus = loadKeyMapLocked(device);
1024    }
1025
1026    // Configure the keyboard, gamepad or virtual keyboard.
1027    if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1028        // Register the keyboard as a built-in keyboard if it is eligible.
1029        if (!keyMapStatus
1030                && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD
1031                && isEligibleBuiltInKeyboard(device->identifier,
1032                        device->configuration, &device->keyMap)) {
1033            mBuiltInKeyboardId = device->id;
1034        }
1035
1036        // 'Q' key support = cheap test of whether this is an alpha-capable kbd
1037        if (hasKeycodeLocked(device, AKEYCODE_Q)) {
1038            device->classes |= INPUT_DEVICE_CLASS_ALPHAKEY;
1039        }
1040
1041        // See if this device has a DPAD.
1042        if (hasKeycodeLocked(device, AKEYCODE_DPAD_UP) &&
1043                hasKeycodeLocked(device, AKEYCODE_DPAD_DOWN) &&
1044                hasKeycodeLocked(device, AKEYCODE_DPAD_LEFT) &&
1045                hasKeycodeLocked(device, AKEYCODE_DPAD_RIGHT) &&
1046                hasKeycodeLocked(device, AKEYCODE_DPAD_CENTER)) {
1047            device->classes |= INPUT_DEVICE_CLASS_DPAD;
1048        }
1049
1050        // See if this device has a gamepad.
1051        for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES)/sizeof(GAMEPAD_KEYCODES[0]); i++) {
1052            if (hasKeycodeLocked(device, GAMEPAD_KEYCODES[i])) {
1053                device->classes |= INPUT_DEVICE_CLASS_GAMEPAD;
1054                break;
1055            }
1056        }
1057    }
1058
1059    // If the device isn't recognized as something we handle, don't monitor it.
1060    if (device->classes == 0) {
1061        ALOGV("Dropping device: id=%d, path='%s', name='%s'",
1062                deviceId, devicePath, device->identifier.name.string());
1063        delete device;
1064        return -1;
1065    }
1066
1067    // Determine whether the device is external or internal.
1068    if (isExternalDeviceLocked(device)) {
1069        device->classes |= INPUT_DEVICE_CLASS_EXTERNAL;
1070    }
1071
1072    // Register with epoll.
1073    struct epoll_event eventItem;
1074    memset(&eventItem, 0, sizeof(eventItem));
1075    eventItem.events = EPOLLIN;
1076    eventItem.data.u32 = deviceId;
1077    if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1078        ALOGE("Could not add device fd to epoll instance.  errno=%d", errno);
1079        delete device;
1080        return -1;
1081    }
1082
1083    // Enable wake-lock behavior on kernels that support it.
1084    // TODO: Only need this for devices that can really wake the system.
1085    bool usingSuspendBlockIoctl = !ioctl(fd, EVIOCSSUSPENDBLOCK, 1);
1086
1087    // Tell the kernel that we want to use the monotonic clock for reporting timestamps
1088    // associated with input events.  This is important because the input system
1089    // uses the timestamps extensively and assumes they were recorded using the monotonic
1090    // clock.
1091    //
1092    // In older kernel, before Linux 3.4, there was no way to tell the kernel which
1093    // clock to use to input event timestamps.  The standard kernel behavior was to
1094    // record a real time timestamp, which isn't what we want.  Android kernels therefore
1095    // contained a patch to the evdev_event() function in drivers/input/evdev.c to
1096    // replace the call to do_gettimeofday() with ktime_get_ts() to cause the monotonic
1097    // clock to be used instead of the real time clock.
1098    //
1099    // As of Linux 3.4, there is a new EVIOCSCLOCKID ioctl to set the desired clock.
1100    // Therefore, we no longer require the Android-specific kernel patch described above
1101    // as long as we make sure to set select the monotonic clock.  We do that here.
1102    bool usingClockIoctl = !ioctl(fd, EVIOCSCLOCKID, CLOCK_MONOTONIC);
1103
1104    ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=0x%x, "
1105            "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, "
1106            "usingSuspendBlockIoctl=%s, usingClockIoctl=%s",
1107         deviceId, fd, devicePath, device->identifier.name.string(),
1108         device->classes,
1109         device->configurationFile.string(),
1110         device->keyMap.keyLayoutFile.string(),
1111         device->keyMap.keyCharacterMapFile.string(),
1112         toString(mBuiltInKeyboardId == deviceId),
1113         toString(usingSuspendBlockIoctl), toString(usingClockIoctl));
1114
1115    addDeviceLocked(device);
1116    return 0;
1117}
1118
1119void EventHub::createVirtualKeyboardLocked() {
1120    InputDeviceIdentifier identifier;
1121    identifier.name = "Virtual";
1122    identifier.uniqueId = "<virtual>";
1123    setDescriptor(identifier);
1124
1125    Device* device = new Device(-1, VIRTUAL_KEYBOARD_ID, String8("<virtual>"), identifier);
1126    device->classes = INPUT_DEVICE_CLASS_KEYBOARD
1127            | INPUT_DEVICE_CLASS_ALPHAKEY
1128            | INPUT_DEVICE_CLASS_DPAD
1129            | INPUT_DEVICE_CLASS_VIRTUAL;
1130    loadKeyMapLocked(device);
1131    addDeviceLocked(device);
1132}
1133
1134void EventHub::addDeviceLocked(Device* device) {
1135    mDevices.add(device->id, device);
1136    device->next = mOpeningDevices;
1137    mOpeningDevices = device;
1138}
1139
1140void EventHub::loadConfigurationLocked(Device* device) {
1141    device->configurationFile = getInputDeviceConfigurationFilePathByDeviceIdentifier(
1142            device->identifier, INPUT_DEVICE_CONFIGURATION_FILE_TYPE_CONFIGURATION);
1143    if (device->configurationFile.isEmpty()) {
1144        ALOGD("No input device configuration file found for device '%s'.",
1145                device->identifier.name.string());
1146    } else {
1147        status_t status = PropertyMap::load(device->configurationFile,
1148                &device->configuration);
1149        if (status) {
1150            ALOGE("Error loading input device configuration file for device '%s'.  "
1151                    "Using default configuration.",
1152                    device->identifier.name.string());
1153        }
1154    }
1155}
1156
1157status_t EventHub::loadVirtualKeyMapLocked(Device* device) {
1158    // The virtual key map is supplied by the kernel as a system board property file.
1159    String8 path;
1160    path.append("/sys/board_properties/virtualkeys.");
1161    path.append(device->identifier.name);
1162    if (access(path.string(), R_OK)) {
1163        return NAME_NOT_FOUND;
1164    }
1165    return VirtualKeyMap::load(path, &device->virtualKeyMap);
1166}
1167
1168status_t EventHub::loadKeyMapLocked(Device* device) {
1169    return device->keyMap.load(device->identifier, device->configuration);
1170}
1171
1172bool EventHub::isExternalDeviceLocked(Device* device) {
1173    if (device->configuration) {
1174        bool value;
1175        if (device->configuration->tryGetProperty(String8("device.internal"), value)) {
1176            return !value;
1177        }
1178    }
1179    return device->identifier.bus == BUS_USB || device->identifier.bus == BUS_BLUETOOTH;
1180}
1181
1182bool EventHub::hasKeycodeLocked(Device* device, int keycode) const {
1183    if (!device->keyMap.haveKeyLayout() || !device->keyBitmask) {
1184        return false;
1185    }
1186
1187    Vector<int32_t> scanCodes;
1188    device->keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes);
1189    const size_t N = scanCodes.size();
1190    for (size_t i=0; i<N && i<=KEY_MAX; i++) {
1191        int32_t sc = scanCodes.itemAt(i);
1192        if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, device->keyBitmask)) {
1193            return true;
1194        }
1195    }
1196
1197    return false;
1198}
1199
1200status_t EventHub::closeDeviceByPathLocked(const char *devicePath) {
1201    Device* device = getDeviceByPathLocked(devicePath);
1202    if (device) {
1203        closeDeviceLocked(device);
1204        return 0;
1205    }
1206    ALOGV("Remove device: %s not found, device may already have been removed.", devicePath);
1207    return -1;
1208}
1209
1210void EventHub::closeAllDevicesLocked() {
1211    while (mDevices.size() > 0) {
1212        closeDeviceLocked(mDevices.valueAt(mDevices.size() - 1));
1213    }
1214}
1215
1216void EventHub::closeDeviceLocked(Device* device) {
1217    ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=0x%x\n",
1218         device->path.string(), device->identifier.name.string(), device->id,
1219         device->fd, device->classes);
1220
1221    if (device->id == mBuiltInKeyboardId) {
1222        ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
1223                device->path.string(), mBuiltInKeyboardId);
1224        mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
1225    }
1226
1227    if (!device->isVirtual()) {
1228        if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, device->fd, NULL)) {
1229            ALOGW("Could not remove device fd from epoll instance.  errno=%d", errno);
1230        }
1231    }
1232
1233    mDevices.removeItem(device->id);
1234    device->close();
1235
1236    // Unlink for opening devices list if it is present.
1237    Device* pred = NULL;
1238    bool found = false;
1239    for (Device* entry = mOpeningDevices; entry != NULL; ) {
1240        if (entry == device) {
1241            found = true;
1242            break;
1243        }
1244        pred = entry;
1245        entry = entry->next;
1246    }
1247    if (found) {
1248        // Unlink the device from the opening devices list then delete it.
1249        // We don't need to tell the client that the device was closed because
1250        // it does not even know it was opened in the first place.
1251        ALOGI("Device %s was immediately closed after opening.", device->path.string());
1252        if (pred) {
1253            pred->next = device->next;
1254        } else {
1255            mOpeningDevices = device->next;
1256        }
1257        delete device;
1258    } else {
1259        // Link into closing devices list.
1260        // The device will be deleted later after we have informed the client.
1261        device->next = mClosingDevices;
1262        mClosingDevices = device;
1263    }
1264}
1265
1266status_t EventHub::readNotifyLocked() {
1267    int res;
1268    char devname[PATH_MAX];
1269    char *filename;
1270    char event_buf[512];
1271    int event_size;
1272    int event_pos = 0;
1273    struct inotify_event *event;
1274
1275    ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
1276    res = read(mINotifyFd, event_buf, sizeof(event_buf));
1277    if(res < (int)sizeof(*event)) {
1278        if(errno == EINTR)
1279            return 0;
1280        ALOGW("could not get event, %s\n", strerror(errno));
1281        return -1;
1282    }
1283    //printf("got %d bytes of event information\n", res);
1284
1285    strcpy(devname, DEVICE_PATH);
1286    filename = devname + strlen(devname);
1287    *filename++ = '/';
1288
1289    while(res >= (int)sizeof(*event)) {
1290        event = (struct inotify_event *)(event_buf + event_pos);
1291        //printf("%d: %08x \"%s\"\n", event->wd, event->mask, event->len ? event->name : "");
1292        if(event->len) {
1293            strcpy(filename, event->name);
1294            if(event->mask & IN_CREATE) {
1295                openDeviceLocked(devname);
1296            } else {
1297                ALOGI("Removing device '%s' due to inotify event\n", devname);
1298                closeDeviceByPathLocked(devname);
1299            }
1300        }
1301        event_size = sizeof(*event) + event->len;
1302        res -= event_size;
1303        event_pos += event_size;
1304    }
1305    return 0;
1306}
1307
1308status_t EventHub::scanDirLocked(const char *dirname)
1309{
1310    char devname[PATH_MAX];
1311    char *filename;
1312    DIR *dir;
1313    struct dirent *de;
1314    dir = opendir(dirname);
1315    if(dir == NULL)
1316        return -1;
1317    strcpy(devname, dirname);
1318    filename = devname + strlen(devname);
1319    *filename++ = '/';
1320    while((de = readdir(dir))) {
1321        if(de->d_name[0] == '.' &&
1322           (de->d_name[1] == '\0' ||
1323            (de->d_name[1] == '.' && de->d_name[2] == '\0')))
1324            continue;
1325        strcpy(filename, de->d_name);
1326        openDeviceLocked(devname);
1327    }
1328    closedir(dir);
1329    return 0;
1330}
1331
1332void EventHub::requestReopenDevices() {
1333    ALOGV("requestReopenDevices() called");
1334
1335    AutoMutex _l(mLock);
1336    mNeedToReopenDevices = true;
1337}
1338
1339void EventHub::dump(String8& dump) {
1340    dump.append("Event Hub State:\n");
1341
1342    { // acquire lock
1343        AutoMutex _l(mLock);
1344
1345        dump.appendFormat(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
1346
1347        dump.append(INDENT "Devices:\n");
1348
1349        for (size_t i = 0; i < mDevices.size(); i++) {
1350            const Device* device = mDevices.valueAt(i);
1351            if (mBuiltInKeyboardId == device->id) {
1352                dump.appendFormat(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
1353                        device->id, device->identifier.name.string());
1354            } else {
1355                dump.appendFormat(INDENT2 "%d: %s\n", device->id,
1356                        device->identifier.name.string());
1357            }
1358            dump.appendFormat(INDENT3 "Classes: 0x%08x\n", device->classes);
1359            dump.appendFormat(INDENT3 "Path: %s\n", device->path.string());
1360            dump.appendFormat(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.string());
1361            dump.appendFormat(INDENT3 "Location: %s\n", device->identifier.location.string());
1362            dump.appendFormat(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.string());
1363            dump.appendFormat(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
1364                    "product=0x%04x, version=0x%04x\n",
1365                    device->identifier.bus, device->identifier.vendor,
1366                    device->identifier.product, device->identifier.version);
1367            dump.appendFormat(INDENT3 "KeyLayoutFile: %s\n",
1368                    device->keyMap.keyLayoutFile.string());
1369            dump.appendFormat(INDENT3 "KeyCharacterMapFile: %s\n",
1370                    device->keyMap.keyCharacterMapFile.string());
1371            dump.appendFormat(INDENT3 "ConfigurationFile: %s\n",
1372                    device->configurationFile.string());
1373        }
1374    } // release lock
1375}
1376
1377void EventHub::monitor() {
1378    // Acquire and release the lock to ensure that the event hub has not deadlocked.
1379    mLock.lock();
1380    mLock.unlock();
1381}
1382
1383
1384}; // namespace android
1385