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