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