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 <android-base/stringprintf.h> 43 #include <cutils/properties.h> 44 #include <openssl/sha.h> 45 #include <utils/Log.h> 46 #include <utils/Timers.h> 47 #include <utils/threads.h> 48 #include <utils/Errors.h> 49 50 #include <input/KeyLayoutMap.h> 51 #include <input/KeyCharacterMap.h> 52 #include <input/VirtualKeyMap.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 68 using android::base::StringPrintf; 69 70 namespace android { 71 72 static constexpr bool DEBUG = false; 73 74 static const char *WAKE_LOCK_ID = "KeyEvents"; 75 static const char *DEVICE_PATH = "/dev/input"; 76 // v4l2 devices go directly into /dev 77 static const char *VIDEO_DEVICE_PATH = "/dev"; 78 79 static inline const char* toString(bool value) { 80 return value ? "true" : "false"; 81 } 82 83 static std::string sha1(const std::string& in) { 84 SHA_CTX ctx; 85 SHA1_Init(&ctx); 86 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size()); 87 u_char digest[SHA_DIGEST_LENGTH]; 88 SHA1_Final(digest, &ctx); 89 90 std::string out; 91 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) { 92 out += StringPrintf("%02x", digest[i]); 93 } 94 return out; 95 } 96 97 static 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 /** 106 * Return true if name matches "v4l-touch*" 107 */ 108 static bool isV4lTouchNode(const char* name) { 109 return strstr(name, "v4l-touch") == name; 110 } 111 112 /** 113 * Returns true if V4L devices should be scanned. 114 * 115 * The system property ro.input.video_enabled can be used to control whether 116 * EventHub scans and opens V4L devices. As V4L does not support multiple 117 * clients, EventHub effectively blocks access to these devices when it opens 118 * them. 119 * 120 * Setting this to "false" would prevent any video devices from being discovered and 121 * associated with input devices. 122 * 123 * This property can be used as follows: 124 * 1. To turn off features that are dependent on video device presence. 125 * 2. During testing and development, to allow other clients to read video devices 126 * directly from /dev. 127 */ 128 static bool isV4lScanningEnabled() { 129 return property_get_bool("ro.input.video_enabled", true /* default_value */); 130 } 131 132 static nsecs_t processEventTimestamp(const struct input_event& event) { 133 // Use the time specified in the event instead of the current time 134 // so that downstream code can get more accurate estimates of 135 // event dispatch latency from the time the event is enqueued onto 136 // the evdev client buffer. 137 // 138 // The event's timestamp fortuitously uses the same monotonic clock 139 // time base as the rest of Android. The kernel event device driver 140 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts(). 141 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere 142 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a 143 // system call that also queries ktime_get_ts(). 144 145 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.time.tv_sec) + 146 microseconds_to_nanoseconds(event.time.tv_usec); 147 return inputEventTime; 148 } 149 150 // --- Global Functions --- 151 152 uint32_t getAbsAxisUsage(int32_t axis, uint32_t deviceClasses) { 153 // Touch devices get dibs on touch-related axes. 154 if (deviceClasses & INPUT_DEVICE_CLASS_TOUCH) { 155 switch (axis) { 156 case ABS_X: 157 case ABS_Y: 158 case ABS_PRESSURE: 159 case ABS_TOOL_WIDTH: 160 case ABS_DISTANCE: 161 case ABS_TILT_X: 162 case ABS_TILT_Y: 163 case ABS_MT_SLOT: 164 case ABS_MT_TOUCH_MAJOR: 165 case ABS_MT_TOUCH_MINOR: 166 case ABS_MT_WIDTH_MAJOR: 167 case ABS_MT_WIDTH_MINOR: 168 case ABS_MT_ORIENTATION: 169 case ABS_MT_POSITION_X: 170 case ABS_MT_POSITION_Y: 171 case ABS_MT_TOOL_TYPE: 172 case ABS_MT_BLOB_ID: 173 case ABS_MT_TRACKING_ID: 174 case ABS_MT_PRESSURE: 175 case ABS_MT_DISTANCE: 176 return INPUT_DEVICE_CLASS_TOUCH; 177 } 178 } 179 180 // External stylus gets the pressure axis 181 if (deviceClasses & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) { 182 if (axis == ABS_PRESSURE) { 183 return INPUT_DEVICE_CLASS_EXTERNAL_STYLUS; 184 } 185 } 186 187 // Joystick devices get the rest. 188 return deviceClasses & INPUT_DEVICE_CLASS_JOYSTICK; 189 } 190 191 // --- EventHub::Device --- 192 193 EventHub::Device::Device(int fd, int32_t id, const std::string& path, 194 const InputDeviceIdentifier& identifier) : 195 next(nullptr), 196 fd(fd), id(id), path(path), identifier(identifier), 197 classes(0), configuration(nullptr), virtualKeyMap(nullptr), 198 ffEffectPlaying(false), ffEffectId(-1), controllerNumber(0), 199 enabled(true), isVirtual(fd < 0) { 200 memset(keyBitmask, 0, sizeof(keyBitmask)); 201 memset(absBitmask, 0, sizeof(absBitmask)); 202 memset(relBitmask, 0, sizeof(relBitmask)); 203 memset(swBitmask, 0, sizeof(swBitmask)); 204 memset(ledBitmask, 0, sizeof(ledBitmask)); 205 memset(ffBitmask, 0, sizeof(ffBitmask)); 206 memset(propBitmask, 0, sizeof(propBitmask)); 207 } 208 209 EventHub::Device::~Device() { 210 close(); 211 delete configuration; 212 } 213 214 void EventHub::Device::close() { 215 if (fd >= 0) { 216 ::close(fd); 217 fd = -1; 218 } 219 } 220 221 status_t EventHub::Device::enable() { 222 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK); 223 if(fd < 0) { 224 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno)); 225 return -errno; 226 } 227 enabled = true; 228 return OK; 229 } 230 231 status_t EventHub::Device::disable() { 232 close(); 233 enabled = false; 234 return OK; 235 } 236 237 bool EventHub::Device::hasValidFd() { 238 return !isVirtual && enabled; 239 } 240 241 // --- EventHub --- 242 243 const int EventHub::EPOLL_MAX_EVENTS; 244 245 EventHub::EventHub(void) : 246 mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD), mNextDeviceId(1), mControllerNumbers(), 247 mOpeningDevices(nullptr), mClosingDevices(nullptr), 248 mNeedToSendFinishedDeviceScan(false), 249 mNeedToReopenDevices(false), mNeedToScanDevices(true), 250 mPendingEventCount(0), mPendingEventIndex(0), mPendingINotify(false) { 251 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID); 252 253 mEpollFd = epoll_create1(EPOLL_CLOEXEC); 254 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno)); 255 256 mINotifyFd = inotify_init(); 257 mInputWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE); 258 LOG_ALWAYS_FATAL_IF(mInputWd < 0, "Could not register INotify for %s: %s", 259 DEVICE_PATH, strerror(errno)); 260 if (isV4lScanningEnabled()) { 261 mVideoWd = inotify_add_watch(mINotifyFd, VIDEO_DEVICE_PATH, IN_DELETE | IN_CREATE); 262 LOG_ALWAYS_FATAL_IF(mVideoWd < 0, "Could not register INotify for %s: %s", 263 VIDEO_DEVICE_PATH, strerror(errno)); 264 } else { 265 mVideoWd = -1; 266 ALOGI("Video device scanning disabled"); 267 } 268 269 struct epoll_event eventItem; 270 memset(&eventItem, 0, sizeof(eventItem)); 271 eventItem.events = EPOLLIN; 272 eventItem.data.fd = mINotifyFd; 273 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem); 274 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno); 275 276 int wakeFds[2]; 277 result = pipe(wakeFds); 278 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno); 279 280 mWakeReadPipeFd = wakeFds[0]; 281 mWakeWritePipeFd = wakeFds[1]; 282 283 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK); 284 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d", 285 errno); 286 287 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK); 288 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d", 289 errno); 290 291 eventItem.data.fd = mWakeReadPipeFd; 292 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem); 293 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d", 294 errno); 295 296 int major, minor; 297 getLinuxRelease(&major, &minor); 298 // EPOLLWAKEUP was introduced in kernel 3.5 299 mUsingEpollWakeup = major > 3 || (major == 3 && minor >= 5); 300 } 301 302 EventHub::~EventHub(void) { 303 closeAllDevicesLocked(); 304 305 while (mClosingDevices) { 306 Device* device = mClosingDevices; 307 mClosingDevices = device->next; 308 delete device; 309 } 310 311 ::close(mEpollFd); 312 ::close(mINotifyFd); 313 ::close(mWakeReadPipeFd); 314 ::close(mWakeWritePipeFd); 315 316 release_wake_lock(WAKE_LOCK_ID); 317 } 318 319 InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const { 320 AutoMutex _l(mLock); 321 Device* device = getDeviceLocked(deviceId); 322 if (device == nullptr) return InputDeviceIdentifier(); 323 return device->identifier; 324 } 325 326 uint32_t EventHub::getDeviceClasses(int32_t deviceId) const { 327 AutoMutex _l(mLock); 328 Device* device = getDeviceLocked(deviceId); 329 if (device == nullptr) return 0; 330 return device->classes; 331 } 332 333 int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const { 334 AutoMutex _l(mLock); 335 Device* device = getDeviceLocked(deviceId); 336 if (device == nullptr) return 0; 337 return device->controllerNumber; 338 } 339 340 void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const { 341 AutoMutex _l(mLock); 342 Device* device = getDeviceLocked(deviceId); 343 if (device && device->configuration) { 344 *outConfiguration = *device->configuration; 345 } else { 346 outConfiguration->clear(); 347 } 348 } 349 350 status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis, 351 RawAbsoluteAxisInfo* outAxisInfo) const { 352 outAxisInfo->clear(); 353 354 if (axis >= 0 && axis <= ABS_MAX) { 355 AutoMutex _l(mLock); 356 357 Device* device = getDeviceLocked(deviceId); 358 if (device && device->hasValidFd() && test_bit(axis, device->absBitmask)) { 359 struct input_absinfo info; 360 if(ioctl(device->fd, EVIOCGABS(axis), &info)) { 361 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", 362 axis, device->identifier.name.c_str(), device->fd, errno); 363 return -errno; 364 } 365 366 if (info.minimum != info.maximum) { 367 outAxisInfo->valid = true; 368 outAxisInfo->minValue = info.minimum; 369 outAxisInfo->maxValue = info.maximum; 370 outAxisInfo->flat = info.flat; 371 outAxisInfo->fuzz = info.fuzz; 372 outAxisInfo->resolution = info.resolution; 373 } 374 return OK; 375 } 376 } 377 return -1; 378 } 379 380 bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const { 381 if (axis >= 0 && axis <= REL_MAX) { 382 AutoMutex _l(mLock); 383 384 Device* device = getDeviceLocked(deviceId); 385 if (device) { 386 return test_bit(axis, device->relBitmask); 387 } 388 } 389 return false; 390 } 391 392 bool EventHub::hasInputProperty(int32_t deviceId, int property) const { 393 if (property >= 0 && property <= INPUT_PROP_MAX) { 394 AutoMutex _l(mLock); 395 396 Device* device = getDeviceLocked(deviceId); 397 if (device) { 398 return test_bit(property, device->propBitmask); 399 } 400 } 401 return false; 402 } 403 404 int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const { 405 if (scanCode >= 0 && scanCode <= KEY_MAX) { 406 AutoMutex _l(mLock); 407 408 Device* device = getDeviceLocked(deviceId); 409 if (device && device->hasValidFd() && test_bit(scanCode, device->keyBitmask)) { 410 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)]; 411 memset(keyState, 0, sizeof(keyState)); 412 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) { 413 return test_bit(scanCode, keyState) ? AKEY_STATE_DOWN : AKEY_STATE_UP; 414 } 415 } 416 } 417 return AKEY_STATE_UNKNOWN; 418 } 419 420 int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const { 421 AutoMutex _l(mLock); 422 423 Device* device = getDeviceLocked(deviceId); 424 if (device && device->hasValidFd() && device->keyMap.haveKeyLayout()) { 425 std::vector<int32_t> scanCodes; 426 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode, &scanCodes); 427 if (scanCodes.size() != 0) { 428 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)]; 429 memset(keyState, 0, sizeof(keyState)); 430 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) { 431 for (size_t i = 0; i < scanCodes.size(); i++) { 432 int32_t sc = scanCodes[i]; 433 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, keyState)) { 434 return AKEY_STATE_DOWN; 435 } 436 } 437 return AKEY_STATE_UP; 438 } 439 } 440 } 441 return AKEY_STATE_UNKNOWN; 442 } 443 444 int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const { 445 if (sw >= 0 && sw <= SW_MAX) { 446 AutoMutex _l(mLock); 447 448 Device* device = getDeviceLocked(deviceId); 449 if (device && device->hasValidFd() && test_bit(sw, device->swBitmask)) { 450 uint8_t swState[sizeof_bit_array(SW_MAX + 1)]; 451 memset(swState, 0, sizeof(swState)); 452 if (ioctl(device->fd, EVIOCGSW(sizeof(swState)), swState) >= 0) { 453 return test_bit(sw, swState) ? AKEY_STATE_DOWN : AKEY_STATE_UP; 454 } 455 } 456 } 457 return AKEY_STATE_UNKNOWN; 458 } 459 460 status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const { 461 *outValue = 0; 462 463 if (axis >= 0 && axis <= ABS_MAX) { 464 AutoMutex _l(mLock); 465 466 Device* device = getDeviceLocked(deviceId); 467 if (device && device->hasValidFd() && test_bit(axis, device->absBitmask)) { 468 struct input_absinfo info; 469 if(ioctl(device->fd, EVIOCGABS(axis), &info)) { 470 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", 471 axis, device->identifier.name.c_str(), device->fd, errno); 472 return -errno; 473 } 474 475 *outValue = info.value; 476 return OK; 477 } 478 } 479 return -1; 480 } 481 482 bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes, 483 const int32_t* keyCodes, uint8_t* outFlags) const { 484 AutoMutex _l(mLock); 485 486 Device* device = getDeviceLocked(deviceId); 487 if (device && device->keyMap.haveKeyLayout()) { 488 std::vector<int32_t> scanCodes; 489 for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) { 490 scanCodes.clear(); 491 492 status_t err = device->keyMap.keyLayoutMap->findScanCodesForKey( 493 keyCodes[codeIndex], &scanCodes); 494 if (! err) { 495 // check the possible scan codes identified by the layout map against the 496 // map of codes actually emitted by the driver 497 for (size_t sc = 0; sc < scanCodes.size(); sc++) { 498 if (test_bit(scanCodes[sc], device->keyBitmask)) { 499 outFlags[codeIndex] = 1; 500 break; 501 } 502 } 503 } 504 } 505 return true; 506 } 507 return false; 508 } 509 510 status_t EventHub::mapKey(int32_t deviceId, 511 int32_t scanCode, int32_t usageCode, int32_t metaState, 512 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const { 513 AutoMutex _l(mLock); 514 Device* device = getDeviceLocked(deviceId); 515 status_t status = NAME_NOT_FOUND; 516 517 if (device) { 518 // Check the key character map first. 519 sp<KeyCharacterMap> kcm = device->getKeyCharacterMap(); 520 if (kcm != nullptr) { 521 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) { 522 *outFlags = 0; 523 status = NO_ERROR; 524 } 525 } 526 527 // Check the key layout next. 528 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) { 529 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) { 530 status = NO_ERROR; 531 } 532 } 533 534 if (status == NO_ERROR) { 535 if (kcm != nullptr) { 536 kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState); 537 } else { 538 *outMetaState = metaState; 539 } 540 } 541 } 542 543 if (status != NO_ERROR) { 544 *outKeycode = 0; 545 *outFlags = 0; 546 *outMetaState = metaState; 547 } 548 549 return status; 550 } 551 552 status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const { 553 AutoMutex _l(mLock); 554 Device* device = getDeviceLocked(deviceId); 555 556 if (device && device->keyMap.haveKeyLayout()) { 557 status_t err = device->keyMap.keyLayoutMap->mapAxis(scanCode, outAxisInfo); 558 if (err == NO_ERROR) { 559 return NO_ERROR; 560 } 561 } 562 563 return NAME_NOT_FOUND; 564 } 565 566 void EventHub::setExcludedDevices(const std::vector<std::string>& devices) { 567 AutoMutex _l(mLock); 568 569 mExcludedDevices = devices; 570 } 571 572 bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const { 573 AutoMutex _l(mLock); 574 Device* device = getDeviceLocked(deviceId); 575 if (device && scanCode >= 0 && scanCode <= KEY_MAX) { 576 if (test_bit(scanCode, device->keyBitmask)) { 577 return true; 578 } 579 } 580 return false; 581 } 582 583 bool EventHub::hasLed(int32_t deviceId, int32_t led) const { 584 AutoMutex _l(mLock); 585 Device* device = getDeviceLocked(deviceId); 586 int32_t sc; 587 if (device && mapLed(device, led, &sc) == NO_ERROR) { 588 if (test_bit(sc, device->ledBitmask)) { 589 return true; 590 } 591 } 592 return false; 593 } 594 595 void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) { 596 AutoMutex _l(mLock); 597 Device* device = getDeviceLocked(deviceId); 598 setLedStateLocked(device, led, on); 599 } 600 601 void EventHub::setLedStateLocked(Device* device, int32_t led, bool on) { 602 int32_t sc; 603 if (device && device->hasValidFd() && mapLed(device, led, &sc) != NAME_NOT_FOUND) { 604 struct input_event ev; 605 ev.time.tv_sec = 0; 606 ev.time.tv_usec = 0; 607 ev.type = EV_LED; 608 ev.code = sc; 609 ev.value = on ? 1 : 0; 610 611 ssize_t nWrite; 612 do { 613 nWrite = write(device->fd, &ev, sizeof(struct input_event)); 614 } while (nWrite == -1 && errno == EINTR); 615 } 616 } 617 618 void EventHub::getVirtualKeyDefinitions(int32_t deviceId, 619 std::vector<VirtualKeyDefinition>& outVirtualKeys) const { 620 outVirtualKeys.clear(); 621 622 AutoMutex _l(mLock); 623 Device* device = getDeviceLocked(deviceId); 624 if (device && device->virtualKeyMap) { 625 const std::vector<VirtualKeyDefinition> virtualKeys = 626 device->virtualKeyMap->getVirtualKeys(); 627 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end()); 628 } 629 } 630 631 sp<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const { 632 AutoMutex _l(mLock); 633 Device* device = getDeviceLocked(deviceId); 634 if (device) { 635 return device->getKeyCharacterMap(); 636 } 637 return nullptr; 638 } 639 640 bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, 641 const sp<KeyCharacterMap>& map) { 642 AutoMutex _l(mLock); 643 Device* device = getDeviceLocked(deviceId); 644 if (device) { 645 if (map != device->overlayKeyMap) { 646 device->overlayKeyMap = map; 647 device->combinedKeyMap = KeyCharacterMap::combine( 648 device->keyMap.keyCharacterMap, map); 649 return true; 650 } 651 } 652 return false; 653 } 654 655 static std::string generateDescriptor(InputDeviceIdentifier& identifier) { 656 std::string rawDescriptor; 657 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, 658 identifier.product); 659 // TODO add handling for USB devices to not uniqueify kbs that show up twice 660 if (!identifier.uniqueId.empty()) { 661 rawDescriptor += "uniqueId:"; 662 rawDescriptor += identifier.uniqueId; 663 } else if (identifier.nonce != 0) { 664 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce); 665 } 666 667 if (identifier.vendor == 0 && identifier.product == 0) { 668 // If we don't know the vendor and product id, then the device is probably 669 // built-in so we need to rely on other information to uniquely identify 670 // the input device. Usually we try to avoid relying on the device name or 671 // location but for built-in input device, they are unlikely to ever change. 672 if (!identifier.name.empty()) { 673 rawDescriptor += "name:"; 674 rawDescriptor += identifier.name; 675 } else if (!identifier.location.empty()) { 676 rawDescriptor += "location:"; 677 rawDescriptor += identifier.location; 678 } 679 } 680 identifier.descriptor = sha1(rawDescriptor); 681 return rawDescriptor; 682 } 683 684 void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) { 685 // Compute a device descriptor that uniquely identifies the device. 686 // The descriptor is assumed to be a stable identifier. Its value should not 687 // change between reboots, reconnections, firmware updates or new releases 688 // of Android. In practice we sometimes get devices that cannot be uniquely 689 // identified. In this case we enforce uniqueness between connected devices. 690 // Ideally, we also want the descriptor to be short and relatively opaque. 691 692 identifier.nonce = 0; 693 std::string rawDescriptor = generateDescriptor(identifier); 694 if (identifier.uniqueId.empty()) { 695 // If it didn't have a unique id check for conflicts and enforce 696 // uniqueness if necessary. 697 while(getDeviceByDescriptorLocked(identifier.descriptor) != nullptr) { 698 identifier.nonce++; 699 rawDescriptor = generateDescriptor(identifier); 700 } 701 } 702 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(), 703 identifier.descriptor.c_str()); 704 } 705 706 void EventHub::vibrate(int32_t deviceId, nsecs_t duration) { 707 AutoMutex _l(mLock); 708 Device* device = getDeviceLocked(deviceId); 709 if (device && device->hasValidFd()) { 710 ff_effect effect; 711 memset(&effect, 0, sizeof(effect)); 712 effect.type = FF_RUMBLE; 713 effect.id = device->ffEffectId; 714 effect.u.rumble.strong_magnitude = 0xc000; 715 effect.u.rumble.weak_magnitude = 0xc000; 716 effect.replay.length = (duration + 999999LL) / 1000000LL; 717 effect.replay.delay = 0; 718 if (ioctl(device->fd, EVIOCSFF, &effect)) { 719 ALOGW("Could not upload force feedback effect to device %s due to error %d.", 720 device->identifier.name.c_str(), errno); 721 return; 722 } 723 device->ffEffectId = effect.id; 724 725 struct input_event ev; 726 ev.time.tv_sec = 0; 727 ev.time.tv_usec = 0; 728 ev.type = EV_FF; 729 ev.code = device->ffEffectId; 730 ev.value = 1; 731 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) { 732 ALOGW("Could not start force feedback effect on device %s due to error %d.", 733 device->identifier.name.c_str(), errno); 734 return; 735 } 736 device->ffEffectPlaying = true; 737 } 738 } 739 740 void EventHub::cancelVibrate(int32_t deviceId) { 741 AutoMutex _l(mLock); 742 Device* device = getDeviceLocked(deviceId); 743 if (device && device->hasValidFd()) { 744 if (device->ffEffectPlaying) { 745 device->ffEffectPlaying = false; 746 747 struct input_event ev; 748 ev.time.tv_sec = 0; 749 ev.time.tv_usec = 0; 750 ev.type = EV_FF; 751 ev.code = device->ffEffectId; 752 ev.value = 0; 753 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) { 754 ALOGW("Could not stop force feedback effect on device %s due to error %d.", 755 device->identifier.name.c_str(), errno); 756 return; 757 } 758 } 759 } 760 } 761 762 EventHub::Device* EventHub::getDeviceByDescriptorLocked(const std::string& descriptor) const { 763 size_t size = mDevices.size(); 764 for (size_t i = 0; i < size; i++) { 765 Device* device = mDevices.valueAt(i); 766 if (descriptor == device->identifier.descriptor) { 767 return device; 768 } 769 } 770 return nullptr; 771 } 772 773 EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const { 774 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) { 775 deviceId = mBuiltInKeyboardId; 776 } 777 ssize_t index = mDevices.indexOfKey(deviceId); 778 return index >= 0 ? mDevices.valueAt(index) : NULL; 779 } 780 781 EventHub::Device* EventHub::getDeviceByPathLocked(const char* devicePath) const { 782 for (size_t i = 0; i < mDevices.size(); i++) { 783 Device* device = mDevices.valueAt(i); 784 if (device->path == devicePath) { 785 return device; 786 } 787 } 788 return nullptr; 789 } 790 791 /** 792 * The file descriptor could be either input device, or a video device (associated with a 793 * specific input device). Check both cases here, and return the device that this event 794 * belongs to. Caller can compare the fd's once more to determine event type. 795 * Looks through all input devices, and only attached video devices. Unattached video 796 * devices are ignored. 797 */ 798 EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const { 799 for (size_t i = 0; i < mDevices.size(); i++) { 800 Device* device = mDevices.valueAt(i); 801 if (device->fd == fd) { 802 // This is an input device event 803 return device; 804 } 805 if (device->videoDevice && device->videoDevice->getFd() == fd) { 806 // This is a video device event 807 return device; 808 } 809 } 810 // We do not check mUnattachedVideoDevices here because they should not participate in epoll, 811 // and therefore should never be looked up by fd. 812 return nullptr; 813 } 814 815 size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) { 816 ALOG_ASSERT(bufferSize >= 1); 817 818 AutoMutex _l(mLock); 819 820 struct input_event readBuffer[bufferSize]; 821 822 RawEvent* event = buffer; 823 size_t capacity = bufferSize; 824 bool awoken = false; 825 for (;;) { 826 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC); 827 828 // Reopen input devices if needed. 829 if (mNeedToReopenDevices) { 830 mNeedToReopenDevices = false; 831 832 ALOGI("Reopening all input devices due to a configuration change."); 833 834 closeAllDevicesLocked(); 835 mNeedToScanDevices = true; 836 break; // return to the caller before we actually rescan 837 } 838 839 // Report any devices that had last been added/removed. 840 while (mClosingDevices) { 841 Device* device = mClosingDevices; 842 ALOGV("Reporting device closed: id=%d, name=%s\n", 843 device->id, device->path.c_str()); 844 mClosingDevices = device->next; 845 event->when = now; 846 event->deviceId = (device->id == mBuiltInKeyboardId) ? 847 ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID : device->id; 848 event->type = DEVICE_REMOVED; 849 event += 1; 850 delete device; 851 mNeedToSendFinishedDeviceScan = true; 852 if (--capacity == 0) { 853 break; 854 } 855 } 856 857 if (mNeedToScanDevices) { 858 mNeedToScanDevices = false; 859 scanDevicesLocked(); 860 mNeedToSendFinishedDeviceScan = true; 861 } 862 863 while (mOpeningDevices != nullptr) { 864 Device* device = mOpeningDevices; 865 ALOGV("Reporting device opened: id=%d, name=%s\n", 866 device->id, device->path.c_str()); 867 mOpeningDevices = device->next; 868 event->when = now; 869 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id; 870 event->type = DEVICE_ADDED; 871 event += 1; 872 mNeedToSendFinishedDeviceScan = true; 873 if (--capacity == 0) { 874 break; 875 } 876 } 877 878 if (mNeedToSendFinishedDeviceScan) { 879 mNeedToSendFinishedDeviceScan = false; 880 event->when = now; 881 event->type = FINISHED_DEVICE_SCAN; 882 event += 1; 883 if (--capacity == 0) { 884 break; 885 } 886 } 887 888 // Grab the next input event. 889 bool deviceChanged = false; 890 while (mPendingEventIndex < mPendingEventCount) { 891 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++]; 892 if (eventItem.data.fd == mINotifyFd) { 893 if (eventItem.events & EPOLLIN) { 894 mPendingINotify = true; 895 } else { 896 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events); 897 } 898 continue; 899 } 900 901 if (eventItem.data.fd == mWakeReadPipeFd) { 902 if (eventItem.events & EPOLLIN) { 903 ALOGV("awoken after wake()"); 904 awoken = true; 905 char buffer[16]; 906 ssize_t nRead; 907 do { 908 nRead = read(mWakeReadPipeFd, buffer, sizeof(buffer)); 909 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(buffer)); 910 } else { 911 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.", 912 eventItem.events); 913 } 914 continue; 915 } 916 917 Device* device = getDeviceByFdLocked(eventItem.data.fd); 918 if (!device) { 919 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", 920 eventItem.events, eventItem.data.fd); 921 ALOG_ASSERT(!DEBUG); 922 continue; 923 } 924 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) { 925 if (eventItem.events & EPOLLIN) { 926 size_t numFrames = device->videoDevice->readAndQueueFrames(); 927 if (numFrames == 0) { 928 ALOGE("Received epoll event for video device %s, but could not read frame", 929 device->videoDevice->getName().c_str()); 930 } 931 } else if (eventItem.events & EPOLLHUP) { 932 // TODO(b/121395353) - consider adding EPOLLRDHUP 933 ALOGI("Removing video device %s due to epoll hang-up event.", 934 device->videoDevice->getName().c_str()); 935 unregisterVideoDeviceFromEpollLocked(*device->videoDevice); 936 device->videoDevice = nullptr; 937 } else { 938 ALOGW("Received unexpected epoll event 0x%08x for device %s.", 939 eventItem.events, device->videoDevice->getName().c_str()); 940 ALOG_ASSERT(!DEBUG); 941 } 942 continue; 943 } 944 // This must be an input event 945 if (eventItem.events & EPOLLIN) { 946 int32_t readSize = read(device->fd, readBuffer, 947 sizeof(struct input_event) * capacity); 948 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) { 949 // Device was removed before INotify noticed. 950 ALOGW("could not get event, removed? (fd: %d size: %" PRId32 951 " bufferSize: %zu capacity: %zu errno: %d)\n", 952 device->fd, readSize, bufferSize, capacity, errno); 953 deviceChanged = true; 954 closeDeviceLocked(device); 955 } else if (readSize < 0) { 956 if (errno != EAGAIN && errno != EINTR) { 957 ALOGW("could not get event (errno=%d)", errno); 958 } 959 } else if ((readSize % sizeof(struct input_event)) != 0) { 960 ALOGE("could not get event (wrong size: %d)", readSize); 961 } else { 962 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id; 963 964 size_t count = size_t(readSize) / sizeof(struct input_event); 965 for (size_t i = 0; i < count; i++) { 966 struct input_event& iev = readBuffer[i]; 967 event->when = processEventTimestamp(iev); 968 event->deviceId = deviceId; 969 event->type = iev.type; 970 event->code = iev.code; 971 event->value = iev.value; 972 event += 1; 973 capacity -= 1; 974 } 975 if (capacity == 0) { 976 // The result buffer is full. Reset the pending event index 977 // so we will try to read the device again on the next iteration. 978 mPendingEventIndex -= 1; 979 break; 980 } 981 } 982 } else if (eventItem.events & EPOLLHUP) { 983 ALOGI("Removing device %s due to epoll hang-up event.", 984 device->identifier.name.c_str()); 985 deviceChanged = true; 986 closeDeviceLocked(device); 987 } else { 988 ALOGW("Received unexpected epoll event 0x%08x for device %s.", 989 eventItem.events, device->identifier.name.c_str()); 990 } 991 } 992 993 // readNotify() will modify the list of devices so this must be done after 994 // processing all other events to ensure that we read all remaining events 995 // before closing the devices. 996 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) { 997 mPendingINotify = false; 998 readNotifyLocked(); 999 deviceChanged = true; 1000 } 1001 1002 // Report added or removed devices immediately. 1003 if (deviceChanged) { 1004 continue; 1005 } 1006 1007 // Return now if we have collected any events or if we were explicitly awoken. 1008 if (event != buffer || awoken) { 1009 break; 1010 } 1011 1012 // Poll for events. Mind the wake lock dance! 1013 // We hold a wake lock at all times except during epoll_wait(). This works due to some 1014 // subtle choreography. When a device driver has pending (unread) events, it acquires 1015 // a kernel wake lock. However, once the last pending event has been read, the device 1016 // driver will release the kernel wake lock. To prevent the system from going to sleep 1017 // when this happens, the EventHub holds onto its own user wake lock while the client 1018 // is processing events. Thus the system can only sleep if there are no events 1019 // pending or currently being processed. 1020 // 1021 // The timeout is advisory only. If the device is asleep, it will not wake just to 1022 // service the timeout. 1023 mPendingEventIndex = 0; 1024 1025 mLock.unlock(); // release lock before poll, must be before release_wake_lock 1026 release_wake_lock(WAKE_LOCK_ID); 1027 1028 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis); 1029 1030 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID); 1031 mLock.lock(); // reacquire lock after poll, must be after acquire_wake_lock 1032 1033 if (pollResult == 0) { 1034 // Timed out. 1035 mPendingEventCount = 0; 1036 break; 1037 } 1038 1039 if (pollResult < 0) { 1040 // An error occurred. 1041 mPendingEventCount = 0; 1042 1043 // Sleep after errors to avoid locking up the system. 1044 // Hopefully the error is transient. 1045 if (errno != EINTR) { 1046 ALOGW("poll failed (errno=%d)\n", errno); 1047 usleep(100000); 1048 } 1049 } else { 1050 // Some events occurred. 1051 mPendingEventCount = size_t(pollResult); 1052 } 1053 } 1054 1055 // All done, return the number of events we read. 1056 return event - buffer; 1057 } 1058 1059 std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) { 1060 AutoMutex _l(mLock); 1061 1062 Device* device = getDeviceLocked(deviceId); 1063 if (!device || !device->videoDevice) { 1064 return {}; 1065 } 1066 return device->videoDevice->consumeFrames(); 1067 } 1068 1069 void EventHub::wake() { 1070 ALOGV("wake() called"); 1071 1072 ssize_t nWrite; 1073 do { 1074 nWrite = write(mWakeWritePipeFd, "W", 1); 1075 } while (nWrite == -1 && errno == EINTR); 1076 1077 if (nWrite != 1 && errno != EAGAIN) { 1078 ALOGW("Could not write wake signal: %s", strerror(errno)); 1079 } 1080 } 1081 1082 void EventHub::scanDevicesLocked() { 1083 status_t result = scanDirLocked(DEVICE_PATH); 1084 if(result < 0) { 1085 ALOGE("scan dir failed for %s", DEVICE_PATH); 1086 } 1087 if (isV4lScanningEnabled()) { 1088 result = scanVideoDirLocked(VIDEO_DEVICE_PATH); 1089 if (result != OK) { 1090 ALOGE("scan video dir failed for %s", VIDEO_DEVICE_PATH); 1091 } 1092 } 1093 if (mDevices.indexOfKey(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) < 0) { 1094 createVirtualKeyboardLocked(); 1095 } 1096 } 1097 1098 // ---------------------------------------------------------------------------- 1099 1100 static bool containsNonZeroByte(const uint8_t* array, uint32_t startIndex, uint32_t endIndex) { 1101 const uint8_t* end = array + endIndex; 1102 array += startIndex; 1103 while (array != end) { 1104 if (*(array++) != 0) { 1105 return true; 1106 } 1107 } 1108 return false; 1109 } 1110 1111 static const int32_t GAMEPAD_KEYCODES[] = { 1112 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C, 1113 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z, 1114 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1, 1115 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2, 1116 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR, 1117 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE, 1118 }; 1119 1120 status_t EventHub::registerFdForEpoll(int fd) { 1121 // TODO(b/121395353) - consider adding EPOLLRDHUP 1122 struct epoll_event eventItem = {}; 1123 eventItem.events = EPOLLIN | EPOLLWAKEUP; 1124 eventItem.data.fd = fd; 1125 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) { 1126 ALOGE("Could not add fd to epoll instance: %s", strerror(errno)); 1127 return -errno; 1128 } 1129 return OK; 1130 } 1131 1132 status_t EventHub::unregisterFdFromEpoll(int fd) { 1133 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) { 1134 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno)); 1135 return -errno; 1136 } 1137 return OK; 1138 } 1139 1140 status_t EventHub::registerDeviceForEpollLocked(Device* device) { 1141 if (device == nullptr) { 1142 if (DEBUG) { 1143 LOG_ALWAYS_FATAL("Cannot call registerDeviceForEpollLocked with null Device"); 1144 } 1145 return BAD_VALUE; 1146 } 1147 status_t result = registerFdForEpoll(device->fd); 1148 if (result != OK) { 1149 ALOGE("Could not add input device fd to epoll for device %" PRId32, device->id); 1150 return result; 1151 } 1152 if (device->videoDevice) { 1153 registerVideoDeviceForEpollLocked(*device->videoDevice); 1154 } 1155 return result; 1156 } 1157 1158 void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) { 1159 status_t result = registerFdForEpoll(videoDevice.getFd()); 1160 if (result != OK) { 1161 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str()); 1162 } 1163 } 1164 1165 status_t EventHub::unregisterDeviceFromEpollLocked(Device* device) { 1166 if (device->hasValidFd()) { 1167 status_t result = unregisterFdFromEpoll(device->fd); 1168 if (result != OK) { 1169 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device->id); 1170 return result; 1171 } 1172 } 1173 if (device->videoDevice) { 1174 unregisterVideoDeviceFromEpollLocked(*device->videoDevice); 1175 } 1176 return OK; 1177 } 1178 1179 void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) { 1180 if (videoDevice.hasValidFd()) { 1181 status_t result = unregisterFdFromEpoll(videoDevice.getFd()); 1182 if (result != OK) { 1183 ALOGW("Could not remove video device fd from epoll for device: %s", 1184 videoDevice.getName().c_str()); 1185 } 1186 } 1187 } 1188 1189 status_t EventHub::openDeviceLocked(const char* devicePath) { 1190 char buffer[80]; 1191 1192 ALOGV("Opening device: %s", devicePath); 1193 1194 int fd = open(devicePath, O_RDWR | O_CLOEXEC | O_NONBLOCK); 1195 if(fd < 0) { 1196 ALOGE("could not open %s, %s\n", devicePath, strerror(errno)); 1197 return -1; 1198 } 1199 1200 InputDeviceIdentifier identifier; 1201 1202 // Get device name. 1203 if(ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) { 1204 ALOGE("Could not get device name for %s: %s", devicePath, strerror(errno)); 1205 } else { 1206 buffer[sizeof(buffer) - 1] = '\0'; 1207 identifier.name = buffer; 1208 } 1209 1210 // Check to see if the device is on our excluded list 1211 for (size_t i = 0; i < mExcludedDevices.size(); i++) { 1212 const std::string& item = mExcludedDevices[i]; 1213 if (identifier.name == item) { 1214 ALOGI("ignoring event id %s driver %s\n", devicePath, item.c_str()); 1215 close(fd); 1216 return -1; 1217 } 1218 } 1219 1220 // Get device driver version. 1221 int driverVersion; 1222 if(ioctl(fd, EVIOCGVERSION, &driverVersion)) { 1223 ALOGE("could not get driver version for %s, %s\n", devicePath, strerror(errno)); 1224 close(fd); 1225 return -1; 1226 } 1227 1228 // Get device identifier. 1229 struct input_id inputId; 1230 if(ioctl(fd, EVIOCGID, &inputId)) { 1231 ALOGE("could not get device input id for %s, %s\n", devicePath, strerror(errno)); 1232 close(fd); 1233 return -1; 1234 } 1235 identifier.bus = inputId.bustype; 1236 identifier.product = inputId.product; 1237 identifier.vendor = inputId.vendor; 1238 identifier.version = inputId.version; 1239 1240 // Get device physical location. 1241 if(ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) { 1242 //fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno)); 1243 } else { 1244 buffer[sizeof(buffer) - 1] = '\0'; 1245 identifier.location = buffer; 1246 } 1247 1248 // Get device unique id. 1249 if(ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) { 1250 //fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno)); 1251 } else { 1252 buffer[sizeof(buffer) - 1] = '\0'; 1253 identifier.uniqueId = buffer; 1254 } 1255 1256 // Fill in the descriptor. 1257 assignDescriptorLocked(identifier); 1258 1259 // Allocate device. (The device object takes ownership of the fd at this point.) 1260 int32_t deviceId = mNextDeviceId++; 1261 Device* device = new Device(fd, deviceId, devicePath, identifier); 1262 1263 ALOGV("add device %d: %s\n", deviceId, devicePath); 1264 ALOGV(" bus: %04x\n" 1265 " vendor %04x\n" 1266 " product %04x\n" 1267 " version %04x\n", 1268 identifier.bus, identifier.vendor, identifier.product, identifier.version); 1269 ALOGV(" name: \"%s\"\n", identifier.name.c_str()); 1270 ALOGV(" location: \"%s\"\n", identifier.location.c_str()); 1271 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str()); 1272 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str()); 1273 ALOGV(" driver: v%d.%d.%d\n", 1274 driverVersion >> 16, (driverVersion >> 8) & 0xff, driverVersion & 0xff); 1275 1276 // Load the configuration file for the device. 1277 loadConfigurationLocked(device); 1278 1279 // Figure out the kinds of events the device reports. 1280 ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(device->keyBitmask)), device->keyBitmask); 1281 ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(device->absBitmask)), device->absBitmask); 1282 ioctl(fd, EVIOCGBIT(EV_REL, sizeof(device->relBitmask)), device->relBitmask); 1283 ioctl(fd, EVIOCGBIT(EV_SW, sizeof(device->swBitmask)), device->swBitmask); 1284 ioctl(fd, EVIOCGBIT(EV_LED, sizeof(device->ledBitmask)), device->ledBitmask); 1285 ioctl(fd, EVIOCGBIT(EV_FF, sizeof(device->ffBitmask)), device->ffBitmask); 1286 ioctl(fd, EVIOCGPROP(sizeof(device->propBitmask)), device->propBitmask); 1287 1288 // See if this is a keyboard. Ignore everything in the button range except for 1289 // joystick and gamepad buttons which are handled like keyboards for the most part. 1290 bool haveKeyboardKeys = containsNonZeroByte(device->keyBitmask, 0, sizeof_bit_array(BTN_MISC)) 1291 || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(KEY_OK), 1292 sizeof_bit_array(KEY_MAX + 1)); 1293 bool haveGamepadButtons = containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_MISC), 1294 sizeof_bit_array(BTN_MOUSE)) 1295 || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_JOYSTICK), 1296 sizeof_bit_array(BTN_DIGI)); 1297 if (haveKeyboardKeys || haveGamepadButtons) { 1298 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD; 1299 } 1300 1301 // See if this is a cursor device such as a trackball or mouse. 1302 if (test_bit(BTN_MOUSE, device->keyBitmask) 1303 && test_bit(REL_X, device->relBitmask) 1304 && test_bit(REL_Y, device->relBitmask)) { 1305 device->classes |= INPUT_DEVICE_CLASS_CURSOR; 1306 } 1307 1308 // See if this is a rotary encoder type device. 1309 String8 deviceType = String8(); 1310 if (device->configuration && 1311 device->configuration->tryGetProperty(String8("device.type"), deviceType)) { 1312 if (!deviceType.compare(String8("rotaryEncoder"))) { 1313 device->classes |= INPUT_DEVICE_CLASS_ROTARY_ENCODER; 1314 } 1315 } 1316 1317 // See if this is a touch pad. 1318 // Is this a new modern multi-touch driver? 1319 if (test_bit(ABS_MT_POSITION_X, device->absBitmask) 1320 && test_bit(ABS_MT_POSITION_Y, device->absBitmask)) { 1321 // Some joysticks such as the PS3 controller report axes that conflict 1322 // with the ABS_MT range. Try to confirm that the device really is 1323 // a touch screen. 1324 if (test_bit(BTN_TOUCH, device->keyBitmask) || !haveGamepadButtons) { 1325 device->classes |= INPUT_DEVICE_CLASS_TOUCH | INPUT_DEVICE_CLASS_TOUCH_MT; 1326 } 1327 // Is this an old style single-touch driver? 1328 } else if (test_bit(BTN_TOUCH, device->keyBitmask) 1329 && test_bit(ABS_X, device->absBitmask) 1330 && test_bit(ABS_Y, device->absBitmask)) { 1331 device->classes |= INPUT_DEVICE_CLASS_TOUCH; 1332 // Is this a BT stylus? 1333 } else if ((test_bit(ABS_PRESSURE, device->absBitmask) || 1334 test_bit(BTN_TOUCH, device->keyBitmask)) 1335 && !test_bit(ABS_X, device->absBitmask) 1336 && !test_bit(ABS_Y, device->absBitmask)) { 1337 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL_STYLUS; 1338 // Keyboard will try to claim some of the buttons but we really want to reserve those so we 1339 // can fuse it with the touch screen data, so just take them back. Note this means an 1340 // external stylus cannot also be a keyboard device. 1341 device->classes &= ~INPUT_DEVICE_CLASS_KEYBOARD; 1342 } 1343 1344 // See if this device is a joystick. 1345 // Assumes that joysticks always have gamepad buttons in order to distinguish them 1346 // from other devices such as accelerometers that also have absolute axes. 1347 if (haveGamepadButtons) { 1348 uint32_t assumedClasses = device->classes | INPUT_DEVICE_CLASS_JOYSTICK; 1349 for (int i = 0; i <= ABS_MAX; i++) { 1350 if (test_bit(i, device->absBitmask) 1351 && (getAbsAxisUsage(i, assumedClasses) & INPUT_DEVICE_CLASS_JOYSTICK)) { 1352 device->classes = assumedClasses; 1353 break; 1354 } 1355 } 1356 } 1357 1358 // Check whether this device has switches. 1359 for (int i = 0; i <= SW_MAX; i++) { 1360 if (test_bit(i, device->swBitmask)) { 1361 device->classes |= INPUT_DEVICE_CLASS_SWITCH; 1362 break; 1363 } 1364 } 1365 1366 // Check whether this device supports the vibrator. 1367 if (test_bit(FF_RUMBLE, device->ffBitmask)) { 1368 device->classes |= INPUT_DEVICE_CLASS_VIBRATOR; 1369 } 1370 1371 // Configure virtual keys. 1372 if ((device->classes & INPUT_DEVICE_CLASS_TOUCH)) { 1373 // Load the virtual keys for the touch screen, if any. 1374 // We do this now so that we can make sure to load the keymap if necessary. 1375 bool success = loadVirtualKeyMapLocked(device); 1376 if (success) { 1377 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD; 1378 } 1379 } 1380 1381 // Load the key map. 1382 // We need to do this for joysticks too because the key layout may specify axes. 1383 status_t keyMapStatus = NAME_NOT_FOUND; 1384 if (device->classes & (INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_JOYSTICK)) { 1385 // Load the keymap for the device. 1386 keyMapStatus = loadKeyMapLocked(device); 1387 } 1388 1389 // Configure the keyboard, gamepad or virtual keyboard. 1390 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) { 1391 // Register the keyboard as a built-in keyboard if it is eligible. 1392 if (!keyMapStatus 1393 && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD 1394 && isEligibleBuiltInKeyboard(device->identifier, 1395 device->configuration, &device->keyMap)) { 1396 mBuiltInKeyboardId = device->id; 1397 } 1398 1399 // 'Q' key support = cheap test of whether this is an alpha-capable kbd 1400 if (hasKeycodeLocked(device, AKEYCODE_Q)) { 1401 device->classes |= INPUT_DEVICE_CLASS_ALPHAKEY; 1402 } 1403 1404 // See if this device has a DPAD. 1405 if (hasKeycodeLocked(device, AKEYCODE_DPAD_UP) && 1406 hasKeycodeLocked(device, AKEYCODE_DPAD_DOWN) && 1407 hasKeycodeLocked(device, AKEYCODE_DPAD_LEFT) && 1408 hasKeycodeLocked(device, AKEYCODE_DPAD_RIGHT) && 1409 hasKeycodeLocked(device, AKEYCODE_DPAD_CENTER)) { 1410 device->classes |= INPUT_DEVICE_CLASS_DPAD; 1411 } 1412 1413 // See if this device has a gamepad. 1414 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES)/sizeof(GAMEPAD_KEYCODES[0]); i++) { 1415 if (hasKeycodeLocked(device, GAMEPAD_KEYCODES[i])) { 1416 device->classes |= INPUT_DEVICE_CLASS_GAMEPAD; 1417 break; 1418 } 1419 } 1420 } 1421 1422 // If the device isn't recognized as something we handle, don't monitor it. 1423 if (device->classes == 0) { 1424 ALOGV("Dropping device: id=%d, path='%s', name='%s'", 1425 deviceId, devicePath, device->identifier.name.c_str()); 1426 delete device; 1427 return -1; 1428 } 1429 1430 // Determine whether the device has a mic. 1431 if (deviceHasMicLocked(device)) { 1432 device->classes |= INPUT_DEVICE_CLASS_MIC; 1433 } 1434 1435 // Determine whether the device is external or internal. 1436 if (isExternalDeviceLocked(device)) { 1437 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL; 1438 } 1439 1440 if (device->classes & (INPUT_DEVICE_CLASS_JOYSTICK | INPUT_DEVICE_CLASS_DPAD) 1441 && device->classes & INPUT_DEVICE_CLASS_GAMEPAD) { 1442 device->controllerNumber = getNextControllerNumberLocked(device); 1443 setLedForControllerLocked(device); 1444 } 1445 1446 // Find a matching video device by comparing device names 1447 // This should be done before registerDeviceForEpollLocked, so that both fds are added to epoll 1448 for (std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) { 1449 if (device->identifier.name == videoDevice->getName()) { 1450 device->videoDevice = std::move(videoDevice); 1451 break; 1452 } 1453 } 1454 mUnattachedVideoDevices.erase(std::remove_if(mUnattachedVideoDevices.begin(), 1455 mUnattachedVideoDevices.end(), 1456 [](const std::unique_ptr<TouchVideoDevice>& videoDevice){ 1457 return videoDevice == nullptr; }), mUnattachedVideoDevices.end()); 1458 1459 if (registerDeviceForEpollLocked(device) != OK) { 1460 delete device; 1461 return -1; 1462 } 1463 1464 configureFd(device); 1465 1466 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=0x%x, " 1467 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ", 1468 deviceId, fd, devicePath, device->identifier.name.c_str(), 1469 device->classes, 1470 device->configurationFile.c_str(), 1471 device->keyMap.keyLayoutFile.c_str(), 1472 device->keyMap.keyCharacterMapFile.c_str(), 1473 toString(mBuiltInKeyboardId == deviceId)); 1474 1475 addDeviceLocked(device); 1476 return OK; 1477 } 1478 1479 void EventHub::configureFd(Device* device) { 1480 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type 1481 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) { 1482 // Disable kernel key repeat since we handle it ourselves 1483 unsigned int repeatRate[] = {0, 0}; 1484 if (ioctl(device->fd, EVIOCSREP, repeatRate)) { 1485 ALOGW("Unable to disable kernel key repeat for %s: %s", 1486 device->path.c_str(), strerror(errno)); 1487 } 1488 } 1489 1490 std::string wakeMechanism = "EPOLLWAKEUP"; 1491 if (!mUsingEpollWakeup) { 1492 #ifndef EVIOCSSUSPENDBLOCK 1493 // uapi headers don't include EVIOCSSUSPENDBLOCK, and future kernels 1494 // will use an epoll flag instead, so as long as we want to support 1495 // this feature, we need to be prepared to define the ioctl ourselves. 1496 #define EVIOCSSUSPENDBLOCK _IOW('E', 0x91, int) 1497 #endif 1498 if (ioctl(device->fd, EVIOCSSUSPENDBLOCK, 1)) { 1499 wakeMechanism = "<none>"; 1500 } else { 1501 wakeMechanism = "EVIOCSSUSPENDBLOCK"; 1502 } 1503 } 1504 // Tell the kernel that we want to use the monotonic clock for reporting timestamps 1505 // associated with input events. This is important because the input system 1506 // uses the timestamps extensively and assumes they were recorded using the monotonic 1507 // clock. 1508 int clockId = CLOCK_MONOTONIC; 1509 bool usingClockIoctl = !ioctl(device->fd, EVIOCSCLOCKID, &clockId); 1510 ALOGI("wakeMechanism=%s, usingClockIoctl=%s", wakeMechanism.c_str(), 1511 toString(usingClockIoctl)); 1512 } 1513 1514 void EventHub::openVideoDeviceLocked(const std::string& devicePath) { 1515 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath); 1516 if (!videoDevice) { 1517 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str()); 1518 return; 1519 } 1520 // Transfer ownership of this video device to a matching input device 1521 for (size_t i = 0; i < mDevices.size(); i++) { 1522 Device* device = mDevices.valueAt(i); 1523 if (videoDevice->getName() == device->identifier.name) { 1524 device->videoDevice = std::move(videoDevice); 1525 if (device->enabled) { 1526 registerVideoDeviceForEpollLocked(*device->videoDevice); 1527 } 1528 return; 1529 } 1530 } 1531 1532 // Couldn't find a matching input device, so just add it to a temporary holding queue. 1533 // A matching input device may appear later. 1534 ALOGI("Adding video device %s to list of unattached video devices", 1535 videoDevice->getName().c_str()); 1536 mUnattachedVideoDevices.push_back(std::move(videoDevice)); 1537 } 1538 1539 bool EventHub::isDeviceEnabled(int32_t deviceId) { 1540 AutoMutex _l(mLock); 1541 Device* device = getDeviceLocked(deviceId); 1542 if (device == nullptr) { 1543 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__); 1544 return false; 1545 } 1546 return device->enabled; 1547 } 1548 1549 status_t EventHub::enableDevice(int32_t deviceId) { 1550 AutoMutex _l(mLock); 1551 Device* device = getDeviceLocked(deviceId); 1552 if (device == nullptr) { 1553 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__); 1554 return BAD_VALUE; 1555 } 1556 if (device->enabled) { 1557 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId); 1558 return OK; 1559 } 1560 status_t result = device->enable(); 1561 if (result != OK) { 1562 ALOGE("Failed to enable device %" PRId32, deviceId); 1563 return result; 1564 } 1565 1566 configureFd(device); 1567 1568 return registerDeviceForEpollLocked(device); 1569 } 1570 1571 status_t EventHub::disableDevice(int32_t deviceId) { 1572 AutoMutex _l(mLock); 1573 Device* device = getDeviceLocked(deviceId); 1574 if (device == nullptr) { 1575 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__); 1576 return BAD_VALUE; 1577 } 1578 if (!device->enabled) { 1579 ALOGW("Duplicate call to %s, input device already disabled", __func__); 1580 return OK; 1581 } 1582 unregisterDeviceFromEpollLocked(device); 1583 return device->disable(); 1584 } 1585 1586 void EventHub::createVirtualKeyboardLocked() { 1587 InputDeviceIdentifier identifier; 1588 identifier.name = "Virtual"; 1589 identifier.uniqueId = "<virtual>"; 1590 assignDescriptorLocked(identifier); 1591 1592 Device* device = new Device(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>", 1593 identifier); 1594 device->classes = INPUT_DEVICE_CLASS_KEYBOARD 1595 | INPUT_DEVICE_CLASS_ALPHAKEY 1596 | INPUT_DEVICE_CLASS_DPAD 1597 | INPUT_DEVICE_CLASS_VIRTUAL; 1598 loadKeyMapLocked(device); 1599 addDeviceLocked(device); 1600 } 1601 1602 void EventHub::addDeviceLocked(Device* device) { 1603 mDevices.add(device->id, device); 1604 device->next = mOpeningDevices; 1605 mOpeningDevices = device; 1606 } 1607 1608 void EventHub::loadConfigurationLocked(Device* device) { 1609 device->configurationFile = getInputDeviceConfigurationFilePathByDeviceIdentifier( 1610 device->identifier, INPUT_DEVICE_CONFIGURATION_FILE_TYPE_CONFIGURATION); 1611 if (device->configurationFile.empty()) { 1612 ALOGD("No input device configuration file found for device '%s'.", 1613 device->identifier.name.c_str()); 1614 } else { 1615 status_t status = PropertyMap::load(String8(device->configurationFile.c_str()), 1616 &device->configuration); 1617 if (status) { 1618 ALOGE("Error loading input device configuration file for device '%s'. " 1619 "Using default configuration.", 1620 device->identifier.name.c_str()); 1621 } 1622 } 1623 } 1624 1625 bool EventHub::loadVirtualKeyMapLocked(Device* device) { 1626 // The virtual key map is supplied by the kernel as a system board property file. 1627 std::string path; 1628 path += "/sys/board_properties/virtualkeys."; 1629 path += device->identifier.getCanonicalName(); 1630 if (access(path.c_str(), R_OK)) { 1631 return false; 1632 } 1633 device->virtualKeyMap = VirtualKeyMap::load(path); 1634 return device->virtualKeyMap != nullptr; 1635 } 1636 1637 status_t EventHub::loadKeyMapLocked(Device* device) { 1638 return device->keyMap.load(device->identifier, device->configuration); 1639 } 1640 1641 bool EventHub::isExternalDeviceLocked(Device* device) { 1642 if (device->configuration) { 1643 bool value; 1644 if (device->configuration->tryGetProperty(String8("device.internal"), value)) { 1645 return !value; 1646 } 1647 } 1648 return device->identifier.bus == BUS_USB || device->identifier.bus == BUS_BLUETOOTH; 1649 } 1650 1651 bool EventHub::deviceHasMicLocked(Device* device) { 1652 if (device->configuration) { 1653 bool value; 1654 if (device->configuration->tryGetProperty(String8("audio.mic"), value)) { 1655 return value; 1656 } 1657 } 1658 return false; 1659 } 1660 1661 int32_t EventHub::getNextControllerNumberLocked(Device* device) { 1662 if (mControllerNumbers.isFull()) { 1663 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s", 1664 device->identifier.name.c_str()); 1665 return 0; 1666 } 1667 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by 1668 // one 1669 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1); 1670 } 1671 1672 void EventHub::releaseControllerNumberLocked(Device* device) { 1673 int32_t num = device->controllerNumber; 1674 device->controllerNumber= 0; 1675 if (num == 0) { 1676 return; 1677 } 1678 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1)); 1679 } 1680 1681 void EventHub::setLedForControllerLocked(Device* device) { 1682 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) { 1683 setLedStateLocked(device, ALED_CONTROLLER_1 + i, device->controllerNumber == i + 1); 1684 } 1685 } 1686 1687 bool EventHub::hasKeycodeLocked(Device* device, int keycode) const { 1688 if (!device->keyMap.haveKeyLayout()) { 1689 return false; 1690 } 1691 1692 std::vector<int32_t> scanCodes; 1693 device->keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes); 1694 const size_t N = scanCodes.size(); 1695 for (size_t i=0; i<N && i<=KEY_MAX; i++) { 1696 int32_t sc = scanCodes[i]; 1697 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, device->keyBitmask)) { 1698 return true; 1699 } 1700 } 1701 1702 return false; 1703 } 1704 1705 status_t EventHub::mapLed(Device* device, int32_t led, int32_t* outScanCode) const { 1706 if (!device->keyMap.haveKeyLayout()) { 1707 return NAME_NOT_FOUND; 1708 } 1709 1710 int32_t scanCode; 1711 if(device->keyMap.keyLayoutMap->findScanCodeForLed(led, &scanCode) != NAME_NOT_FOUND) { 1712 if(scanCode >= 0 && scanCode <= LED_MAX && test_bit(scanCode, device->ledBitmask)) { 1713 *outScanCode = scanCode; 1714 return NO_ERROR; 1715 } 1716 } 1717 return NAME_NOT_FOUND; 1718 } 1719 1720 void EventHub::closeDeviceByPathLocked(const char *devicePath) { 1721 Device* device = getDeviceByPathLocked(devicePath); 1722 if (device) { 1723 closeDeviceLocked(device); 1724 return; 1725 } 1726 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath); 1727 } 1728 1729 /** 1730 * Find the video device by filename, and close it. 1731 * The video device is closed by path during an inotify event, where we don't have the 1732 * additional context about the video device fd, or the associated input device. 1733 */ 1734 void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) { 1735 // A video device may be owned by an existing input device, or it may be stored in 1736 // the mUnattachedVideoDevices queue. Check both locations. 1737 for (size_t i = 0; i < mDevices.size(); i++) { 1738 Device* device = mDevices.valueAt(i); 1739 if (device->videoDevice && device->videoDevice->getPath() == devicePath) { 1740 unregisterVideoDeviceFromEpollLocked(*device->videoDevice); 1741 device->videoDevice = nullptr; 1742 return; 1743 } 1744 } 1745 mUnattachedVideoDevices.erase(std::remove_if(mUnattachedVideoDevices.begin(), 1746 mUnattachedVideoDevices.end(), [&devicePath]( 1747 const std::unique_ptr<TouchVideoDevice>& videoDevice) { 1748 return videoDevice->getPath() == devicePath; }), mUnattachedVideoDevices.end()); 1749 } 1750 1751 void EventHub::closeAllDevicesLocked() { 1752 mUnattachedVideoDevices.clear(); 1753 while (mDevices.size() > 0) { 1754 closeDeviceLocked(mDevices.valueAt(mDevices.size() - 1)); 1755 } 1756 } 1757 1758 void EventHub::closeDeviceLocked(Device* device) { 1759 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=0x%x", 1760 device->path.c_str(), device->identifier.name.c_str(), device->id, 1761 device->fd, device->classes); 1762 1763 if (device->id == mBuiltInKeyboardId) { 1764 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this", 1765 device->path.c_str(), mBuiltInKeyboardId); 1766 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD; 1767 } 1768 1769 unregisterDeviceFromEpollLocked(device); 1770 if (device->videoDevice) { 1771 // This must be done after the video device is removed from epoll 1772 mUnattachedVideoDevices.push_back(std::move(device->videoDevice)); 1773 } 1774 1775 releaseControllerNumberLocked(device); 1776 1777 mDevices.removeItem(device->id); 1778 device->close(); 1779 1780 // Unlink for opening devices list if it is present. 1781 Device* pred = nullptr; 1782 bool found = false; 1783 for (Device* entry = mOpeningDevices; entry != nullptr; ) { 1784 if (entry == device) { 1785 found = true; 1786 break; 1787 } 1788 pred = entry; 1789 entry = entry->next; 1790 } 1791 if (found) { 1792 // Unlink the device from the opening devices list then delete it. 1793 // We don't need to tell the client that the device was closed because 1794 // it does not even know it was opened in the first place. 1795 ALOGI("Device %s was immediately closed after opening.", device->path.c_str()); 1796 if (pred) { 1797 pred->next = device->next; 1798 } else { 1799 mOpeningDevices = device->next; 1800 } 1801 delete device; 1802 } else { 1803 // Link into closing devices list. 1804 // The device will be deleted later after we have informed the client. 1805 device->next = mClosingDevices; 1806 mClosingDevices = device; 1807 } 1808 } 1809 1810 status_t EventHub::readNotifyLocked() { 1811 int res; 1812 char event_buf[512]; 1813 int event_size; 1814 int event_pos = 0; 1815 struct inotify_event *event; 1816 1817 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd); 1818 res = read(mINotifyFd, event_buf, sizeof(event_buf)); 1819 if(res < (int)sizeof(*event)) { 1820 if(errno == EINTR) 1821 return 0; 1822 ALOGW("could not get event, %s\n", strerror(errno)); 1823 return -1; 1824 } 1825 1826 while(res >= (int)sizeof(*event)) { 1827 event = (struct inotify_event *)(event_buf + event_pos); 1828 if(event->len) { 1829 if (event->wd == mInputWd) { 1830 std::string filename = StringPrintf("%s/%s", DEVICE_PATH, event->name); 1831 if(event->mask & IN_CREATE) { 1832 openDeviceLocked(filename.c_str()); 1833 } else { 1834 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str()); 1835 closeDeviceByPathLocked(filename.c_str()); 1836 } 1837 } 1838 else if (event->wd == mVideoWd) { 1839 if (isV4lTouchNode(event->name)) { 1840 std::string filename = StringPrintf("%s/%s", VIDEO_DEVICE_PATH, event->name); 1841 if (event->mask & IN_CREATE) { 1842 openVideoDeviceLocked(filename); 1843 } else { 1844 ALOGI("Removing video device '%s' due to inotify event", filename.c_str()); 1845 closeVideoDeviceByPathLocked(filename); 1846 } 1847 } 1848 } 1849 else { 1850 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event->wd); 1851 } 1852 } 1853 event_size = sizeof(*event) + event->len; 1854 res -= event_size; 1855 event_pos += event_size; 1856 } 1857 return 0; 1858 } 1859 1860 status_t EventHub::scanDirLocked(const char *dirname) 1861 { 1862 char devname[PATH_MAX]; 1863 char *filename; 1864 DIR *dir; 1865 struct dirent *de; 1866 dir = opendir(dirname); 1867 if(dir == nullptr) 1868 return -1; 1869 strcpy(devname, dirname); 1870 filename = devname + strlen(devname); 1871 *filename++ = '/'; 1872 while((de = readdir(dir))) { 1873 if(de->d_name[0] == '.' && 1874 (de->d_name[1] == '\0' || 1875 (de->d_name[1] == '.' && de->d_name[2] == '\0'))) 1876 continue; 1877 strcpy(filename, de->d_name); 1878 openDeviceLocked(devname); 1879 } 1880 closedir(dir); 1881 return 0; 1882 } 1883 1884 /** 1885 * Look for all dirname/v4l-touch* devices, and open them. 1886 */ 1887 status_t EventHub::scanVideoDirLocked(const std::string& dirname) 1888 { 1889 DIR* dir; 1890 struct dirent* de; 1891 dir = opendir(dirname.c_str()); 1892 if(!dir) { 1893 ALOGE("Could not open video directory %s", dirname.c_str()); 1894 return BAD_VALUE; 1895 } 1896 1897 while((de = readdir(dir))) { 1898 const char* name = de->d_name; 1899 if (isV4lTouchNode(name)) { 1900 ALOGI("Found touch video device %s", name); 1901 openVideoDeviceLocked(dirname + "/" + name); 1902 } 1903 } 1904 closedir(dir); 1905 return OK; 1906 } 1907 1908 void EventHub::requestReopenDevices() { 1909 ALOGV("requestReopenDevices() called"); 1910 1911 AutoMutex _l(mLock); 1912 mNeedToReopenDevices = true; 1913 } 1914 1915 void EventHub::dump(std::string& dump) { 1916 dump += "Event Hub State:\n"; 1917 1918 { // acquire lock 1919 AutoMutex _l(mLock); 1920 1921 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId); 1922 1923 dump += INDENT "Devices:\n"; 1924 1925 for (size_t i = 0; i < mDevices.size(); i++) { 1926 const Device* device = mDevices.valueAt(i); 1927 if (mBuiltInKeyboardId == device->id) { 1928 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n", 1929 device->id, device->identifier.name.c_str()); 1930 } else { 1931 dump += StringPrintf(INDENT2 "%d: %s\n", device->id, 1932 device->identifier.name.c_str()); 1933 } 1934 dump += StringPrintf(INDENT3 "Classes: 0x%08x\n", device->classes); 1935 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str()); 1936 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled)); 1937 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str()); 1938 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str()); 1939 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber); 1940 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str()); 1941 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, " 1942 "product=0x%04x, version=0x%04x\n", 1943 device->identifier.bus, device->identifier.vendor, 1944 device->identifier.product, device->identifier.version); 1945 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n", 1946 device->keyMap.keyLayoutFile.c_str()); 1947 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n", 1948 device->keyMap.keyCharacterMapFile.c_str()); 1949 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n", 1950 device->configurationFile.c_str()); 1951 dump += StringPrintf(INDENT3 "HaveKeyboardLayoutOverlay: %s\n", 1952 toString(device->overlayKeyMap != nullptr)); 1953 dump += INDENT3 "VideoDevice: "; 1954 if (device->videoDevice) { 1955 dump += device->videoDevice->dump() + "\n"; 1956 } else { 1957 dump += "<none>\n"; 1958 } 1959 } 1960 1961 dump += INDENT "Unattached video devices:\n"; 1962 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) { 1963 dump += INDENT2 + videoDevice->dump() + "\n"; 1964 } 1965 if (mUnattachedVideoDevices.empty()) { 1966 dump += INDENT2 "<none>\n"; 1967 } 1968 } // release lock 1969 } 1970 1971 void EventHub::monitor() { 1972 // Acquire and release the lock to ensure that the event hub has not deadlocked. 1973 mLock.lock(); 1974 mLock.unlock(); 1975 } 1976 1977 1978 }; // namespace android 1979