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