OSDN Git Service

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