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