OSDN Git Service

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