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