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