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