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