blob: f7802b99536c608a85ef2c494002dc97275ab9eb [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
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
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070017#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>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070031#include <sys/utsname.h>
32#include <unistd.h>
33
Michael Wrightd02c5b62014-02-10 15:10:22 -080034#define LOG_TAG "EventHub"
35
36// #define LOG_NDEBUG 0
37
38#include "EventHub.h"
39
40#include <hardware_legacy/power.h>
41
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080042#include <android-base/stringprintf.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080043#include <cutils/properties.h>
Dan Albert677d87e2014-06-16 17:31:28 -070044#include <openssl/sha.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080045#include <utils/Log.h>
46#include <utils/Timers.h>
47#include <utils/threads.h>
48#include <utils/Errors.h>
49
Michael Wrightd02c5b62014-02-10 15:10:22 -080050#include <input/KeyLayoutMap.h>
51#include <input/KeyCharacterMap.h>
52#include <input/VirtualKeyMap.h>
53
Michael Wrightd02c5b62014-02-10 15:10:22 -080054/* 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 */
Chih-Hung Hsieh4a186d42016-05-20 11:33:26 -070059#define test_bit(bit, array) ((array)[(bit)/8] & (1<<((bit)%8)))
Michael Wrightd02c5b62014-02-10 15:10:22 -080060
61/* this macro computes the number of bytes needed to represent a bit array of the specified size */
Chih-Hung Hsieh4a186d42016-05-20 11:33:26 -070062#define sizeof_bit_array(bits) (((bits) + 7) / 8)
Michael Wrightd02c5b62014-02-10 15:10:22 -080063
64#define INDENT " "
65#define INDENT2 " "
66#define INDENT3 " "
67
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080068using android::base::StringPrintf;
69
Michael Wrightd02c5b62014-02-10 15:10:22 -080070namespace android {
71
Siarhei Vishniakou25920312018-12-12 15:24:44 -080072static constexpr bool DEBUG = false;
73
Michael Wrightd02c5b62014-02-10 15:10:22 -080074static const char *WAKE_LOCK_ID = "KeyEvents";
75static const char *DEVICE_PATH = "/dev/input";
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080076// v4l2 devices go directly into /dev
77static const char *VIDEO_DEVICE_PATH = "/dev";
Michael Wrightd02c5b62014-02-10 15:10:22 -080078
Michael Wrightd02c5b62014-02-10 15:10:22 -080079static inline const char* toString(bool value) {
80 return value ? "true" : "false";
81}
82
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010083static std::string sha1(const std::string& in) {
Dan Albert677d87e2014-06-16 17:31:28 -070084 SHA_CTX ctx;
85 SHA1_Init(&ctx);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010086 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
Dan Albert677d87e2014-06-16 17:31:28 -070087 u_char digest[SHA_DIGEST_LENGTH];
88 SHA1_Final(digest, &ctx);
Michael Wrightd02c5b62014-02-10 15:10:22 -080089
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010090 std::string out;
Dan Albert677d87e2014-06-16 17:31:28 -070091 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010092 out += StringPrintf("%02x", digest[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -080093 }
94 return out;
95}
96
97static void getLinuxRelease(int* major, int* minor) {
98 struct utsname info;
99 if (uname(&info) || sscanf(info.release, "%d.%d", major, minor) <= 0) {
100 *major = 0, *minor = 0;
101 ALOGE("Could not get linux version: %s", strerror(errno));
102 }
103}
104
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800105/**
106 * Return true if name matches "v4l-touch*"
107 */
108static bool isV4lTouchNode(const char* name) {
109 return strstr(name, "v4l-touch") == name;
110}
111
Michael Wrightd02c5b62014-02-10 15:10:22 -0800112// --- Global Functions ---
113
114uint32_t getAbsAxisUsage(int32_t axis, uint32_t deviceClasses) {
115 // Touch devices get dibs on touch-related axes.
116 if (deviceClasses & INPUT_DEVICE_CLASS_TOUCH) {
117 switch (axis) {
118 case ABS_X:
119 case ABS_Y:
120 case ABS_PRESSURE:
121 case ABS_TOOL_WIDTH:
122 case ABS_DISTANCE:
123 case ABS_TILT_X:
124 case ABS_TILT_Y:
125 case ABS_MT_SLOT:
126 case ABS_MT_TOUCH_MAJOR:
127 case ABS_MT_TOUCH_MINOR:
128 case ABS_MT_WIDTH_MAJOR:
129 case ABS_MT_WIDTH_MINOR:
130 case ABS_MT_ORIENTATION:
131 case ABS_MT_POSITION_X:
132 case ABS_MT_POSITION_Y:
133 case ABS_MT_TOOL_TYPE:
134 case ABS_MT_BLOB_ID:
135 case ABS_MT_TRACKING_ID:
136 case ABS_MT_PRESSURE:
137 case ABS_MT_DISTANCE:
138 return INPUT_DEVICE_CLASS_TOUCH;
139 }
140 }
141
Michael Wright842500e2015-03-13 17:32:02 -0700142 // External stylus gets the pressure axis
143 if (deviceClasses & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
144 if (axis == ABS_PRESSURE) {
145 return INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
146 }
147 }
148
Michael Wrightd02c5b62014-02-10 15:10:22 -0800149 // Joystick devices get the rest.
150 return deviceClasses & INPUT_DEVICE_CLASS_JOYSTICK;
151}
152
153// --- EventHub::Device ---
154
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100155EventHub::Device::Device(int fd, int32_t id, const std::string& path,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800156 const InputDeviceIdentifier& identifier) :
Yi Kong9b14ac62018-07-17 13:48:38 -0700157 next(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800158 fd(fd), id(id), path(path), identifier(identifier),
Yi Kong9b14ac62018-07-17 13:48:38 -0700159 classes(0), configuration(nullptr), virtualKeyMap(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800160 ffEffectPlaying(false), ffEffectId(-1), controllerNumber(0),
Siarhei Vishniakou88786812018-11-09 15:36:21 -0800161 enabled(true), isVirtual(fd < 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800162 memset(keyBitmask, 0, sizeof(keyBitmask));
163 memset(absBitmask, 0, sizeof(absBitmask));
164 memset(relBitmask, 0, sizeof(relBitmask));
165 memset(swBitmask, 0, sizeof(swBitmask));
166 memset(ledBitmask, 0, sizeof(ledBitmask));
167 memset(ffBitmask, 0, sizeof(ffBitmask));
168 memset(propBitmask, 0, sizeof(propBitmask));
169}
170
171EventHub::Device::~Device() {
172 close();
173 delete configuration;
174 delete virtualKeyMap;
175}
176
177void EventHub::Device::close() {
178 if (fd >= 0) {
179 ::close(fd);
180 fd = -1;
181 }
182}
183
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700184status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100185 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700186 if(fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100187 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700188 return -errno;
189 }
190 enabled = true;
191 return OK;
192}
193
194status_t EventHub::Device::disable() {
195 close();
196 enabled = false;
197 return OK;
198}
199
200bool EventHub::Device::hasValidFd() {
201 return !isVirtual && enabled;
202}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800203
204// --- EventHub ---
205
Michael Wrightd02c5b62014-02-10 15:10:22 -0800206const int EventHub::EPOLL_SIZE_HINT;
207const int EventHub::EPOLL_MAX_EVENTS;
208
209EventHub::EventHub(void) :
210 mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD), mNextDeviceId(1), mControllerNumbers(),
Yi Kong9b14ac62018-07-17 13:48:38 -0700211 mOpeningDevices(nullptr), mClosingDevices(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800212 mNeedToSendFinishedDeviceScan(false),
213 mNeedToReopenDevices(false), mNeedToScanDevices(true),
214 mPendingEventCount(0), mPendingEventIndex(0), mPendingINotify(false) {
215 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
216
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800217 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800218 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800219
220 mINotifyFd = inotify_init();
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800221 mInputWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
222 LOG_ALWAYS_FATAL_IF(mInputWd < 0, "Could not register INotify for %s: %s",
223 DEVICE_PATH, strerror(errno));
224 mVideoWd = inotify_add_watch(mINotifyFd, VIDEO_DEVICE_PATH, IN_DELETE | IN_CREATE);
225 LOG_ALWAYS_FATAL_IF(mVideoWd < 0, "Could not register INotify for %s: %s",
226 VIDEO_DEVICE_PATH, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800227
228 struct epoll_event eventItem;
229 memset(&eventItem, 0, sizeof(eventItem));
230 eventItem.events = EPOLLIN;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700231 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800232 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800233 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
234
235 int wakeFds[2];
236 result = pipe(wakeFds);
237 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
238
239 mWakeReadPipeFd = wakeFds[0];
240 mWakeWritePipeFd = wakeFds[1];
241
242 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
243 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
244 errno);
245
246 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
247 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
248 errno);
249
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700250 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800251 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
252 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
253 errno);
254
255 int major, minor;
256 getLinuxRelease(&major, &minor);
257 // EPOLLWAKEUP was introduced in kernel 3.5
258 mUsingEpollWakeup = major > 3 || (major == 3 && minor >= 5);
259}
260
261EventHub::~EventHub(void) {
262 closeAllDevicesLocked();
263
264 while (mClosingDevices) {
265 Device* device = mClosingDevices;
266 mClosingDevices = device->next;
267 delete device;
268 }
269
270 ::close(mEpollFd);
271 ::close(mINotifyFd);
272 ::close(mWakeReadPipeFd);
273 ::close(mWakeWritePipeFd);
274
275 release_wake_lock(WAKE_LOCK_ID);
276}
277
278InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
279 AutoMutex _l(mLock);
280 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700281 if (device == nullptr) return InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800282 return device->identifier;
283}
284
285uint32_t EventHub::getDeviceClasses(int32_t deviceId) const {
286 AutoMutex _l(mLock);
287 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700288 if (device == nullptr) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800289 return device->classes;
290}
291
292int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
293 AutoMutex _l(mLock);
294 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700295 if (device == nullptr) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800296 return device->controllerNumber;
297}
298
299void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
300 AutoMutex _l(mLock);
301 Device* device = getDeviceLocked(deviceId);
302 if (device && device->configuration) {
303 *outConfiguration = *device->configuration;
304 } else {
305 outConfiguration->clear();
306 }
307}
308
309status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
310 RawAbsoluteAxisInfo* outAxisInfo) const {
311 outAxisInfo->clear();
312
313 if (axis >= 0 && axis <= ABS_MAX) {
314 AutoMutex _l(mLock);
315
316 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700317 if (device && device->hasValidFd() && test_bit(axis, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800318 struct input_absinfo info;
319 if(ioctl(device->fd, EVIOCGABS(axis), &info)) {
320 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100321 axis, device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800322 return -errno;
323 }
324
325 if (info.minimum != info.maximum) {
326 outAxisInfo->valid = true;
327 outAxisInfo->minValue = info.minimum;
328 outAxisInfo->maxValue = info.maximum;
329 outAxisInfo->flat = info.flat;
330 outAxisInfo->fuzz = info.fuzz;
331 outAxisInfo->resolution = info.resolution;
332 }
333 return OK;
334 }
335 }
336 return -1;
337}
338
339bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
340 if (axis >= 0 && axis <= REL_MAX) {
341 AutoMutex _l(mLock);
342
343 Device* device = getDeviceLocked(deviceId);
344 if (device) {
345 return test_bit(axis, device->relBitmask);
346 }
347 }
348 return false;
349}
350
351bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
352 if (property >= 0 && property <= INPUT_PROP_MAX) {
353 AutoMutex _l(mLock);
354
355 Device* device = getDeviceLocked(deviceId);
356 if (device) {
357 return test_bit(property, device->propBitmask);
358 }
359 }
360 return false;
361}
362
363int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
364 if (scanCode >= 0 && scanCode <= KEY_MAX) {
365 AutoMutex _l(mLock);
366
367 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700368 if (device && device->hasValidFd() && test_bit(scanCode, device->keyBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800369 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
370 memset(keyState, 0, sizeof(keyState));
371 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
372 return test_bit(scanCode, keyState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
373 }
374 }
375 }
376 return AKEY_STATE_UNKNOWN;
377}
378
379int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
380 AutoMutex _l(mLock);
381
382 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700383 if (device && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800384 Vector<int32_t> scanCodes;
385 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode, &scanCodes);
386 if (scanCodes.size() != 0) {
387 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
388 memset(keyState, 0, sizeof(keyState));
389 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
390 for (size_t i = 0; i < scanCodes.size(); i++) {
391 int32_t sc = scanCodes.itemAt(i);
392 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, keyState)) {
393 return AKEY_STATE_DOWN;
394 }
395 }
396 return AKEY_STATE_UP;
397 }
398 }
399 }
400 return AKEY_STATE_UNKNOWN;
401}
402
403int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
404 if (sw >= 0 && sw <= SW_MAX) {
405 AutoMutex _l(mLock);
406
407 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700408 if (device && device->hasValidFd() && test_bit(sw, device->swBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800409 uint8_t swState[sizeof_bit_array(SW_MAX + 1)];
410 memset(swState, 0, sizeof(swState));
411 if (ioctl(device->fd, EVIOCGSW(sizeof(swState)), swState) >= 0) {
412 return test_bit(sw, swState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
413 }
414 }
415 }
416 return AKEY_STATE_UNKNOWN;
417}
418
419status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
420 *outValue = 0;
421
422 if (axis >= 0 && axis <= ABS_MAX) {
423 AutoMutex _l(mLock);
424
425 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700426 if (device && device->hasValidFd() && test_bit(axis, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800427 struct input_absinfo info;
428 if(ioctl(device->fd, EVIOCGABS(axis), &info)) {
429 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100430 axis, device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800431 return -errno;
432 }
433
434 *outValue = info.value;
435 return OK;
436 }
437 }
438 return -1;
439}
440
441bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes,
442 const int32_t* keyCodes, uint8_t* outFlags) const {
443 AutoMutex _l(mLock);
444
445 Device* device = getDeviceLocked(deviceId);
446 if (device && device->keyMap.haveKeyLayout()) {
447 Vector<int32_t> scanCodes;
448 for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) {
449 scanCodes.clear();
450
451 status_t err = device->keyMap.keyLayoutMap->findScanCodesForKey(
452 keyCodes[codeIndex], &scanCodes);
453 if (! err) {
454 // check the possible scan codes identified by the layout map against the
455 // map of codes actually emitted by the driver
456 for (size_t sc = 0; sc < scanCodes.size(); sc++) {
457 if (test_bit(scanCodes[sc], device->keyBitmask)) {
458 outFlags[codeIndex] = 1;
459 break;
460 }
461 }
462 }
463 }
464 return true;
465 }
466 return false;
467}
468
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700469status_t EventHub::mapKey(int32_t deviceId,
470 int32_t scanCode, int32_t usageCode, int32_t metaState,
471 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800472 AutoMutex _l(mLock);
473 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700474 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800475
476 if (device) {
477 // Check the key character map first.
478 sp<KeyCharacterMap> kcm = device->getKeyCharacterMap();
Yi Kong9b14ac62018-07-17 13:48:38 -0700479 if (kcm != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800480 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
481 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700482 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800483 }
484 }
485
486 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700487 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800488 if (!device->keyMap.keyLayoutMap->mapKey(
489 scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700490 status = NO_ERROR;
491 }
492 }
493
494 if (status == NO_ERROR) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700495 if (kcm != nullptr) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700496 kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState);
497 } else {
498 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800499 }
500 }
501 }
502
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700503 if (status != NO_ERROR) {
504 *outKeycode = 0;
505 *outFlags = 0;
506 *outMetaState = metaState;
507 }
508
509 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800510}
511
512status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
513 AutoMutex _l(mLock);
514 Device* device = getDeviceLocked(deviceId);
515
516 if (device && device->keyMap.haveKeyLayout()) {
517 status_t err = device->keyMap.keyLayoutMap->mapAxis(scanCode, outAxisInfo);
518 if (err == NO_ERROR) {
519 return NO_ERROR;
520 }
521 }
522
523 return NAME_NOT_FOUND;
524}
525
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100526void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800527 AutoMutex _l(mLock);
528
529 mExcludedDevices = devices;
530}
531
532bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
533 AutoMutex _l(mLock);
534 Device* device = getDeviceLocked(deviceId);
535 if (device && scanCode >= 0 && scanCode <= KEY_MAX) {
536 if (test_bit(scanCode, device->keyBitmask)) {
537 return true;
538 }
539 }
540 return false;
541}
542
543bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
544 AutoMutex _l(mLock);
545 Device* device = getDeviceLocked(deviceId);
546 int32_t sc;
547 if (device && mapLed(device, led, &sc) == NO_ERROR) {
548 if (test_bit(sc, device->ledBitmask)) {
549 return true;
550 }
551 }
552 return false;
553}
554
555void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
556 AutoMutex _l(mLock);
557 Device* device = getDeviceLocked(deviceId);
558 setLedStateLocked(device, led, on);
559}
560
561void EventHub::setLedStateLocked(Device* device, int32_t led, bool on) {
562 int32_t sc;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700563 if (device && device->hasValidFd() && mapLed(device, led, &sc) != NAME_NOT_FOUND) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800564 struct input_event ev;
565 ev.time.tv_sec = 0;
566 ev.time.tv_usec = 0;
567 ev.type = EV_LED;
568 ev.code = sc;
569 ev.value = on ? 1 : 0;
570
571 ssize_t nWrite;
572 do {
573 nWrite = write(device->fd, &ev, sizeof(struct input_event));
574 } while (nWrite == -1 && errno == EINTR);
575 }
576}
577
578void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
579 Vector<VirtualKeyDefinition>& outVirtualKeys) const {
580 outVirtualKeys.clear();
581
582 AutoMutex _l(mLock);
583 Device* device = getDeviceLocked(deviceId);
584 if (device && device->virtualKeyMap) {
585 outVirtualKeys.appendVector(device->virtualKeyMap->getVirtualKeys());
586 }
587}
588
589sp<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
590 AutoMutex _l(mLock);
591 Device* device = getDeviceLocked(deviceId);
592 if (device) {
593 return device->getKeyCharacterMap();
594 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700595 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800596}
597
598bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId,
599 const sp<KeyCharacterMap>& map) {
600 AutoMutex _l(mLock);
601 Device* device = getDeviceLocked(deviceId);
602 if (device) {
603 if (map != device->overlayKeyMap) {
604 device->overlayKeyMap = map;
605 device->combinedKeyMap = KeyCharacterMap::combine(
606 device->keyMap.keyCharacterMap, map);
607 return true;
608 }
609 }
610 return false;
611}
612
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100613static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
614 std::string rawDescriptor;
615 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800616 identifier.product);
617 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100618 if (!identifier.uniqueId.empty()) {
619 rawDescriptor += "uniqueId:";
620 rawDescriptor += identifier.uniqueId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800621 } else if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100622 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800623 }
624
625 if (identifier.vendor == 0 && identifier.product == 0) {
626 // If we don't know the vendor and product id, then the device is probably
627 // built-in so we need to rely on other information to uniquely identify
628 // the input device. Usually we try to avoid relying on the device name or
629 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100630 if (!identifier.name.empty()) {
631 rawDescriptor += "name:";
632 rawDescriptor += identifier.name;
633 } else if (!identifier.location.empty()) {
634 rawDescriptor += "location:";
635 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800636 }
637 }
638 identifier.descriptor = sha1(rawDescriptor);
639 return rawDescriptor;
640}
641
642void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
643 // Compute a device descriptor that uniquely identifies the device.
644 // The descriptor is assumed to be a stable identifier. Its value should not
645 // change between reboots, reconnections, firmware updates or new releases
646 // of Android. In practice we sometimes get devices that cannot be uniquely
647 // identified. In this case we enforce uniqueness between connected devices.
648 // Ideally, we also want the descriptor to be short and relatively opaque.
649
650 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100651 std::string rawDescriptor = generateDescriptor(identifier);
652 if (identifier.uniqueId.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800653 // If it didn't have a unique id check for conflicts and enforce
654 // uniqueness if necessary.
Yi Kong9b14ac62018-07-17 13:48:38 -0700655 while(getDeviceByDescriptorLocked(identifier.descriptor) != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800656 identifier.nonce++;
657 rawDescriptor = generateDescriptor(identifier);
658 }
659 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100660 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
661 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800662}
663
664void EventHub::vibrate(int32_t deviceId, nsecs_t duration) {
665 AutoMutex _l(mLock);
666 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700667 if (device && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800668 ff_effect effect;
669 memset(&effect, 0, sizeof(effect));
670 effect.type = FF_RUMBLE;
671 effect.id = device->ffEffectId;
672 effect.u.rumble.strong_magnitude = 0xc000;
673 effect.u.rumble.weak_magnitude = 0xc000;
674 effect.replay.length = (duration + 999999LL) / 1000000LL;
675 effect.replay.delay = 0;
676 if (ioctl(device->fd, EVIOCSFF, &effect)) {
677 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100678 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800679 return;
680 }
681 device->ffEffectId = effect.id;
682
683 struct input_event ev;
684 ev.time.tv_sec = 0;
685 ev.time.tv_usec = 0;
686 ev.type = EV_FF;
687 ev.code = device->ffEffectId;
688 ev.value = 1;
689 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
690 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100691 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800692 return;
693 }
694 device->ffEffectPlaying = true;
695 }
696}
697
698void EventHub::cancelVibrate(int32_t deviceId) {
699 AutoMutex _l(mLock);
700 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700701 if (device && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800702 if (device->ffEffectPlaying) {
703 device->ffEffectPlaying = false;
704
705 struct input_event ev;
706 ev.time.tv_sec = 0;
707 ev.time.tv_usec = 0;
708 ev.type = EV_FF;
709 ev.code = device->ffEffectId;
710 ev.value = 0;
711 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
712 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100713 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800714 return;
715 }
716 }
717 }
718}
719
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100720EventHub::Device* EventHub::getDeviceByDescriptorLocked(const std::string& descriptor) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800721 size_t size = mDevices.size();
722 for (size_t i = 0; i < size; i++) {
723 Device* device = mDevices.valueAt(i);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100724 if (descriptor == device->identifier.descriptor) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800725 return device;
726 }
727 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700728 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800729}
730
731EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
732 if (deviceId == BUILT_IN_KEYBOARD_ID) {
733 deviceId = mBuiltInKeyboardId;
734 }
735 ssize_t index = mDevices.indexOfKey(deviceId);
736 return index >= 0 ? mDevices.valueAt(index) : NULL;
737}
738
739EventHub::Device* EventHub::getDeviceByPathLocked(const char* devicePath) const {
740 for (size_t i = 0; i < mDevices.size(); i++) {
741 Device* device = mDevices.valueAt(i);
742 if (device->path == devicePath) {
743 return device;
744 }
745 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700746 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800747}
748
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700749EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
750 for (size_t i = 0; i < mDevices.size(); i++) {
751 Device* device = mDevices.valueAt(i);
752 if (device->fd == fd) {
753 return device;
754 }
755 }
756 return nullptr;
757}
758
Michael Wrightd02c5b62014-02-10 15:10:22 -0800759size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
760 ALOG_ASSERT(bufferSize >= 1);
761
762 AutoMutex _l(mLock);
763
764 struct input_event readBuffer[bufferSize];
765
766 RawEvent* event = buffer;
767 size_t capacity = bufferSize;
768 bool awoken = false;
769 for (;;) {
770 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
771
772 // Reopen input devices if needed.
773 if (mNeedToReopenDevices) {
774 mNeedToReopenDevices = false;
775
776 ALOGI("Reopening all input devices due to a configuration change.");
777
778 closeAllDevicesLocked();
779 mNeedToScanDevices = true;
780 break; // return to the caller before we actually rescan
781 }
782
783 // Report any devices that had last been added/removed.
784 while (mClosingDevices) {
785 Device* device = mClosingDevices;
786 ALOGV("Reporting device closed: id=%d, name=%s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100787 device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788 mClosingDevices = device->next;
789 event->when = now;
790 event->deviceId = device->id == mBuiltInKeyboardId ? BUILT_IN_KEYBOARD_ID : device->id;
791 event->type = DEVICE_REMOVED;
792 event += 1;
793 delete device;
794 mNeedToSendFinishedDeviceScan = true;
795 if (--capacity == 0) {
796 break;
797 }
798 }
799
800 if (mNeedToScanDevices) {
801 mNeedToScanDevices = false;
802 scanDevicesLocked();
803 mNeedToSendFinishedDeviceScan = true;
804 }
805
Yi Kong9b14ac62018-07-17 13:48:38 -0700806 while (mOpeningDevices != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800807 Device* device = mOpeningDevices;
808 ALOGV("Reporting device opened: id=%d, name=%s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100809 device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800810 mOpeningDevices = device->next;
811 event->when = now;
812 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
813 event->type = DEVICE_ADDED;
814 event += 1;
815 mNeedToSendFinishedDeviceScan = true;
816 if (--capacity == 0) {
817 break;
818 }
819 }
820
821 if (mNeedToSendFinishedDeviceScan) {
822 mNeedToSendFinishedDeviceScan = false;
823 event->when = now;
824 event->type = FINISHED_DEVICE_SCAN;
825 event += 1;
826 if (--capacity == 0) {
827 break;
828 }
829 }
830
831 // Grab the next input event.
832 bool deviceChanged = false;
833 while (mPendingEventIndex < mPendingEventCount) {
834 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700835 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800836 if (eventItem.events & EPOLLIN) {
837 mPendingINotify = true;
838 } else {
839 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
840 }
841 continue;
842 }
843
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700844 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800845 if (eventItem.events & EPOLLIN) {
846 ALOGV("awoken after wake()");
847 awoken = true;
848 char buffer[16];
849 ssize_t nRead;
850 do {
851 nRead = read(mWakeReadPipeFd, buffer, sizeof(buffer));
852 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(buffer));
853 } else {
854 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
855 eventItem.events);
856 }
857 continue;
858 }
859
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700860 Device* device = getDeviceByFdLocked(eventItem.data.fd);
861 if (device == nullptr) {
862 ALOGW("Received unexpected epoll event 0x%08x for unknown device fd %d.",
863 eventItem.events, eventItem.data.fd);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800864 continue;
865 }
866
Michael Wrightd02c5b62014-02-10 15:10:22 -0800867 if (eventItem.events & EPOLLIN) {
868 int32_t readSize = read(device->fd, readBuffer,
869 sizeof(struct input_event) * capacity);
870 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
871 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -0700872 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
873 " bufferSize: %zu capacity: %zu errno: %d)\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874 device->fd, readSize, bufferSize, capacity, errno);
875 deviceChanged = true;
876 closeDeviceLocked(device);
877 } else if (readSize < 0) {
878 if (errno != EAGAIN && errno != EINTR) {
879 ALOGW("could not get event (errno=%d)", errno);
880 }
881 } else if ((readSize % sizeof(struct input_event)) != 0) {
882 ALOGE("could not get event (wrong size: %d)", readSize);
883 } else {
884 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
885
886 size_t count = size_t(readSize) / sizeof(struct input_event);
887 for (size_t i = 0; i < count; i++) {
888 struct input_event& iev = readBuffer[i];
889 ALOGV("%s got: time=%d.%06d, type=%d, code=%d, value=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100890 device->path.c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800891 (int) iev.time.tv_sec, (int) iev.time.tv_usec,
892 iev.type, iev.code, iev.value);
893
Michael Wrightd02c5b62014-02-10 15:10:22 -0800894 // Use the time specified in the event instead of the current time
895 // so that downstream code can get more accurate estimates of
896 // event dispatch latency from the time the event is enqueued onto
897 // the evdev client buffer.
898 //
899 // The event's timestamp fortuitously uses the same monotonic clock
900 // time base as the rest of Android. The kernel event device driver
901 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
902 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
903 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
904 // system call that also queries ktime_get_ts().
905 event->when = nsecs_t(iev.time.tv_sec) * 1000000000LL
906 + nsecs_t(iev.time.tv_usec) * 1000LL;
Mark Salyzyn5aa26b22014-06-10 13:07:44 -0700907 ALOGV("event time %" PRId64 ", now %" PRId64, event->when, now);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800908
909 // Bug 7291243: Add a guard in case the kernel generates timestamps
910 // that appear to be far into the future because they were generated
911 // using the wrong clock source.
912 //
913 // This can happen because when the input device is initially opened
914 // it has a default clock source of CLOCK_REALTIME. Any input events
915 // enqueued right after the device is opened will have timestamps
916 // generated using CLOCK_REALTIME. We later set the clock source
917 // to CLOCK_MONOTONIC but it is already too late.
918 //
919 // Invalid input event timestamps can result in ANRs, crashes and
920 // and other issues that are hard to track down. We must not let them
921 // propagate through the system.
922 //
923 // Log a warning so that we notice the problem and recover gracefully.
924 if (event->when >= now + 10 * 1000000000LL) {
925 // Double-check. Time may have moved on.
926 nsecs_t time = systemTime(SYSTEM_TIME_MONOTONIC);
927 if (event->when > time) {
928 ALOGW("An input event from %s has a timestamp that appears to "
929 "have been generated using the wrong clock source "
930 "(expected CLOCK_MONOTONIC): "
Mark Salyzyn5aa26b22014-06-10 13:07:44 -0700931 "event time %" PRId64 ", current time %" PRId64
932 ", call time %" PRId64 ". "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800933 "Using current time instead.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100934 device->path.c_str(), event->when, time, now);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800935 event->when = time;
936 } else {
937 ALOGV("Event time is ok but failed the fast path and required "
938 "an extra call to systemTime: "
Mark Salyzyn5aa26b22014-06-10 13:07:44 -0700939 "event time %" PRId64 ", current time %" PRId64
940 ", call time %" PRId64 ".",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800941 event->when, time, now);
942 }
943 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800944 event->deviceId = deviceId;
945 event->type = iev.type;
946 event->code = iev.code;
947 event->value = iev.value;
948 event += 1;
949 capacity -= 1;
950 }
951 if (capacity == 0) {
952 // The result buffer is full. Reset the pending event index
953 // so we will try to read the device again on the next iteration.
954 mPendingEventIndex -= 1;
955 break;
956 }
957 }
958 } else if (eventItem.events & EPOLLHUP) {
959 ALOGI("Removing device %s due to epoll hang-up event.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100960 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800961 deviceChanged = true;
962 closeDeviceLocked(device);
963 } else {
964 ALOGW("Received unexpected epoll event 0x%08x for device %s.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100965 eventItem.events, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800966 }
967 }
968
969 // readNotify() will modify the list of devices so this must be done after
970 // processing all other events to ensure that we read all remaining events
971 // before closing the devices.
972 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
973 mPendingINotify = false;
974 readNotifyLocked();
975 deviceChanged = true;
976 }
977
978 // Report added or removed devices immediately.
979 if (deviceChanged) {
980 continue;
981 }
982
983 // Return now if we have collected any events or if we were explicitly awoken.
984 if (event != buffer || awoken) {
985 break;
986 }
987
988 // Poll for events. Mind the wake lock dance!
989 // We hold a wake lock at all times except during epoll_wait(). This works due to some
990 // subtle choreography. When a device driver has pending (unread) events, it acquires
991 // a kernel wake lock. However, once the last pending event has been read, the device
992 // driver will release the kernel wake lock. To prevent the system from going to sleep
993 // when this happens, the EventHub holds onto its own user wake lock while the client
994 // is processing events. Thus the system can only sleep if there are no events
995 // pending or currently being processed.
996 //
997 // The timeout is advisory only. If the device is asleep, it will not wake just to
998 // service the timeout.
999 mPendingEventIndex = 0;
1000
1001 mLock.unlock(); // release lock before poll, must be before release_wake_lock
1002 release_wake_lock(WAKE_LOCK_ID);
1003
1004 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1005
1006 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
1007 mLock.lock(); // reacquire lock after poll, must be after acquire_wake_lock
1008
1009 if (pollResult == 0) {
1010 // Timed out.
1011 mPendingEventCount = 0;
1012 break;
1013 }
1014
1015 if (pollResult < 0) {
1016 // An error occurred.
1017 mPendingEventCount = 0;
1018
1019 // Sleep after errors to avoid locking up the system.
1020 // Hopefully the error is transient.
1021 if (errno != EINTR) {
1022 ALOGW("poll failed (errno=%d)\n", errno);
1023 usleep(100000);
1024 }
1025 } else {
1026 // Some events occurred.
1027 mPendingEventCount = size_t(pollResult);
1028 }
1029 }
1030
1031 // All done, return the number of events we read.
1032 return event - buffer;
1033}
1034
1035void EventHub::wake() {
1036 ALOGV("wake() called");
1037
1038 ssize_t nWrite;
1039 do {
1040 nWrite = write(mWakeWritePipeFd, "W", 1);
1041 } while (nWrite == -1 && errno == EINTR);
1042
1043 if (nWrite != 1 && errno != EAGAIN) {
1044 ALOGW("Could not write wake signal, errno=%d", errno);
1045 }
1046}
1047
1048void EventHub::scanDevicesLocked() {
1049 status_t res = scanDirLocked(DEVICE_PATH);
1050 if(res < 0) {
1051 ALOGE("scan dir failed for %s\n", DEVICE_PATH);
1052 }
1053 if (mDevices.indexOfKey(VIRTUAL_KEYBOARD_ID) < 0) {
1054 createVirtualKeyboardLocked();
1055 }
1056}
1057
1058// ----------------------------------------------------------------------------
1059
1060static bool containsNonZeroByte(const uint8_t* array, uint32_t startIndex, uint32_t endIndex) {
1061 const uint8_t* end = array + endIndex;
1062 array += startIndex;
1063 while (array != end) {
1064 if (*(array++) != 0) {
1065 return true;
1066 }
1067 }
1068 return false;
1069}
1070
1071static const int32_t GAMEPAD_KEYCODES[] = {
1072 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C,
1073 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z,
1074 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1,
1075 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2,
1076 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR,
1077 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001078};
1079
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001080status_t EventHub::registerFdForEpoll(int fd) {
1081 struct epoll_event eventItem = {};
1082 eventItem.events = EPOLLIN | EPOLLWAKEUP;
1083 eventItem.data.fd = fd;
1084 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1085 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001086 return -errno;
1087 }
1088 return OK;
1089}
1090
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001091status_t EventHub::unregisterFdFromEpoll(int fd) {
1092 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
1093 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
1094 return -errno;
1095 }
1096 return OK;
1097}
1098
1099status_t EventHub::registerDeviceForEpollLocked(Device* device) {
1100 if (device == nullptr) {
1101 if (DEBUG) {
1102 LOG_ALWAYS_FATAL("Cannot call registerDeviceForEpollLocked with null Device");
1103 }
1104 return BAD_VALUE;
1105 }
1106 status_t result = registerFdForEpoll(device->fd);
1107 if (result != OK) {
1108 ALOGE("Could not add input device fd to epoll for device %" PRId32, device->id);
1109 }
1110 return result;
1111}
1112
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001113status_t EventHub::unregisterDeviceFromEpollLocked(Device* device) {
1114 if (device->hasValidFd()) {
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001115 status_t result = unregisterFdFromEpoll(device->fd);
1116 if (result != OK) {
1117 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device->id);
1118 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001119 }
1120 }
1121 return OK;
1122}
1123
Michael Wrightd02c5b62014-02-10 15:10:22 -08001124status_t EventHub::openDeviceLocked(const char *devicePath) {
1125 char buffer[80];
1126
1127 ALOGV("Opening device: %s", devicePath);
1128
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001129 int fd = open(devicePath, O_RDWR | O_CLOEXEC | O_NONBLOCK);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001130 if(fd < 0) {
1131 ALOGE("could not open %s, %s\n", devicePath, strerror(errno));
1132 return -1;
1133 }
1134
1135 InputDeviceIdentifier identifier;
1136
1137 // Get device name.
1138 if(ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001139 ALOGE("Could not get device name for %s: %s", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001140 } else {
1141 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001142 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001143 }
1144
1145 // Check to see if the device is on our excluded list
1146 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001147 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001148 if (identifier.name == item) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001149 ALOGI("ignoring event id %s driver %s\n", devicePath, item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001150 close(fd);
1151 return -1;
1152 }
1153 }
1154
1155 // Get device driver version.
1156 int driverVersion;
1157 if(ioctl(fd, EVIOCGVERSION, &driverVersion)) {
1158 ALOGE("could not get driver version for %s, %s\n", devicePath, strerror(errno));
1159 close(fd);
1160 return -1;
1161 }
1162
1163 // Get device identifier.
1164 struct input_id inputId;
1165 if(ioctl(fd, EVIOCGID, &inputId)) {
1166 ALOGE("could not get device input id for %s, %s\n", devicePath, strerror(errno));
1167 close(fd);
1168 return -1;
1169 }
1170 identifier.bus = inputId.bustype;
1171 identifier.product = inputId.product;
1172 identifier.vendor = inputId.vendor;
1173 identifier.version = inputId.version;
1174
1175 // Get device physical location.
1176 if(ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
1177 //fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
1178 } else {
1179 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001180 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001181 }
1182
1183 // Get device unique id.
1184 if(ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
1185 //fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
1186 } else {
1187 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001188 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001189 }
1190
1191 // Fill in the descriptor.
1192 assignDescriptorLocked(identifier);
1193
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194 // Allocate device. (The device object takes ownership of the fd at this point.)
1195 int32_t deviceId = mNextDeviceId++;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001196 Device* device = new Device(fd, deviceId, devicePath, identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001197
1198 ALOGV("add device %d: %s\n", deviceId, devicePath);
1199 ALOGV(" bus: %04x\n"
1200 " vendor %04x\n"
1201 " product %04x\n"
1202 " version %04x\n",
1203 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001204 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
1205 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
1206 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
1207 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001208 ALOGV(" driver: v%d.%d.%d\n",
1209 driverVersion >> 16, (driverVersion >> 8) & 0xff, driverVersion & 0xff);
1210
1211 // Load the configuration file for the device.
1212 loadConfigurationLocked(device);
1213
1214 // Figure out the kinds of events the device reports.
1215 ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(device->keyBitmask)), device->keyBitmask);
1216 ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(device->absBitmask)), device->absBitmask);
1217 ioctl(fd, EVIOCGBIT(EV_REL, sizeof(device->relBitmask)), device->relBitmask);
1218 ioctl(fd, EVIOCGBIT(EV_SW, sizeof(device->swBitmask)), device->swBitmask);
1219 ioctl(fd, EVIOCGBIT(EV_LED, sizeof(device->ledBitmask)), device->ledBitmask);
1220 ioctl(fd, EVIOCGBIT(EV_FF, sizeof(device->ffBitmask)), device->ffBitmask);
1221 ioctl(fd, EVIOCGPROP(sizeof(device->propBitmask)), device->propBitmask);
1222
1223 // See if this is a keyboard. Ignore everything in the button range except for
1224 // joystick and gamepad buttons which are handled like keyboards for the most part.
1225 bool haveKeyboardKeys = containsNonZeroByte(device->keyBitmask, 0, sizeof_bit_array(BTN_MISC))
1226 || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(KEY_OK),
1227 sizeof_bit_array(KEY_MAX + 1));
1228 bool haveGamepadButtons = containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_MISC),
1229 sizeof_bit_array(BTN_MOUSE))
1230 || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_JOYSTICK),
1231 sizeof_bit_array(BTN_DIGI));
1232 if (haveKeyboardKeys || haveGamepadButtons) {
1233 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1234 }
1235
1236 // See if this is a cursor device such as a trackball or mouse.
1237 if (test_bit(BTN_MOUSE, device->keyBitmask)
1238 && test_bit(REL_X, device->relBitmask)
1239 && test_bit(REL_Y, device->relBitmask)) {
1240 device->classes |= INPUT_DEVICE_CLASS_CURSOR;
1241 }
1242
Prashant Malani1941ff52015-08-11 18:29:28 -07001243 // See if this is a rotary encoder type device.
1244 String8 deviceType = String8();
1245 if (device->configuration &&
1246 device->configuration->tryGetProperty(String8("device.type"), deviceType)) {
1247 if (!deviceType.compare(String8("rotaryEncoder"))) {
1248 device->classes |= INPUT_DEVICE_CLASS_ROTARY_ENCODER;
1249 }
1250 }
1251
Michael Wrightd02c5b62014-02-10 15:10:22 -08001252 // See if this is a touch pad.
1253 // Is this a new modern multi-touch driver?
1254 if (test_bit(ABS_MT_POSITION_X, device->absBitmask)
1255 && test_bit(ABS_MT_POSITION_Y, device->absBitmask)) {
1256 // Some joysticks such as the PS3 controller report axes that conflict
1257 // with the ABS_MT range. Try to confirm that the device really is
1258 // a touch screen.
1259 if (test_bit(BTN_TOUCH, device->keyBitmask) || !haveGamepadButtons) {
1260 device->classes |= INPUT_DEVICE_CLASS_TOUCH | INPUT_DEVICE_CLASS_TOUCH_MT;
1261 }
1262 // Is this an old style single-touch driver?
1263 } else if (test_bit(BTN_TOUCH, device->keyBitmask)
1264 && test_bit(ABS_X, device->absBitmask)
1265 && test_bit(ABS_Y, device->absBitmask)) {
1266 device->classes |= INPUT_DEVICE_CLASS_TOUCH;
Michael Wright842500e2015-03-13 17:32:02 -07001267 // Is this a BT stylus?
1268 } else if ((test_bit(ABS_PRESSURE, device->absBitmask) ||
1269 test_bit(BTN_TOUCH, device->keyBitmask))
1270 && !test_bit(ABS_X, device->absBitmask)
1271 && !test_bit(ABS_Y, device->absBitmask)) {
1272 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
1273 // Keyboard will try to claim some of the buttons but we really want to reserve those so we
1274 // can fuse it with the touch screen data, so just take them back. Note this means an
1275 // external stylus cannot also be a keyboard device.
1276 device->classes &= ~INPUT_DEVICE_CLASS_KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001277 }
1278
1279 // See if this device is a joystick.
1280 // Assumes that joysticks always have gamepad buttons in order to distinguish them
1281 // from other devices such as accelerometers that also have absolute axes.
1282 if (haveGamepadButtons) {
1283 uint32_t assumedClasses = device->classes | INPUT_DEVICE_CLASS_JOYSTICK;
1284 for (int i = 0; i <= ABS_MAX; i++) {
1285 if (test_bit(i, device->absBitmask)
1286 && (getAbsAxisUsage(i, assumedClasses) & INPUT_DEVICE_CLASS_JOYSTICK)) {
1287 device->classes = assumedClasses;
1288 break;
1289 }
1290 }
1291 }
1292
1293 // Check whether this device has switches.
1294 for (int i = 0; i <= SW_MAX; i++) {
1295 if (test_bit(i, device->swBitmask)) {
1296 device->classes |= INPUT_DEVICE_CLASS_SWITCH;
1297 break;
1298 }
1299 }
1300
1301 // Check whether this device supports the vibrator.
1302 if (test_bit(FF_RUMBLE, device->ffBitmask)) {
1303 device->classes |= INPUT_DEVICE_CLASS_VIBRATOR;
1304 }
1305
1306 // Configure virtual keys.
1307 if ((device->classes & INPUT_DEVICE_CLASS_TOUCH)) {
1308 // Load the virtual keys for the touch screen, if any.
1309 // We do this now so that we can make sure to load the keymap if necessary.
1310 status_t status = loadVirtualKeyMapLocked(device);
1311 if (!status) {
1312 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1313 }
1314 }
1315
1316 // Load the key map.
1317 // We need to do this for joysticks too because the key layout may specify axes.
1318 status_t keyMapStatus = NAME_NOT_FOUND;
1319 if (device->classes & (INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_JOYSTICK)) {
1320 // Load the keymap for the device.
1321 keyMapStatus = loadKeyMapLocked(device);
1322 }
1323
1324 // Configure the keyboard, gamepad or virtual keyboard.
1325 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1326 // Register the keyboard as a built-in keyboard if it is eligible.
1327 if (!keyMapStatus
1328 && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD
1329 && isEligibleBuiltInKeyboard(device->identifier,
1330 device->configuration, &device->keyMap)) {
1331 mBuiltInKeyboardId = device->id;
1332 }
1333
1334 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
1335 if (hasKeycodeLocked(device, AKEYCODE_Q)) {
1336 device->classes |= INPUT_DEVICE_CLASS_ALPHAKEY;
1337 }
1338
1339 // See if this device has a DPAD.
1340 if (hasKeycodeLocked(device, AKEYCODE_DPAD_UP) &&
1341 hasKeycodeLocked(device, AKEYCODE_DPAD_DOWN) &&
1342 hasKeycodeLocked(device, AKEYCODE_DPAD_LEFT) &&
1343 hasKeycodeLocked(device, AKEYCODE_DPAD_RIGHT) &&
1344 hasKeycodeLocked(device, AKEYCODE_DPAD_CENTER)) {
1345 device->classes |= INPUT_DEVICE_CLASS_DPAD;
1346 }
1347
1348 // See if this device has a gamepad.
1349 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES)/sizeof(GAMEPAD_KEYCODES[0]); i++) {
1350 if (hasKeycodeLocked(device, GAMEPAD_KEYCODES[i])) {
1351 device->classes |= INPUT_DEVICE_CLASS_GAMEPAD;
1352 break;
1353 }
1354 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001355 }
1356
1357 // If the device isn't recognized as something we handle, don't monitor it.
1358 if (device->classes == 0) {
1359 ALOGV("Dropping device: id=%d, path='%s', name='%s'",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001360 deviceId, devicePath, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001361 delete device;
1362 return -1;
1363 }
1364
Tim Kilbourn063ff532015-04-08 10:26:18 -07001365 // Determine whether the device has a mic.
1366 if (deviceHasMicLocked(device)) {
1367 device->classes |= INPUT_DEVICE_CLASS_MIC;
1368 }
1369
Michael Wrightd02c5b62014-02-10 15:10:22 -08001370 // Determine whether the device is external or internal.
1371 if (isExternalDeviceLocked(device)) {
1372 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL;
1373 }
1374
Michael Wright42f2c6a2014-03-12 10:33:03 -07001375 if (device->classes & (INPUT_DEVICE_CLASS_JOYSTICK | INPUT_DEVICE_CLASS_DPAD)
1376 && device->classes & INPUT_DEVICE_CLASS_GAMEPAD) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001377 device->controllerNumber = getNextControllerNumberLocked(device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001378 setLedForControllerLocked(device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001379 }
1380
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001381
1382 if (registerDeviceForEpollLocked(device) != OK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001383 delete device;
1384 return -1;
1385 }
1386
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001387 configureFd(device);
1388
1389 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=0x%x, "
1390 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001391 deviceId, fd, devicePath, device->identifier.name.c_str(),
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001392 device->classes,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001393 device->configurationFile.c_str(),
1394 device->keyMap.keyLayoutFile.c_str(),
1395 device->keyMap.keyCharacterMapFile.c_str(),
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001396 toString(mBuiltInKeyboardId == deviceId));
1397
1398 addDeviceLocked(device);
1399 return OK;
1400}
1401
1402void EventHub::configureFd(Device* device) {
1403 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
1404 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1405 // Disable kernel key repeat since we handle it ourselves
1406 unsigned int repeatRate[] = {0, 0};
1407 if (ioctl(device->fd, EVIOCSREP, repeatRate)) {
1408 ALOGW("Unable to disable kernel key repeat for %s: %s",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001409 device->path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001410 }
1411 }
1412
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001413 std::string wakeMechanism = "EPOLLWAKEUP";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001414 if (!mUsingEpollWakeup) {
1415#ifndef EVIOCSSUSPENDBLOCK
1416 // uapi headers don't include EVIOCSSUSPENDBLOCK, and future kernels
1417 // will use an epoll flag instead, so as long as we want to support
1418 // this feature, we need to be prepared to define the ioctl ourselves.
1419#define EVIOCSSUSPENDBLOCK _IOW('E', 0x91, int)
1420#endif
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001421 if (ioctl(device->fd, EVIOCSSUSPENDBLOCK, 1)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001422 wakeMechanism = "<none>";
1423 } else {
1424 wakeMechanism = "EVIOCSSUSPENDBLOCK";
1425 }
1426 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001427 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
1428 // associated with input events. This is important because the input system
1429 // uses the timestamps extensively and assumes they were recorded using the monotonic
1430 // clock.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001431 int clockId = CLOCK_MONOTONIC;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001432 bool usingClockIoctl = !ioctl(device->fd, EVIOCSCLOCKID, &clockId);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001433 ALOGI("wakeMechanism=%s, usingClockIoctl=%s", wakeMechanism.c_str(),
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001434 toString(usingClockIoctl));
1435}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001436
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001437bool EventHub::isDeviceEnabled(int32_t deviceId) {
1438 AutoMutex _l(mLock);
1439 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001440 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001441 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1442 return false;
1443 }
1444 return device->enabled;
1445}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001446
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001447status_t EventHub::enableDevice(int32_t deviceId) {
1448 AutoMutex _l(mLock);
1449 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001450 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001451 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1452 return BAD_VALUE;
1453 }
1454 if (device->enabled) {
1455 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
1456 return OK;
1457 }
1458 status_t result = device->enable();
1459 if (result != OK) {
1460 ALOGE("Failed to enable device %" PRId32, deviceId);
1461 return result;
1462 }
1463
1464 configureFd(device);
1465
1466 return registerDeviceForEpollLocked(device);
1467}
1468
1469status_t EventHub::disableDevice(int32_t deviceId) {
1470 AutoMutex _l(mLock);
1471 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001472 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001473 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1474 return BAD_VALUE;
1475 }
1476 if (!device->enabled) {
1477 ALOGW("Duplicate call to %s, input device already disabled", __func__);
1478 return OK;
1479 }
1480 unregisterDeviceFromEpollLocked(device);
1481 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001482}
1483
1484void EventHub::createVirtualKeyboardLocked() {
1485 InputDeviceIdentifier identifier;
1486 identifier.name = "Virtual";
1487 identifier.uniqueId = "<virtual>";
1488 assignDescriptorLocked(identifier);
1489
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001490 Device* device = new Device(-1, VIRTUAL_KEYBOARD_ID, "<virtual>", identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001491 device->classes = INPUT_DEVICE_CLASS_KEYBOARD
1492 | INPUT_DEVICE_CLASS_ALPHAKEY
1493 | INPUT_DEVICE_CLASS_DPAD
1494 | INPUT_DEVICE_CLASS_VIRTUAL;
1495 loadKeyMapLocked(device);
1496 addDeviceLocked(device);
1497}
1498
1499void EventHub::addDeviceLocked(Device* device) {
1500 mDevices.add(device->id, device);
1501 device->next = mOpeningDevices;
1502 mOpeningDevices = device;
1503}
1504
1505void EventHub::loadConfigurationLocked(Device* device) {
1506 device->configurationFile = getInputDeviceConfigurationFilePathByDeviceIdentifier(
1507 device->identifier, INPUT_DEVICE_CONFIGURATION_FILE_TYPE_CONFIGURATION);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001508 if (device->configurationFile.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001509 ALOGD("No input device configuration file found for device '%s'.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001510 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001511 } else {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001512 status_t status = PropertyMap::load(String8(device->configurationFile.c_str()),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001513 &device->configuration);
1514 if (status) {
1515 ALOGE("Error loading input device configuration file for device '%s'. "
1516 "Using default configuration.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001517 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001518 }
1519 }
1520}
1521
1522status_t EventHub::loadVirtualKeyMapLocked(Device* device) {
1523 // The virtual key map is supplied by the kernel as a system board property file.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001524 std::string path;
1525 path += "/sys/board_properties/virtualkeys.";
1526 path += device->identifier.name;
1527 if (access(path.c_str(), R_OK)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001528 return NAME_NOT_FOUND;
1529 }
1530 return VirtualKeyMap::load(path, &device->virtualKeyMap);
1531}
1532
1533status_t EventHub::loadKeyMapLocked(Device* device) {
1534 return device->keyMap.load(device->identifier, device->configuration);
1535}
1536
1537bool EventHub::isExternalDeviceLocked(Device* device) {
1538 if (device->configuration) {
1539 bool value;
1540 if (device->configuration->tryGetProperty(String8("device.internal"), value)) {
1541 return !value;
1542 }
1543 }
1544 return device->identifier.bus == BUS_USB || device->identifier.bus == BUS_BLUETOOTH;
1545}
1546
Tim Kilbourn063ff532015-04-08 10:26:18 -07001547bool EventHub::deviceHasMicLocked(Device* device) {
1548 if (device->configuration) {
1549 bool value;
1550 if (device->configuration->tryGetProperty(String8("audio.mic"), value)) {
1551 return value;
1552 }
1553 }
1554 return false;
1555}
1556
Michael Wrightd02c5b62014-02-10 15:10:22 -08001557int32_t EventHub::getNextControllerNumberLocked(Device* device) {
1558 if (mControllerNumbers.isFull()) {
1559 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001560 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001561 return 0;
1562 }
1563 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
1564 // one
1565 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
1566}
1567
1568void EventHub::releaseControllerNumberLocked(Device* device) {
1569 int32_t num = device->controllerNumber;
1570 device->controllerNumber= 0;
1571 if (num == 0) {
1572 return;
1573 }
1574 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
1575}
1576
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001577void EventHub::setLedForControllerLocked(Device* device) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001578 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
1579 setLedStateLocked(device, ALED_CONTROLLER_1 + i, device->controllerNumber == i + 1);
1580 }
1581}
1582
1583bool EventHub::hasKeycodeLocked(Device* device, int keycode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001584 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001585 return false;
1586 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001587
Michael Wrightd02c5b62014-02-10 15:10:22 -08001588 Vector<int32_t> scanCodes;
1589 device->keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes);
1590 const size_t N = scanCodes.size();
1591 for (size_t i=0; i<N && i<=KEY_MAX; i++) {
1592 int32_t sc = scanCodes.itemAt(i);
1593 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, device->keyBitmask)) {
1594 return true;
1595 }
1596 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001597
Michael Wrightd02c5b62014-02-10 15:10:22 -08001598 return false;
1599}
1600
1601status_t EventHub::mapLed(Device* device, int32_t led, int32_t* outScanCode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001602 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001603 return NAME_NOT_FOUND;
1604 }
1605
1606 int32_t scanCode;
1607 if(device->keyMap.keyLayoutMap->findScanCodeForLed(led, &scanCode) != NAME_NOT_FOUND) {
1608 if(scanCode >= 0 && scanCode <= LED_MAX && test_bit(scanCode, device->ledBitmask)) {
1609 *outScanCode = scanCode;
1610 return NO_ERROR;
1611 }
1612 }
1613 return NAME_NOT_FOUND;
1614}
1615
1616status_t EventHub::closeDeviceByPathLocked(const char *devicePath) {
1617 Device* device = getDeviceByPathLocked(devicePath);
1618 if (device) {
1619 closeDeviceLocked(device);
1620 return 0;
1621 }
1622 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath);
1623 return -1;
1624}
1625
1626void EventHub::closeAllDevicesLocked() {
1627 while (mDevices.size() > 0) {
1628 closeDeviceLocked(mDevices.valueAt(mDevices.size() - 1));
1629 }
1630}
1631
1632void EventHub::closeDeviceLocked(Device* device) {
1633 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=0x%x\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001634 device->path.c_str(), device->identifier.name.c_str(), device->id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001635 device->fd, device->classes);
1636
1637 if (device->id == mBuiltInKeyboardId) {
1638 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001639 device->path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001640 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
1641 }
1642
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001643 unregisterDeviceFromEpollLocked(device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001644
1645 releaseControllerNumberLocked(device);
1646
1647 mDevices.removeItem(device->id);
1648 device->close();
1649
1650 // Unlink for opening devices list if it is present.
Yi Kong9b14ac62018-07-17 13:48:38 -07001651 Device* pred = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001652 bool found = false;
Yi Kong9b14ac62018-07-17 13:48:38 -07001653 for (Device* entry = mOpeningDevices; entry != nullptr; ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001654 if (entry == device) {
1655 found = true;
1656 break;
1657 }
1658 pred = entry;
1659 entry = entry->next;
1660 }
1661 if (found) {
1662 // Unlink the device from the opening devices list then delete it.
1663 // We don't need to tell the client that the device was closed because
1664 // it does not even know it was opened in the first place.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001665 ALOGI("Device %s was immediately closed after opening.", device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001666 if (pred) {
1667 pred->next = device->next;
1668 } else {
1669 mOpeningDevices = device->next;
1670 }
1671 delete device;
1672 } else {
1673 // Link into closing devices list.
1674 // The device will be deleted later after we have informed the client.
1675 device->next = mClosingDevices;
1676 mClosingDevices = device;
1677 }
1678}
1679
1680status_t EventHub::readNotifyLocked() {
1681 int res;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001682 char event_buf[512];
1683 int event_size;
1684 int event_pos = 0;
1685 struct inotify_event *event;
1686
1687 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
1688 res = read(mINotifyFd, event_buf, sizeof(event_buf));
1689 if(res < (int)sizeof(*event)) {
1690 if(errno == EINTR)
1691 return 0;
1692 ALOGW("could not get event, %s\n", strerror(errno));
1693 return -1;
1694 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001695
1696 while(res >= (int)sizeof(*event)) {
1697 event = (struct inotify_event *)(event_buf + event_pos);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001698 if(event->len) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001699 if (event->wd == mInputWd) {
1700 std::string filename = StringPrintf("%s/%s", DEVICE_PATH, event->name);
1701 if(event->mask & IN_CREATE) {
1702 openDeviceLocked(filename.c_str());
1703 } else {
1704 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
1705 closeDeviceByPathLocked(filename.c_str());
1706 }
1707 }
1708 else if (event->wd == mVideoWd) {
1709 if (isV4lTouchNode(event->name)) {
1710 std::string filename = StringPrintf("%s/%s", VIDEO_DEVICE_PATH, event->name);
1711 ALOGV("Received an inotify event for a video device %s", filename.c_str());
1712 }
1713 }
1714 else {
1715 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event->wd);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001716 }
1717 }
1718 event_size = sizeof(*event) + event->len;
1719 res -= event_size;
1720 event_pos += event_size;
1721 }
1722 return 0;
1723}
1724
1725status_t EventHub::scanDirLocked(const char *dirname)
1726{
1727 char devname[PATH_MAX];
1728 char *filename;
1729 DIR *dir;
1730 struct dirent *de;
1731 dir = opendir(dirname);
Yi Kong9b14ac62018-07-17 13:48:38 -07001732 if(dir == nullptr)
Michael Wrightd02c5b62014-02-10 15:10:22 -08001733 return -1;
1734 strcpy(devname, dirname);
1735 filename = devname + strlen(devname);
1736 *filename++ = '/';
1737 while((de = readdir(dir))) {
1738 if(de->d_name[0] == '.' &&
1739 (de->d_name[1] == '\0' ||
1740 (de->d_name[1] == '.' && de->d_name[2] == '\0')))
1741 continue;
1742 strcpy(filename, de->d_name);
1743 openDeviceLocked(devname);
1744 }
1745 closedir(dir);
1746 return 0;
1747}
1748
1749void EventHub::requestReopenDevices() {
1750 ALOGV("requestReopenDevices() called");
1751
1752 AutoMutex _l(mLock);
1753 mNeedToReopenDevices = true;
1754}
1755
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001756void EventHub::dump(std::string& dump) {
1757 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001758
1759 { // acquire lock
1760 AutoMutex _l(mLock);
1761
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001762 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001763
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001764 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001765
1766 for (size_t i = 0; i < mDevices.size(); i++) {
1767 const Device* device = mDevices.valueAt(i);
1768 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001769 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001770 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001771 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001772 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001773 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001774 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001775 dump += StringPrintf(INDENT3 "Classes: 0x%08x\n", device->classes);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001776 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001777 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001778 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
1779 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001780 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001781 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001782 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08001783 "product=0x%04x, version=0x%04x\n",
1784 device->identifier.bus, device->identifier.vendor,
1785 device->identifier.product, device->identifier.version);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001786 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001787 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001788 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001789 device->keyMap.keyCharacterMapFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001790 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001791 device->configurationFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001792 dump += StringPrintf(INDENT3 "HaveKeyboardLayoutOverlay: %s\n",
Yi Kong9b14ac62018-07-17 13:48:38 -07001793 toString(device->overlayKeyMap != nullptr));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001794 }
1795 } // release lock
1796}
1797
1798void EventHub::monitor() {
1799 // Acquire and release the lock to ensure that the event hub has not deadlocked.
1800 mLock.lock();
1801 mLock.unlock();
1802}
1803
1804
1805}; // namespace android