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