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