blob: a025f31de5c4422b47e07e948ed35369e4e5cf5b [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";
76
Michael Wrightd02c5b62014-02-10 15:10:22 -080077static inline const char* toString(bool value) {
78 return value ? "true" : "false";
79}
80
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010081static std::string sha1(const std::string& in) {
Dan Albert677d87e2014-06-16 17:31:28 -070082 SHA_CTX ctx;
83 SHA1_Init(&ctx);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010084 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
Dan Albert677d87e2014-06-16 17:31:28 -070085 u_char digest[SHA_DIGEST_LENGTH];
86 SHA1_Final(digest, &ctx);
Michael Wrightd02c5b62014-02-10 15:10:22 -080087
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010088 std::string out;
Dan Albert677d87e2014-06-16 17:31:28 -070089 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010090 out += StringPrintf("%02x", digest[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -080091 }
92 return out;
93}
94
95static void getLinuxRelease(int* major, int* minor) {
96 struct utsname info;
97 if (uname(&info) || sscanf(info.release, "%d.%d", major, minor) <= 0) {
98 *major = 0, *minor = 0;
99 ALOGE("Could not get linux version: %s", strerror(errno));
100 }
101}
102
103// --- Global Functions ---
104
105uint32_t getAbsAxisUsage(int32_t axis, uint32_t deviceClasses) {
106 // Touch devices get dibs on touch-related axes.
107 if (deviceClasses & INPUT_DEVICE_CLASS_TOUCH) {
108 switch (axis) {
109 case ABS_X:
110 case ABS_Y:
111 case ABS_PRESSURE:
112 case ABS_TOOL_WIDTH:
113 case ABS_DISTANCE:
114 case ABS_TILT_X:
115 case ABS_TILT_Y:
116 case ABS_MT_SLOT:
117 case ABS_MT_TOUCH_MAJOR:
118 case ABS_MT_TOUCH_MINOR:
119 case ABS_MT_WIDTH_MAJOR:
120 case ABS_MT_WIDTH_MINOR:
121 case ABS_MT_ORIENTATION:
122 case ABS_MT_POSITION_X:
123 case ABS_MT_POSITION_Y:
124 case ABS_MT_TOOL_TYPE:
125 case ABS_MT_BLOB_ID:
126 case ABS_MT_TRACKING_ID:
127 case ABS_MT_PRESSURE:
128 case ABS_MT_DISTANCE:
129 return INPUT_DEVICE_CLASS_TOUCH;
130 }
131 }
132
Michael Wright842500e2015-03-13 17:32:02 -0700133 // External stylus gets the pressure axis
134 if (deviceClasses & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
135 if (axis == ABS_PRESSURE) {
136 return INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
137 }
138 }
139
Michael Wrightd02c5b62014-02-10 15:10:22 -0800140 // Joystick devices get the rest.
141 return deviceClasses & INPUT_DEVICE_CLASS_JOYSTICK;
142}
143
144// --- EventHub::Device ---
145
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100146EventHub::Device::Device(int fd, int32_t id, const std::string& path,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800147 const InputDeviceIdentifier& identifier) :
Yi Kong9b14ac62018-07-17 13:48:38 -0700148 next(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800149 fd(fd), id(id), path(path), identifier(identifier),
Yi Kong9b14ac62018-07-17 13:48:38 -0700150 classes(0), configuration(nullptr), virtualKeyMap(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800151 ffEffectPlaying(false), ffEffectId(-1), controllerNumber(0),
Siarhei Vishniakou88786812018-11-09 15:36:21 -0800152 enabled(true), isVirtual(fd < 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800153 memset(keyBitmask, 0, sizeof(keyBitmask));
154 memset(absBitmask, 0, sizeof(absBitmask));
155 memset(relBitmask, 0, sizeof(relBitmask));
156 memset(swBitmask, 0, sizeof(swBitmask));
157 memset(ledBitmask, 0, sizeof(ledBitmask));
158 memset(ffBitmask, 0, sizeof(ffBitmask));
159 memset(propBitmask, 0, sizeof(propBitmask));
160}
161
162EventHub::Device::~Device() {
163 close();
164 delete configuration;
165 delete virtualKeyMap;
166}
167
168void EventHub::Device::close() {
169 if (fd >= 0) {
170 ::close(fd);
171 fd = -1;
172 }
173}
174
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700175status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100176 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700177 if(fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100178 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700179 return -errno;
180 }
181 enabled = true;
182 return OK;
183}
184
185status_t EventHub::Device::disable() {
186 close();
187 enabled = false;
188 return OK;
189}
190
191bool EventHub::Device::hasValidFd() {
192 return !isVirtual && enabled;
193}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800194
195// --- EventHub ---
196
Michael Wrightd02c5b62014-02-10 15:10:22 -0800197const int EventHub::EPOLL_SIZE_HINT;
198const int EventHub::EPOLL_MAX_EVENTS;
199
200EventHub::EventHub(void) :
201 mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD), mNextDeviceId(1), mControllerNumbers(),
Yi Kong9b14ac62018-07-17 13:48:38 -0700202 mOpeningDevices(nullptr), mClosingDevices(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800203 mNeedToSendFinishedDeviceScan(false),
204 mNeedToReopenDevices(false), mNeedToScanDevices(true),
205 mPendingEventCount(0), mPendingEventIndex(0), mPendingINotify(false) {
206 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
207
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800208 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800209 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance. errno=%d", errno);
210
211 mINotifyFd = inotify_init();
212 int result = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
213 LOG_ALWAYS_FATAL_IF(result < 0, "Could not register INotify for %s. errno=%d",
214 DEVICE_PATH, errno);
215
216 struct epoll_event eventItem;
217 memset(&eventItem, 0, sizeof(eventItem));
218 eventItem.events = EPOLLIN;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700219 eventItem.data.fd = mINotifyFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800220 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
221 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
222
223 int wakeFds[2];
224 result = pipe(wakeFds);
225 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
226
227 mWakeReadPipeFd = wakeFds[0];
228 mWakeWritePipeFd = wakeFds[1];
229
230 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
231 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
232 errno);
233
234 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
235 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
236 errno);
237
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700238 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800239 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
240 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
241 errno);
242
243 int major, minor;
244 getLinuxRelease(&major, &minor);
245 // EPOLLWAKEUP was introduced in kernel 3.5
246 mUsingEpollWakeup = major > 3 || (major == 3 && minor >= 5);
247}
248
249EventHub::~EventHub(void) {
250 closeAllDevicesLocked();
251
252 while (mClosingDevices) {
253 Device* device = mClosingDevices;
254 mClosingDevices = device->next;
255 delete device;
256 }
257
258 ::close(mEpollFd);
259 ::close(mINotifyFd);
260 ::close(mWakeReadPipeFd);
261 ::close(mWakeWritePipeFd);
262
263 release_wake_lock(WAKE_LOCK_ID);
264}
265
266InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
267 AutoMutex _l(mLock);
268 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700269 if (device == nullptr) return InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800270 return device->identifier;
271}
272
273uint32_t EventHub::getDeviceClasses(int32_t deviceId) const {
274 AutoMutex _l(mLock);
275 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700276 if (device == nullptr) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800277 return device->classes;
278}
279
280int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
281 AutoMutex _l(mLock);
282 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700283 if (device == nullptr) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800284 return device->controllerNumber;
285}
286
287void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
288 AutoMutex _l(mLock);
289 Device* device = getDeviceLocked(deviceId);
290 if (device && device->configuration) {
291 *outConfiguration = *device->configuration;
292 } else {
293 outConfiguration->clear();
294 }
295}
296
297status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
298 RawAbsoluteAxisInfo* outAxisInfo) const {
299 outAxisInfo->clear();
300
301 if (axis >= 0 && axis <= ABS_MAX) {
302 AutoMutex _l(mLock);
303
304 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700305 if (device && device->hasValidFd() && test_bit(axis, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800306 struct input_absinfo info;
307 if(ioctl(device->fd, EVIOCGABS(axis), &info)) {
308 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100309 axis, device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800310 return -errno;
311 }
312
313 if (info.minimum != info.maximum) {
314 outAxisInfo->valid = true;
315 outAxisInfo->minValue = info.minimum;
316 outAxisInfo->maxValue = info.maximum;
317 outAxisInfo->flat = info.flat;
318 outAxisInfo->fuzz = info.fuzz;
319 outAxisInfo->resolution = info.resolution;
320 }
321 return OK;
322 }
323 }
324 return -1;
325}
326
327bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
328 if (axis >= 0 && axis <= REL_MAX) {
329 AutoMutex _l(mLock);
330
331 Device* device = getDeviceLocked(deviceId);
332 if (device) {
333 return test_bit(axis, device->relBitmask);
334 }
335 }
336 return false;
337}
338
339bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
340 if (property >= 0 && property <= INPUT_PROP_MAX) {
341 AutoMutex _l(mLock);
342
343 Device* device = getDeviceLocked(deviceId);
344 if (device) {
345 return test_bit(property, device->propBitmask);
346 }
347 }
348 return false;
349}
350
351int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
352 if (scanCode >= 0 && scanCode <= KEY_MAX) {
353 AutoMutex _l(mLock);
354
355 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700356 if (device && device->hasValidFd() && test_bit(scanCode, device->keyBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800357 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
358 memset(keyState, 0, sizeof(keyState));
359 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
360 return test_bit(scanCode, keyState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
361 }
362 }
363 }
364 return AKEY_STATE_UNKNOWN;
365}
366
367int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
368 AutoMutex _l(mLock);
369
370 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700371 if (device && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800372 Vector<int32_t> scanCodes;
373 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode, &scanCodes);
374 if (scanCodes.size() != 0) {
375 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
376 memset(keyState, 0, sizeof(keyState));
377 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
378 for (size_t i = 0; i < scanCodes.size(); i++) {
379 int32_t sc = scanCodes.itemAt(i);
380 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, keyState)) {
381 return AKEY_STATE_DOWN;
382 }
383 }
384 return AKEY_STATE_UP;
385 }
386 }
387 }
388 return AKEY_STATE_UNKNOWN;
389}
390
391int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
392 if (sw >= 0 && sw <= SW_MAX) {
393 AutoMutex _l(mLock);
394
395 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700396 if (device && device->hasValidFd() && test_bit(sw, device->swBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800397 uint8_t swState[sizeof_bit_array(SW_MAX + 1)];
398 memset(swState, 0, sizeof(swState));
399 if (ioctl(device->fd, EVIOCGSW(sizeof(swState)), swState) >= 0) {
400 return test_bit(sw, swState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
401 }
402 }
403 }
404 return AKEY_STATE_UNKNOWN;
405}
406
407status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
408 *outValue = 0;
409
410 if (axis >= 0 && axis <= ABS_MAX) {
411 AutoMutex _l(mLock);
412
413 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700414 if (device && device->hasValidFd() && test_bit(axis, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800415 struct input_absinfo info;
416 if(ioctl(device->fd, EVIOCGABS(axis), &info)) {
417 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100418 axis, device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800419 return -errno;
420 }
421
422 *outValue = info.value;
423 return OK;
424 }
425 }
426 return -1;
427}
428
429bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes,
430 const int32_t* keyCodes, uint8_t* outFlags) const {
431 AutoMutex _l(mLock);
432
433 Device* device = getDeviceLocked(deviceId);
434 if (device && device->keyMap.haveKeyLayout()) {
435 Vector<int32_t> scanCodes;
436 for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) {
437 scanCodes.clear();
438
439 status_t err = device->keyMap.keyLayoutMap->findScanCodesForKey(
440 keyCodes[codeIndex], &scanCodes);
441 if (! err) {
442 // check the possible scan codes identified by the layout map against the
443 // map of codes actually emitted by the driver
444 for (size_t sc = 0; sc < scanCodes.size(); sc++) {
445 if (test_bit(scanCodes[sc], device->keyBitmask)) {
446 outFlags[codeIndex] = 1;
447 break;
448 }
449 }
450 }
451 }
452 return true;
453 }
454 return false;
455}
456
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700457status_t EventHub::mapKey(int32_t deviceId,
458 int32_t scanCode, int32_t usageCode, int32_t metaState,
459 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800460 AutoMutex _l(mLock);
461 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700462 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800463
464 if (device) {
465 // Check the key character map first.
466 sp<KeyCharacterMap> kcm = device->getKeyCharacterMap();
Yi Kong9b14ac62018-07-17 13:48:38 -0700467 if (kcm != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800468 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
469 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700470 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800471 }
472 }
473
474 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700475 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800476 if (!device->keyMap.keyLayoutMap->mapKey(
477 scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700478 status = NO_ERROR;
479 }
480 }
481
482 if (status == NO_ERROR) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700483 if (kcm != nullptr) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700484 kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState);
485 } else {
486 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800487 }
488 }
489 }
490
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700491 if (status != NO_ERROR) {
492 *outKeycode = 0;
493 *outFlags = 0;
494 *outMetaState = metaState;
495 }
496
497 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800498}
499
500status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
501 AutoMutex _l(mLock);
502 Device* device = getDeviceLocked(deviceId);
503
504 if (device && device->keyMap.haveKeyLayout()) {
505 status_t err = device->keyMap.keyLayoutMap->mapAxis(scanCode, outAxisInfo);
506 if (err == NO_ERROR) {
507 return NO_ERROR;
508 }
509 }
510
511 return NAME_NOT_FOUND;
512}
513
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100514void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800515 AutoMutex _l(mLock);
516
517 mExcludedDevices = devices;
518}
519
520bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
521 AutoMutex _l(mLock);
522 Device* device = getDeviceLocked(deviceId);
523 if (device && scanCode >= 0 && scanCode <= KEY_MAX) {
524 if (test_bit(scanCode, device->keyBitmask)) {
525 return true;
526 }
527 }
528 return false;
529}
530
531bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
532 AutoMutex _l(mLock);
533 Device* device = getDeviceLocked(deviceId);
534 int32_t sc;
535 if (device && mapLed(device, led, &sc) == NO_ERROR) {
536 if (test_bit(sc, device->ledBitmask)) {
537 return true;
538 }
539 }
540 return false;
541}
542
543void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
544 AutoMutex _l(mLock);
545 Device* device = getDeviceLocked(deviceId);
546 setLedStateLocked(device, led, on);
547}
548
549void EventHub::setLedStateLocked(Device* device, int32_t led, bool on) {
550 int32_t sc;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700551 if (device && device->hasValidFd() && mapLed(device, led, &sc) != NAME_NOT_FOUND) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800552 struct input_event ev;
553 ev.time.tv_sec = 0;
554 ev.time.tv_usec = 0;
555 ev.type = EV_LED;
556 ev.code = sc;
557 ev.value = on ? 1 : 0;
558
559 ssize_t nWrite;
560 do {
561 nWrite = write(device->fd, &ev, sizeof(struct input_event));
562 } while (nWrite == -1 && errno == EINTR);
563 }
564}
565
566void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
567 Vector<VirtualKeyDefinition>& outVirtualKeys) const {
568 outVirtualKeys.clear();
569
570 AutoMutex _l(mLock);
571 Device* device = getDeviceLocked(deviceId);
572 if (device && device->virtualKeyMap) {
573 outVirtualKeys.appendVector(device->virtualKeyMap->getVirtualKeys());
574 }
575}
576
577sp<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
578 AutoMutex _l(mLock);
579 Device* device = getDeviceLocked(deviceId);
580 if (device) {
581 return device->getKeyCharacterMap();
582 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700583 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800584}
585
586bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId,
587 const sp<KeyCharacterMap>& map) {
588 AutoMutex _l(mLock);
589 Device* device = getDeviceLocked(deviceId);
590 if (device) {
591 if (map != device->overlayKeyMap) {
592 device->overlayKeyMap = map;
593 device->combinedKeyMap = KeyCharacterMap::combine(
594 device->keyMap.keyCharacterMap, map);
595 return true;
596 }
597 }
598 return false;
599}
600
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100601static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
602 std::string rawDescriptor;
603 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800604 identifier.product);
605 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100606 if (!identifier.uniqueId.empty()) {
607 rawDescriptor += "uniqueId:";
608 rawDescriptor += identifier.uniqueId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800609 } else if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100610 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800611 }
612
613 if (identifier.vendor == 0 && identifier.product == 0) {
614 // If we don't know the vendor and product id, then the device is probably
615 // built-in so we need to rely on other information to uniquely identify
616 // the input device. Usually we try to avoid relying on the device name or
617 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100618 if (!identifier.name.empty()) {
619 rawDescriptor += "name:";
620 rawDescriptor += identifier.name;
621 } else if (!identifier.location.empty()) {
622 rawDescriptor += "location:";
623 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800624 }
625 }
626 identifier.descriptor = sha1(rawDescriptor);
627 return rawDescriptor;
628}
629
630void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
631 // Compute a device descriptor that uniquely identifies the device.
632 // The descriptor is assumed to be a stable identifier. Its value should not
633 // change between reboots, reconnections, firmware updates or new releases
634 // of Android. In practice we sometimes get devices that cannot be uniquely
635 // identified. In this case we enforce uniqueness between connected devices.
636 // Ideally, we also want the descriptor to be short and relatively opaque.
637
638 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100639 std::string rawDescriptor = generateDescriptor(identifier);
640 if (identifier.uniqueId.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800641 // If it didn't have a unique id check for conflicts and enforce
642 // uniqueness if necessary.
Yi Kong9b14ac62018-07-17 13:48:38 -0700643 while(getDeviceByDescriptorLocked(identifier.descriptor) != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800644 identifier.nonce++;
645 rawDescriptor = generateDescriptor(identifier);
646 }
647 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100648 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
649 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800650}
651
652void EventHub::vibrate(int32_t deviceId, nsecs_t duration) {
653 AutoMutex _l(mLock);
654 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700655 if (device && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800656 ff_effect effect;
657 memset(&effect, 0, sizeof(effect));
658 effect.type = FF_RUMBLE;
659 effect.id = device->ffEffectId;
660 effect.u.rumble.strong_magnitude = 0xc000;
661 effect.u.rumble.weak_magnitude = 0xc000;
662 effect.replay.length = (duration + 999999LL) / 1000000LL;
663 effect.replay.delay = 0;
664 if (ioctl(device->fd, EVIOCSFF, &effect)) {
665 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100666 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800667 return;
668 }
669 device->ffEffectId = effect.id;
670
671 struct input_event ev;
672 ev.time.tv_sec = 0;
673 ev.time.tv_usec = 0;
674 ev.type = EV_FF;
675 ev.code = device->ffEffectId;
676 ev.value = 1;
677 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
678 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100679 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800680 return;
681 }
682 device->ffEffectPlaying = true;
683 }
684}
685
686void EventHub::cancelVibrate(int32_t deviceId) {
687 AutoMutex _l(mLock);
688 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700689 if (device && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800690 if (device->ffEffectPlaying) {
691 device->ffEffectPlaying = false;
692
693 struct input_event ev;
694 ev.time.tv_sec = 0;
695 ev.time.tv_usec = 0;
696 ev.type = EV_FF;
697 ev.code = device->ffEffectId;
698 ev.value = 0;
699 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
700 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100701 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800702 return;
703 }
704 }
705 }
706}
707
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100708EventHub::Device* EventHub::getDeviceByDescriptorLocked(const std::string& descriptor) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800709 size_t size = mDevices.size();
710 for (size_t i = 0; i < size; i++) {
711 Device* device = mDevices.valueAt(i);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100712 if (descriptor == device->identifier.descriptor) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800713 return device;
714 }
715 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700716 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800717}
718
719EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
720 if (deviceId == BUILT_IN_KEYBOARD_ID) {
721 deviceId = mBuiltInKeyboardId;
722 }
723 ssize_t index = mDevices.indexOfKey(deviceId);
724 return index >= 0 ? mDevices.valueAt(index) : NULL;
725}
726
727EventHub::Device* EventHub::getDeviceByPathLocked(const char* devicePath) const {
728 for (size_t i = 0; i < mDevices.size(); i++) {
729 Device* device = mDevices.valueAt(i);
730 if (device->path == devicePath) {
731 return device;
732 }
733 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700734 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800735}
736
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700737EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
738 for (size_t i = 0; i < mDevices.size(); i++) {
739 Device* device = mDevices.valueAt(i);
740 if (device->fd == fd) {
741 return device;
742 }
743 }
744 return nullptr;
745}
746
Michael Wrightd02c5b62014-02-10 15:10:22 -0800747size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
748 ALOG_ASSERT(bufferSize >= 1);
749
750 AutoMutex _l(mLock);
751
752 struct input_event readBuffer[bufferSize];
753
754 RawEvent* event = buffer;
755 size_t capacity = bufferSize;
756 bool awoken = false;
757 for (;;) {
758 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
759
760 // Reopen input devices if needed.
761 if (mNeedToReopenDevices) {
762 mNeedToReopenDevices = false;
763
764 ALOGI("Reopening all input devices due to a configuration change.");
765
766 closeAllDevicesLocked();
767 mNeedToScanDevices = true;
768 break; // return to the caller before we actually rescan
769 }
770
771 // Report any devices that had last been added/removed.
772 while (mClosingDevices) {
773 Device* device = mClosingDevices;
774 ALOGV("Reporting device closed: id=%d, name=%s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100775 device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800776 mClosingDevices = device->next;
777 event->when = now;
778 event->deviceId = device->id == mBuiltInKeyboardId ? BUILT_IN_KEYBOARD_ID : device->id;
779 event->type = DEVICE_REMOVED;
780 event += 1;
781 delete device;
782 mNeedToSendFinishedDeviceScan = true;
783 if (--capacity == 0) {
784 break;
785 }
786 }
787
788 if (mNeedToScanDevices) {
789 mNeedToScanDevices = false;
790 scanDevicesLocked();
791 mNeedToSendFinishedDeviceScan = true;
792 }
793
Yi Kong9b14ac62018-07-17 13:48:38 -0700794 while (mOpeningDevices != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800795 Device* device = mOpeningDevices;
796 ALOGV("Reporting device opened: id=%d, name=%s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100797 device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800798 mOpeningDevices = device->next;
799 event->when = now;
800 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
801 event->type = DEVICE_ADDED;
802 event += 1;
803 mNeedToSendFinishedDeviceScan = true;
804 if (--capacity == 0) {
805 break;
806 }
807 }
808
809 if (mNeedToSendFinishedDeviceScan) {
810 mNeedToSendFinishedDeviceScan = false;
811 event->when = now;
812 event->type = FINISHED_DEVICE_SCAN;
813 event += 1;
814 if (--capacity == 0) {
815 break;
816 }
817 }
818
819 // Grab the next input event.
820 bool deviceChanged = false;
821 while (mPendingEventIndex < mPendingEventCount) {
822 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700823 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800824 if (eventItem.events & EPOLLIN) {
825 mPendingINotify = true;
826 } else {
827 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
828 }
829 continue;
830 }
831
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700832 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800833 if (eventItem.events & EPOLLIN) {
834 ALOGV("awoken after wake()");
835 awoken = true;
836 char buffer[16];
837 ssize_t nRead;
838 do {
839 nRead = read(mWakeReadPipeFd, buffer, sizeof(buffer));
840 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(buffer));
841 } else {
842 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
843 eventItem.events);
844 }
845 continue;
846 }
847
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700848 Device* device = getDeviceByFdLocked(eventItem.data.fd);
849 if (device == nullptr) {
850 ALOGW("Received unexpected epoll event 0x%08x for unknown device fd %d.",
851 eventItem.events, eventItem.data.fd);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800852 continue;
853 }
854
Michael Wrightd02c5b62014-02-10 15:10:22 -0800855 if (eventItem.events & EPOLLIN) {
856 int32_t readSize = read(device->fd, readBuffer,
857 sizeof(struct input_event) * capacity);
858 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
859 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -0700860 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
861 " bufferSize: %zu capacity: %zu errno: %d)\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800862 device->fd, readSize, bufferSize, capacity, errno);
863 deviceChanged = true;
864 closeDeviceLocked(device);
865 } else if (readSize < 0) {
866 if (errno != EAGAIN && errno != EINTR) {
867 ALOGW("could not get event (errno=%d)", errno);
868 }
869 } else if ((readSize % sizeof(struct input_event)) != 0) {
870 ALOGE("could not get event (wrong size: %d)", readSize);
871 } else {
872 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
873
874 size_t count = size_t(readSize) / sizeof(struct input_event);
875 for (size_t i = 0; i < count; i++) {
876 struct input_event& iev = readBuffer[i];
877 ALOGV("%s got: time=%d.%06d, type=%d, code=%d, value=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100878 device->path.c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800879 (int) iev.time.tv_sec, (int) iev.time.tv_usec,
880 iev.type, iev.code, iev.value);
881
Michael Wrightd02c5b62014-02-10 15:10:22 -0800882 // Use the time specified in the event instead of the current time
883 // so that downstream code can get more accurate estimates of
884 // event dispatch latency from the time the event is enqueued onto
885 // the evdev client buffer.
886 //
887 // The event's timestamp fortuitously uses the same monotonic clock
888 // time base as the rest of Android. The kernel event device driver
889 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
890 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
891 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
892 // system call that also queries ktime_get_ts().
893 event->when = nsecs_t(iev.time.tv_sec) * 1000000000LL
894 + nsecs_t(iev.time.tv_usec) * 1000LL;
Mark Salyzyn5aa26b22014-06-10 13:07:44 -0700895 ALOGV("event time %" PRId64 ", now %" PRId64, event->when, now);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800896
897 // Bug 7291243: Add a guard in case the kernel generates timestamps
898 // that appear to be far into the future because they were generated
899 // using the wrong clock source.
900 //
901 // This can happen because when the input device is initially opened
902 // it has a default clock source of CLOCK_REALTIME. Any input events
903 // enqueued right after the device is opened will have timestamps
904 // generated using CLOCK_REALTIME. We later set the clock source
905 // to CLOCK_MONOTONIC but it is already too late.
906 //
907 // Invalid input event timestamps can result in ANRs, crashes and
908 // and other issues that are hard to track down. We must not let them
909 // propagate through the system.
910 //
911 // Log a warning so that we notice the problem and recover gracefully.
912 if (event->when >= now + 10 * 1000000000LL) {
913 // Double-check. Time may have moved on.
914 nsecs_t time = systemTime(SYSTEM_TIME_MONOTONIC);
915 if (event->when > time) {
916 ALOGW("An input event from %s has a timestamp that appears to "
917 "have been generated using the wrong clock source "
918 "(expected CLOCK_MONOTONIC): "
Mark Salyzyn5aa26b22014-06-10 13:07:44 -0700919 "event time %" PRId64 ", current time %" PRId64
920 ", call time %" PRId64 ". "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800921 "Using current time instead.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100922 device->path.c_str(), event->when, time, now);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800923 event->when = time;
924 } else {
925 ALOGV("Event time is ok but failed the fast path and required "
926 "an extra call to systemTime: "
Mark Salyzyn5aa26b22014-06-10 13:07:44 -0700927 "event time %" PRId64 ", current time %" PRId64
928 ", call time %" PRId64 ".",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800929 event->when, time, now);
930 }
931 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800932 event->deviceId = deviceId;
933 event->type = iev.type;
934 event->code = iev.code;
935 event->value = iev.value;
936 event += 1;
937 capacity -= 1;
938 }
939 if (capacity == 0) {
940 // The result buffer is full. Reset the pending event index
941 // so we will try to read the device again on the next iteration.
942 mPendingEventIndex -= 1;
943 break;
944 }
945 }
946 } else if (eventItem.events & EPOLLHUP) {
947 ALOGI("Removing device %s due to epoll hang-up event.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100948 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800949 deviceChanged = true;
950 closeDeviceLocked(device);
951 } else {
952 ALOGW("Received unexpected epoll event 0x%08x for device %s.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100953 eventItem.events, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800954 }
955 }
956
957 // readNotify() will modify the list of devices so this must be done after
958 // processing all other events to ensure that we read all remaining events
959 // before closing the devices.
960 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
961 mPendingINotify = false;
962 readNotifyLocked();
963 deviceChanged = true;
964 }
965
966 // Report added or removed devices immediately.
967 if (deviceChanged) {
968 continue;
969 }
970
971 // Return now if we have collected any events or if we were explicitly awoken.
972 if (event != buffer || awoken) {
973 break;
974 }
975
976 // Poll for events. Mind the wake lock dance!
977 // We hold a wake lock at all times except during epoll_wait(). This works due to some
978 // subtle choreography. When a device driver has pending (unread) events, it acquires
979 // a kernel wake lock. However, once the last pending event has been read, the device
980 // driver will release the kernel wake lock. To prevent the system from going to sleep
981 // when this happens, the EventHub holds onto its own user wake lock while the client
982 // is processing events. Thus the system can only sleep if there are no events
983 // pending or currently being processed.
984 //
985 // The timeout is advisory only. If the device is asleep, it will not wake just to
986 // service the timeout.
987 mPendingEventIndex = 0;
988
989 mLock.unlock(); // release lock before poll, must be before release_wake_lock
990 release_wake_lock(WAKE_LOCK_ID);
991
992 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
993
994 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
995 mLock.lock(); // reacquire lock after poll, must be after acquire_wake_lock
996
997 if (pollResult == 0) {
998 // Timed out.
999 mPendingEventCount = 0;
1000 break;
1001 }
1002
1003 if (pollResult < 0) {
1004 // An error occurred.
1005 mPendingEventCount = 0;
1006
1007 // Sleep after errors to avoid locking up the system.
1008 // Hopefully the error is transient.
1009 if (errno != EINTR) {
1010 ALOGW("poll failed (errno=%d)\n", errno);
1011 usleep(100000);
1012 }
1013 } else {
1014 // Some events occurred.
1015 mPendingEventCount = size_t(pollResult);
1016 }
1017 }
1018
1019 // All done, return the number of events we read.
1020 return event - buffer;
1021}
1022
1023void EventHub::wake() {
1024 ALOGV("wake() called");
1025
1026 ssize_t nWrite;
1027 do {
1028 nWrite = write(mWakeWritePipeFd, "W", 1);
1029 } while (nWrite == -1 && errno == EINTR);
1030
1031 if (nWrite != 1 && errno != EAGAIN) {
1032 ALOGW("Could not write wake signal, errno=%d", errno);
1033 }
1034}
1035
1036void EventHub::scanDevicesLocked() {
1037 status_t res = scanDirLocked(DEVICE_PATH);
1038 if(res < 0) {
1039 ALOGE("scan dir failed for %s\n", DEVICE_PATH);
1040 }
1041 if (mDevices.indexOfKey(VIRTUAL_KEYBOARD_ID) < 0) {
1042 createVirtualKeyboardLocked();
1043 }
1044}
1045
1046// ----------------------------------------------------------------------------
1047
1048static bool containsNonZeroByte(const uint8_t* array, uint32_t startIndex, uint32_t endIndex) {
1049 const uint8_t* end = array + endIndex;
1050 array += startIndex;
1051 while (array != end) {
1052 if (*(array++) != 0) {
1053 return true;
1054 }
1055 }
1056 return false;
1057}
1058
1059static const int32_t GAMEPAD_KEYCODES[] = {
1060 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C,
1061 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z,
1062 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1,
1063 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2,
1064 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR,
1065 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001066};
1067
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001068status_t EventHub::registerFdForEpoll(int fd) {
1069 struct epoll_event eventItem = {};
1070 eventItem.events = EPOLLIN | EPOLLWAKEUP;
1071 eventItem.data.fd = fd;
1072 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1073 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001074 return -errno;
1075 }
1076 return OK;
1077}
1078
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001079status_t EventHub::unregisterFdFromEpoll(int fd) {
1080 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
1081 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
1082 return -errno;
1083 }
1084 return OK;
1085}
1086
1087status_t EventHub::registerDeviceForEpollLocked(Device* device) {
1088 if (device == nullptr) {
1089 if (DEBUG) {
1090 LOG_ALWAYS_FATAL("Cannot call registerDeviceForEpollLocked with null Device");
1091 }
1092 return BAD_VALUE;
1093 }
1094 status_t result = registerFdForEpoll(device->fd);
1095 if (result != OK) {
1096 ALOGE("Could not add input device fd to epoll for device %" PRId32, device->id);
1097 }
1098 return result;
1099}
1100
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001101status_t EventHub::unregisterDeviceFromEpollLocked(Device* device) {
1102 if (device->hasValidFd()) {
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001103 status_t result = unregisterFdFromEpoll(device->fd);
1104 if (result != OK) {
1105 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device->id);
1106 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001107 }
1108 }
1109 return OK;
1110}
1111
Michael Wrightd02c5b62014-02-10 15:10:22 -08001112status_t EventHub::openDeviceLocked(const char *devicePath) {
1113 char buffer[80];
1114
1115 ALOGV("Opening device: %s", devicePath);
1116
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001117 int fd = open(devicePath, O_RDWR | O_CLOEXEC | O_NONBLOCK);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001118 if(fd < 0) {
1119 ALOGE("could not open %s, %s\n", devicePath, strerror(errno));
1120 return -1;
1121 }
1122
1123 InputDeviceIdentifier identifier;
1124
1125 // Get device name.
1126 if(ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001127 ALOGE("Could not get device name for %s: %s", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001128 } else {
1129 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001130 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001131 }
1132
1133 // Check to see if the device is on our excluded list
1134 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001135 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001136 if (identifier.name == item) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001137 ALOGI("ignoring event id %s driver %s\n", devicePath, item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001138 close(fd);
1139 return -1;
1140 }
1141 }
1142
1143 // Get device driver version.
1144 int driverVersion;
1145 if(ioctl(fd, EVIOCGVERSION, &driverVersion)) {
1146 ALOGE("could not get driver version for %s, %s\n", devicePath, strerror(errno));
1147 close(fd);
1148 return -1;
1149 }
1150
1151 // Get device identifier.
1152 struct input_id inputId;
1153 if(ioctl(fd, EVIOCGID, &inputId)) {
1154 ALOGE("could not get device input id for %s, %s\n", devicePath, strerror(errno));
1155 close(fd);
1156 return -1;
1157 }
1158 identifier.bus = inputId.bustype;
1159 identifier.product = inputId.product;
1160 identifier.vendor = inputId.vendor;
1161 identifier.version = inputId.version;
1162
1163 // Get device physical location.
1164 if(ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
1165 //fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
1166 } else {
1167 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001168 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001169 }
1170
1171 // Get device unique id.
1172 if(ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
1173 //fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
1174 } else {
1175 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001176 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001177 }
1178
1179 // Fill in the descriptor.
1180 assignDescriptorLocked(identifier);
1181
Michael Wrightd02c5b62014-02-10 15:10:22 -08001182 // Allocate device. (The device object takes ownership of the fd at this point.)
1183 int32_t deviceId = mNextDeviceId++;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001184 Device* device = new Device(fd, deviceId, devicePath, identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001185
1186 ALOGV("add device %d: %s\n", deviceId, devicePath);
1187 ALOGV(" bus: %04x\n"
1188 " vendor %04x\n"
1189 " product %04x\n"
1190 " version %04x\n",
1191 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001192 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
1193 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
1194 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
1195 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001196 ALOGV(" driver: v%d.%d.%d\n",
1197 driverVersion >> 16, (driverVersion >> 8) & 0xff, driverVersion & 0xff);
1198
1199 // Load the configuration file for the device.
1200 loadConfigurationLocked(device);
1201
1202 // Figure out the kinds of events the device reports.
1203 ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(device->keyBitmask)), device->keyBitmask);
1204 ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(device->absBitmask)), device->absBitmask);
1205 ioctl(fd, EVIOCGBIT(EV_REL, sizeof(device->relBitmask)), device->relBitmask);
1206 ioctl(fd, EVIOCGBIT(EV_SW, sizeof(device->swBitmask)), device->swBitmask);
1207 ioctl(fd, EVIOCGBIT(EV_LED, sizeof(device->ledBitmask)), device->ledBitmask);
1208 ioctl(fd, EVIOCGBIT(EV_FF, sizeof(device->ffBitmask)), device->ffBitmask);
1209 ioctl(fd, EVIOCGPROP(sizeof(device->propBitmask)), device->propBitmask);
1210
1211 // See if this is a keyboard. Ignore everything in the button range except for
1212 // joystick and gamepad buttons which are handled like keyboards for the most part.
1213 bool haveKeyboardKeys = containsNonZeroByte(device->keyBitmask, 0, sizeof_bit_array(BTN_MISC))
1214 || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(KEY_OK),
1215 sizeof_bit_array(KEY_MAX + 1));
1216 bool haveGamepadButtons = containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_MISC),
1217 sizeof_bit_array(BTN_MOUSE))
1218 || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_JOYSTICK),
1219 sizeof_bit_array(BTN_DIGI));
1220 if (haveKeyboardKeys || haveGamepadButtons) {
1221 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1222 }
1223
1224 // See if this is a cursor device such as a trackball or mouse.
1225 if (test_bit(BTN_MOUSE, device->keyBitmask)
1226 && test_bit(REL_X, device->relBitmask)
1227 && test_bit(REL_Y, device->relBitmask)) {
1228 device->classes |= INPUT_DEVICE_CLASS_CURSOR;
1229 }
1230
Prashant Malani1941ff52015-08-11 18:29:28 -07001231 // See if this is a rotary encoder type device.
1232 String8 deviceType = String8();
1233 if (device->configuration &&
1234 device->configuration->tryGetProperty(String8("device.type"), deviceType)) {
1235 if (!deviceType.compare(String8("rotaryEncoder"))) {
1236 device->classes |= INPUT_DEVICE_CLASS_ROTARY_ENCODER;
1237 }
1238 }
1239
Michael Wrightd02c5b62014-02-10 15:10:22 -08001240 // See if this is a touch pad.
1241 // Is this a new modern multi-touch driver?
1242 if (test_bit(ABS_MT_POSITION_X, device->absBitmask)
1243 && test_bit(ABS_MT_POSITION_Y, device->absBitmask)) {
1244 // Some joysticks such as the PS3 controller report axes that conflict
1245 // with the ABS_MT range. Try to confirm that the device really is
1246 // a touch screen.
1247 if (test_bit(BTN_TOUCH, device->keyBitmask) || !haveGamepadButtons) {
1248 device->classes |= INPUT_DEVICE_CLASS_TOUCH | INPUT_DEVICE_CLASS_TOUCH_MT;
1249 }
1250 // Is this an old style single-touch driver?
1251 } else if (test_bit(BTN_TOUCH, device->keyBitmask)
1252 && test_bit(ABS_X, device->absBitmask)
1253 && test_bit(ABS_Y, device->absBitmask)) {
1254 device->classes |= INPUT_DEVICE_CLASS_TOUCH;
Michael Wright842500e2015-03-13 17:32:02 -07001255 // Is this a BT stylus?
1256 } else if ((test_bit(ABS_PRESSURE, device->absBitmask) ||
1257 test_bit(BTN_TOUCH, device->keyBitmask))
1258 && !test_bit(ABS_X, device->absBitmask)
1259 && !test_bit(ABS_Y, device->absBitmask)) {
1260 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
1261 // Keyboard will try to claim some of the buttons but we really want to reserve those so we
1262 // can fuse it with the touch screen data, so just take them back. Note this means an
1263 // external stylus cannot also be a keyboard device.
1264 device->classes &= ~INPUT_DEVICE_CLASS_KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001265 }
1266
1267 // See if this device is a joystick.
1268 // Assumes that joysticks always have gamepad buttons in order to distinguish them
1269 // from other devices such as accelerometers that also have absolute axes.
1270 if (haveGamepadButtons) {
1271 uint32_t assumedClasses = device->classes | INPUT_DEVICE_CLASS_JOYSTICK;
1272 for (int i = 0; i <= ABS_MAX; i++) {
1273 if (test_bit(i, device->absBitmask)
1274 && (getAbsAxisUsage(i, assumedClasses) & INPUT_DEVICE_CLASS_JOYSTICK)) {
1275 device->classes = assumedClasses;
1276 break;
1277 }
1278 }
1279 }
1280
1281 // Check whether this device has switches.
1282 for (int i = 0; i <= SW_MAX; i++) {
1283 if (test_bit(i, device->swBitmask)) {
1284 device->classes |= INPUT_DEVICE_CLASS_SWITCH;
1285 break;
1286 }
1287 }
1288
1289 // Check whether this device supports the vibrator.
1290 if (test_bit(FF_RUMBLE, device->ffBitmask)) {
1291 device->classes |= INPUT_DEVICE_CLASS_VIBRATOR;
1292 }
1293
1294 // Configure virtual keys.
1295 if ((device->classes & INPUT_DEVICE_CLASS_TOUCH)) {
1296 // Load the virtual keys for the touch screen, if any.
1297 // We do this now so that we can make sure to load the keymap if necessary.
1298 status_t status = loadVirtualKeyMapLocked(device);
1299 if (!status) {
1300 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1301 }
1302 }
1303
1304 // Load the key map.
1305 // We need to do this for joysticks too because the key layout may specify axes.
1306 status_t keyMapStatus = NAME_NOT_FOUND;
1307 if (device->classes & (INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_JOYSTICK)) {
1308 // Load the keymap for the device.
1309 keyMapStatus = loadKeyMapLocked(device);
1310 }
1311
1312 // Configure the keyboard, gamepad or virtual keyboard.
1313 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1314 // Register the keyboard as a built-in keyboard if it is eligible.
1315 if (!keyMapStatus
1316 && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD
1317 && isEligibleBuiltInKeyboard(device->identifier,
1318 device->configuration, &device->keyMap)) {
1319 mBuiltInKeyboardId = device->id;
1320 }
1321
1322 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
1323 if (hasKeycodeLocked(device, AKEYCODE_Q)) {
1324 device->classes |= INPUT_DEVICE_CLASS_ALPHAKEY;
1325 }
1326
1327 // See if this device has a DPAD.
1328 if (hasKeycodeLocked(device, AKEYCODE_DPAD_UP) &&
1329 hasKeycodeLocked(device, AKEYCODE_DPAD_DOWN) &&
1330 hasKeycodeLocked(device, AKEYCODE_DPAD_LEFT) &&
1331 hasKeycodeLocked(device, AKEYCODE_DPAD_RIGHT) &&
1332 hasKeycodeLocked(device, AKEYCODE_DPAD_CENTER)) {
1333 device->classes |= INPUT_DEVICE_CLASS_DPAD;
1334 }
1335
1336 // See if this device has a gamepad.
1337 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES)/sizeof(GAMEPAD_KEYCODES[0]); i++) {
1338 if (hasKeycodeLocked(device, GAMEPAD_KEYCODES[i])) {
1339 device->classes |= INPUT_DEVICE_CLASS_GAMEPAD;
1340 break;
1341 }
1342 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001343 }
1344
1345 // If the device isn't recognized as something we handle, don't monitor it.
1346 if (device->classes == 0) {
1347 ALOGV("Dropping device: id=%d, path='%s', name='%s'",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001348 deviceId, devicePath, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001349 delete device;
1350 return -1;
1351 }
1352
Tim Kilbourn063ff532015-04-08 10:26:18 -07001353 // Determine whether the device has a mic.
1354 if (deviceHasMicLocked(device)) {
1355 device->classes |= INPUT_DEVICE_CLASS_MIC;
1356 }
1357
Michael Wrightd02c5b62014-02-10 15:10:22 -08001358 // Determine whether the device is external or internal.
1359 if (isExternalDeviceLocked(device)) {
1360 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL;
1361 }
1362
Michael Wright42f2c6a2014-03-12 10:33:03 -07001363 if (device->classes & (INPUT_DEVICE_CLASS_JOYSTICK | INPUT_DEVICE_CLASS_DPAD)
1364 && device->classes & INPUT_DEVICE_CLASS_GAMEPAD) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001365 device->controllerNumber = getNextControllerNumberLocked(device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001366 setLedForControllerLocked(device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001367 }
1368
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001369
1370 if (registerDeviceForEpollLocked(device) != OK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001371 delete device;
1372 return -1;
1373 }
1374
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001375 configureFd(device);
1376
1377 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=0x%x, "
1378 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001379 deviceId, fd, devicePath, device->identifier.name.c_str(),
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001380 device->classes,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001381 device->configurationFile.c_str(),
1382 device->keyMap.keyLayoutFile.c_str(),
1383 device->keyMap.keyCharacterMapFile.c_str(),
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001384 toString(mBuiltInKeyboardId == deviceId));
1385
1386 addDeviceLocked(device);
1387 return OK;
1388}
1389
1390void EventHub::configureFd(Device* device) {
1391 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
1392 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1393 // Disable kernel key repeat since we handle it ourselves
1394 unsigned int repeatRate[] = {0, 0};
1395 if (ioctl(device->fd, EVIOCSREP, repeatRate)) {
1396 ALOGW("Unable to disable kernel key repeat for %s: %s",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001397 device->path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001398 }
1399 }
1400
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001401 std::string wakeMechanism = "EPOLLWAKEUP";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001402 if (!mUsingEpollWakeup) {
1403#ifndef EVIOCSSUSPENDBLOCK
1404 // uapi headers don't include EVIOCSSUSPENDBLOCK, and future kernels
1405 // will use an epoll flag instead, so as long as we want to support
1406 // this feature, we need to be prepared to define the ioctl ourselves.
1407#define EVIOCSSUSPENDBLOCK _IOW('E', 0x91, int)
1408#endif
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001409 if (ioctl(device->fd, EVIOCSSUSPENDBLOCK, 1)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001410 wakeMechanism = "<none>";
1411 } else {
1412 wakeMechanism = "EVIOCSSUSPENDBLOCK";
1413 }
1414 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001415 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
1416 // associated with input events. This is important because the input system
1417 // uses the timestamps extensively and assumes they were recorded using the monotonic
1418 // clock.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001419 int clockId = CLOCK_MONOTONIC;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001420 bool usingClockIoctl = !ioctl(device->fd, EVIOCSCLOCKID, &clockId);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001421 ALOGI("wakeMechanism=%s, usingClockIoctl=%s", wakeMechanism.c_str(),
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001422 toString(usingClockIoctl));
1423}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001424
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001425bool EventHub::isDeviceEnabled(int32_t deviceId) {
1426 AutoMutex _l(mLock);
1427 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001428 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001429 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1430 return false;
1431 }
1432 return device->enabled;
1433}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001434
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001435status_t EventHub::enableDevice(int32_t deviceId) {
1436 AutoMutex _l(mLock);
1437 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001438 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001439 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1440 return BAD_VALUE;
1441 }
1442 if (device->enabled) {
1443 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
1444 return OK;
1445 }
1446 status_t result = device->enable();
1447 if (result != OK) {
1448 ALOGE("Failed to enable device %" PRId32, deviceId);
1449 return result;
1450 }
1451
1452 configureFd(device);
1453
1454 return registerDeviceForEpollLocked(device);
1455}
1456
1457status_t EventHub::disableDevice(int32_t deviceId) {
1458 AutoMutex _l(mLock);
1459 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001460 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001461 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1462 return BAD_VALUE;
1463 }
1464 if (!device->enabled) {
1465 ALOGW("Duplicate call to %s, input device already disabled", __func__);
1466 return OK;
1467 }
1468 unregisterDeviceFromEpollLocked(device);
1469 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001470}
1471
1472void EventHub::createVirtualKeyboardLocked() {
1473 InputDeviceIdentifier identifier;
1474 identifier.name = "Virtual";
1475 identifier.uniqueId = "<virtual>";
1476 assignDescriptorLocked(identifier);
1477
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001478 Device* device = new Device(-1, VIRTUAL_KEYBOARD_ID, "<virtual>", identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001479 device->classes = INPUT_DEVICE_CLASS_KEYBOARD
1480 | INPUT_DEVICE_CLASS_ALPHAKEY
1481 | INPUT_DEVICE_CLASS_DPAD
1482 | INPUT_DEVICE_CLASS_VIRTUAL;
1483 loadKeyMapLocked(device);
1484 addDeviceLocked(device);
1485}
1486
1487void EventHub::addDeviceLocked(Device* device) {
1488 mDevices.add(device->id, device);
1489 device->next = mOpeningDevices;
1490 mOpeningDevices = device;
1491}
1492
1493void EventHub::loadConfigurationLocked(Device* device) {
1494 device->configurationFile = getInputDeviceConfigurationFilePathByDeviceIdentifier(
1495 device->identifier, INPUT_DEVICE_CONFIGURATION_FILE_TYPE_CONFIGURATION);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001496 if (device->configurationFile.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001497 ALOGD("No input device configuration file found for device '%s'.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001498 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001499 } else {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001500 status_t status = PropertyMap::load(String8(device->configurationFile.c_str()),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001501 &device->configuration);
1502 if (status) {
1503 ALOGE("Error loading input device configuration file for device '%s'. "
1504 "Using default configuration.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001505 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001506 }
1507 }
1508}
1509
1510status_t EventHub::loadVirtualKeyMapLocked(Device* device) {
1511 // The virtual key map is supplied by the kernel as a system board property file.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001512 std::string path;
1513 path += "/sys/board_properties/virtualkeys.";
1514 path += device->identifier.name;
1515 if (access(path.c_str(), R_OK)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001516 return NAME_NOT_FOUND;
1517 }
1518 return VirtualKeyMap::load(path, &device->virtualKeyMap);
1519}
1520
1521status_t EventHub::loadKeyMapLocked(Device* device) {
1522 return device->keyMap.load(device->identifier, device->configuration);
1523}
1524
1525bool EventHub::isExternalDeviceLocked(Device* device) {
1526 if (device->configuration) {
1527 bool value;
1528 if (device->configuration->tryGetProperty(String8("device.internal"), value)) {
1529 return !value;
1530 }
1531 }
1532 return device->identifier.bus == BUS_USB || device->identifier.bus == BUS_BLUETOOTH;
1533}
1534
Tim Kilbourn063ff532015-04-08 10:26:18 -07001535bool EventHub::deviceHasMicLocked(Device* device) {
1536 if (device->configuration) {
1537 bool value;
1538 if (device->configuration->tryGetProperty(String8("audio.mic"), value)) {
1539 return value;
1540 }
1541 }
1542 return false;
1543}
1544
Michael Wrightd02c5b62014-02-10 15:10:22 -08001545int32_t EventHub::getNextControllerNumberLocked(Device* device) {
1546 if (mControllerNumbers.isFull()) {
1547 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001548 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001549 return 0;
1550 }
1551 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
1552 // one
1553 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
1554}
1555
1556void EventHub::releaseControllerNumberLocked(Device* device) {
1557 int32_t num = device->controllerNumber;
1558 device->controllerNumber= 0;
1559 if (num == 0) {
1560 return;
1561 }
1562 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
1563}
1564
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001565void EventHub::setLedForControllerLocked(Device* device) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001566 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
1567 setLedStateLocked(device, ALED_CONTROLLER_1 + i, device->controllerNumber == i + 1);
1568 }
1569}
1570
1571bool EventHub::hasKeycodeLocked(Device* device, int keycode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001572 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001573 return false;
1574 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001575
Michael Wrightd02c5b62014-02-10 15:10:22 -08001576 Vector<int32_t> scanCodes;
1577 device->keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes);
1578 const size_t N = scanCodes.size();
1579 for (size_t i=0; i<N && i<=KEY_MAX; i++) {
1580 int32_t sc = scanCodes.itemAt(i);
1581 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, device->keyBitmask)) {
1582 return true;
1583 }
1584 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001585
Michael Wrightd02c5b62014-02-10 15:10:22 -08001586 return false;
1587}
1588
1589status_t EventHub::mapLed(Device* device, int32_t led, int32_t* outScanCode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001590 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001591 return NAME_NOT_FOUND;
1592 }
1593
1594 int32_t scanCode;
1595 if(device->keyMap.keyLayoutMap->findScanCodeForLed(led, &scanCode) != NAME_NOT_FOUND) {
1596 if(scanCode >= 0 && scanCode <= LED_MAX && test_bit(scanCode, device->ledBitmask)) {
1597 *outScanCode = scanCode;
1598 return NO_ERROR;
1599 }
1600 }
1601 return NAME_NOT_FOUND;
1602}
1603
1604status_t EventHub::closeDeviceByPathLocked(const char *devicePath) {
1605 Device* device = getDeviceByPathLocked(devicePath);
1606 if (device) {
1607 closeDeviceLocked(device);
1608 return 0;
1609 }
1610 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath);
1611 return -1;
1612}
1613
1614void EventHub::closeAllDevicesLocked() {
1615 while (mDevices.size() > 0) {
1616 closeDeviceLocked(mDevices.valueAt(mDevices.size() - 1));
1617 }
1618}
1619
1620void EventHub::closeDeviceLocked(Device* device) {
1621 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=0x%x\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001622 device->path.c_str(), device->identifier.name.c_str(), device->id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001623 device->fd, device->classes);
1624
1625 if (device->id == mBuiltInKeyboardId) {
1626 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001627 device->path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001628 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
1629 }
1630
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001631 unregisterDeviceFromEpollLocked(device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001632
1633 releaseControllerNumberLocked(device);
1634
1635 mDevices.removeItem(device->id);
1636 device->close();
1637
1638 // Unlink for opening devices list if it is present.
Yi Kong9b14ac62018-07-17 13:48:38 -07001639 Device* pred = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001640 bool found = false;
Yi Kong9b14ac62018-07-17 13:48:38 -07001641 for (Device* entry = mOpeningDevices; entry != nullptr; ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001642 if (entry == device) {
1643 found = true;
1644 break;
1645 }
1646 pred = entry;
1647 entry = entry->next;
1648 }
1649 if (found) {
1650 // Unlink the device from the opening devices list then delete it.
1651 // We don't need to tell the client that the device was closed because
1652 // it does not even know it was opened in the first place.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001653 ALOGI("Device %s was immediately closed after opening.", device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001654 if (pred) {
1655 pred->next = device->next;
1656 } else {
1657 mOpeningDevices = device->next;
1658 }
1659 delete device;
1660 } else {
1661 // Link into closing devices list.
1662 // The device will be deleted later after we have informed the client.
1663 device->next = mClosingDevices;
1664 mClosingDevices = device;
1665 }
1666}
1667
1668status_t EventHub::readNotifyLocked() {
1669 int res;
1670 char devname[PATH_MAX];
1671 char *filename;
1672 char event_buf[512];
1673 int event_size;
1674 int event_pos = 0;
1675 struct inotify_event *event;
1676
1677 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
1678 res = read(mINotifyFd, event_buf, sizeof(event_buf));
1679 if(res < (int)sizeof(*event)) {
1680 if(errno == EINTR)
1681 return 0;
1682 ALOGW("could not get event, %s\n", strerror(errno));
1683 return -1;
1684 }
1685 //printf("got %d bytes of event information\n", res);
1686
1687 strcpy(devname, DEVICE_PATH);
1688 filename = devname + strlen(devname);
1689 *filename++ = '/';
1690
1691 while(res >= (int)sizeof(*event)) {
1692 event = (struct inotify_event *)(event_buf + event_pos);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001693 if(event->len) {
1694 strcpy(filename, event->name);
1695 if(event->mask & IN_CREATE) {
1696 openDeviceLocked(devname);
1697 } else {
1698 ALOGI("Removing device '%s' due to inotify event\n", devname);
1699 closeDeviceByPathLocked(devname);
1700 }
1701 }
1702 event_size = sizeof(*event) + event->len;
1703 res -= event_size;
1704 event_pos += event_size;
1705 }
1706 return 0;
1707}
1708
1709status_t EventHub::scanDirLocked(const char *dirname)
1710{
1711 char devname[PATH_MAX];
1712 char *filename;
1713 DIR *dir;
1714 struct dirent *de;
1715 dir = opendir(dirname);
Yi Kong9b14ac62018-07-17 13:48:38 -07001716 if(dir == nullptr)
Michael Wrightd02c5b62014-02-10 15:10:22 -08001717 return -1;
1718 strcpy(devname, dirname);
1719 filename = devname + strlen(devname);
1720 *filename++ = '/';
1721 while((de = readdir(dir))) {
1722 if(de->d_name[0] == '.' &&
1723 (de->d_name[1] == '\0' ||
1724 (de->d_name[1] == '.' && de->d_name[2] == '\0')))
1725 continue;
1726 strcpy(filename, de->d_name);
1727 openDeviceLocked(devname);
1728 }
1729 closedir(dir);
1730 return 0;
1731}
1732
1733void EventHub::requestReopenDevices() {
1734 ALOGV("requestReopenDevices() called");
1735
1736 AutoMutex _l(mLock);
1737 mNeedToReopenDevices = true;
1738}
1739
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001740void EventHub::dump(std::string& dump) {
1741 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001742
1743 { // acquire lock
1744 AutoMutex _l(mLock);
1745
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001746 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001747
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001748 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001749
1750 for (size_t i = 0; i < mDevices.size(); i++) {
1751 const Device* device = mDevices.valueAt(i);
1752 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001753 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001754 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001755 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001756 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001757 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001758 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001759 dump += StringPrintf(INDENT3 "Classes: 0x%08x\n", device->classes);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001760 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001761 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001762 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
1763 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001764 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001765 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001766 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08001767 "product=0x%04x, version=0x%04x\n",
1768 device->identifier.bus, device->identifier.vendor,
1769 device->identifier.product, device->identifier.version);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001770 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001771 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001772 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001773 device->keyMap.keyCharacterMapFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001774 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001775 device->configurationFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001776 dump += StringPrintf(INDENT3 "HaveKeyboardLayoutOverlay: %s\n",
Yi Kong9b14ac62018-07-17 13:48:38 -07001777 toString(device->overlayKeyMap != nullptr));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001778 }
1779 } // release lock
1780}
1781
1782void EventHub::monitor() {
1783 // Acquire and release the lock to ensure that the event hub has not deadlocked.
1784 mLock.lock();
1785 mLock.unlock();
1786}
1787
1788
1789}; // namespace android