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