OSDN Git Service

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