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