blob: 1a1dabbb1586e7d23b06aa02f2ee9632f982e950 [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
72static const char *WAKE_LOCK_ID = "KeyEvents";
73static const char *DEVICE_PATH = "/dev/input";
74
Michael Wrightd02c5b62014-02-10 15:10:22 -080075static inline const char* toString(bool value) {
76 return value ? "true" : "false";
77}
78
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010079static std::string sha1(const std::string& in) {
Dan Albert677d87e2014-06-16 17:31:28 -070080 SHA_CTX ctx;
81 SHA1_Init(&ctx);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010082 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
Dan Albert677d87e2014-06-16 17:31:28 -070083 u_char digest[SHA_DIGEST_LENGTH];
84 SHA1_Final(digest, &ctx);
Michael Wrightd02c5b62014-02-10 15:10:22 -080085
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010086 std::string out;
Dan Albert677d87e2014-06-16 17:31:28 -070087 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010088 out += StringPrintf("%02x", digest[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -080089 }
90 return out;
91}
92
93static void getLinuxRelease(int* major, int* minor) {
94 struct utsname info;
95 if (uname(&info) || sscanf(info.release, "%d.%d", major, minor) <= 0) {
96 *major = 0, *minor = 0;
97 ALOGE("Could not get linux version: %s", strerror(errno));
98 }
99}
100
101// --- Global Functions ---
102
103uint32_t getAbsAxisUsage(int32_t axis, uint32_t deviceClasses) {
104 // Touch devices get dibs on touch-related axes.
105 if (deviceClasses & INPUT_DEVICE_CLASS_TOUCH) {
106 switch (axis) {
107 case ABS_X:
108 case ABS_Y:
109 case ABS_PRESSURE:
110 case ABS_TOOL_WIDTH:
111 case ABS_DISTANCE:
112 case ABS_TILT_X:
113 case ABS_TILT_Y:
114 case ABS_MT_SLOT:
115 case ABS_MT_TOUCH_MAJOR:
116 case ABS_MT_TOUCH_MINOR:
117 case ABS_MT_WIDTH_MAJOR:
118 case ABS_MT_WIDTH_MINOR:
119 case ABS_MT_ORIENTATION:
120 case ABS_MT_POSITION_X:
121 case ABS_MT_POSITION_Y:
122 case ABS_MT_TOOL_TYPE:
123 case ABS_MT_BLOB_ID:
124 case ABS_MT_TRACKING_ID:
125 case ABS_MT_PRESSURE:
126 case ABS_MT_DISTANCE:
127 return INPUT_DEVICE_CLASS_TOUCH;
128 }
129 }
130
Michael Wright842500e2015-03-13 17:32:02 -0700131 // External stylus gets the pressure axis
132 if (deviceClasses & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
133 if (axis == ABS_PRESSURE) {
134 return INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
135 }
136 }
137
Michael Wrightd02c5b62014-02-10 15:10:22 -0800138 // Joystick devices get the rest.
139 return deviceClasses & INPUT_DEVICE_CLASS_JOYSTICK;
140}
141
142// --- EventHub::Device ---
143
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100144EventHub::Device::Device(int fd, int32_t id, const std::string& path,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800145 const InputDeviceIdentifier& identifier) :
Yi Kong9b14ac62018-07-17 13:48:38 -0700146 next(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800147 fd(fd), id(id), path(path), identifier(identifier),
Yi Kong9b14ac62018-07-17 13:48:38 -0700148 classes(0), configuration(nullptr), virtualKeyMap(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800149 ffEffectPlaying(false), ffEffectId(-1), controllerNumber(0),
Siarhei Vishniakou88786812018-11-09 15:36:21 -0800150 enabled(true), isVirtual(fd < 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800151 memset(keyBitmask, 0, sizeof(keyBitmask));
152 memset(absBitmask, 0, sizeof(absBitmask));
153 memset(relBitmask, 0, sizeof(relBitmask));
154 memset(swBitmask, 0, sizeof(swBitmask));
155 memset(ledBitmask, 0, sizeof(ledBitmask));
156 memset(ffBitmask, 0, sizeof(ffBitmask));
157 memset(propBitmask, 0, sizeof(propBitmask));
158}
159
160EventHub::Device::~Device() {
161 close();
162 delete configuration;
163 delete virtualKeyMap;
164}
165
166void EventHub::Device::close() {
167 if (fd >= 0) {
168 ::close(fd);
169 fd = -1;
170 }
171}
172
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700173status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100174 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700175 if(fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100176 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700177 return -errno;
178 }
179 enabled = true;
180 return OK;
181}
182
183status_t EventHub::Device::disable() {
184 close();
185 enabled = false;
186 return OK;
187}
188
189bool EventHub::Device::hasValidFd() {
190 return !isVirtual && enabled;
191}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800192
193// --- EventHub ---
194
195const uint32_t EventHub::EPOLL_ID_INOTIFY;
196const uint32_t EventHub::EPOLL_ID_WAKE;
197const 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
208 mEpollFd = epoll_create(EPOLL_SIZE_HINT);
209 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;
219 eventItem.data.u32 = EPOLL_ID_INOTIFY;
220 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
238 eventItem.data.u32 = EPOLL_ID_WAKE;
239 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
737size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
738 ALOG_ASSERT(bufferSize >= 1);
739
740 AutoMutex _l(mLock);
741
742 struct input_event readBuffer[bufferSize];
743
744 RawEvent* event = buffer;
745 size_t capacity = bufferSize;
746 bool awoken = false;
747 for (;;) {
748 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
749
750 // Reopen input devices if needed.
751 if (mNeedToReopenDevices) {
752 mNeedToReopenDevices = false;
753
754 ALOGI("Reopening all input devices due to a configuration change.");
755
756 closeAllDevicesLocked();
757 mNeedToScanDevices = true;
758 break; // return to the caller before we actually rescan
759 }
760
761 // Report any devices that had last been added/removed.
762 while (mClosingDevices) {
763 Device* device = mClosingDevices;
764 ALOGV("Reporting device closed: id=%d, name=%s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100765 device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800766 mClosingDevices = device->next;
767 event->when = now;
768 event->deviceId = device->id == mBuiltInKeyboardId ? BUILT_IN_KEYBOARD_ID : device->id;
769 event->type = DEVICE_REMOVED;
770 event += 1;
771 delete device;
772 mNeedToSendFinishedDeviceScan = true;
773 if (--capacity == 0) {
774 break;
775 }
776 }
777
778 if (mNeedToScanDevices) {
779 mNeedToScanDevices = false;
780 scanDevicesLocked();
781 mNeedToSendFinishedDeviceScan = true;
782 }
783
Yi Kong9b14ac62018-07-17 13:48:38 -0700784 while (mOpeningDevices != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800785 Device* device = mOpeningDevices;
786 ALOGV("Reporting device opened: 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 mOpeningDevices = device->next;
789 event->when = now;
790 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
791 event->type = DEVICE_ADDED;
792 event += 1;
793 mNeedToSendFinishedDeviceScan = true;
794 if (--capacity == 0) {
795 break;
796 }
797 }
798
799 if (mNeedToSendFinishedDeviceScan) {
800 mNeedToSendFinishedDeviceScan = false;
801 event->when = now;
802 event->type = FINISHED_DEVICE_SCAN;
803 event += 1;
804 if (--capacity == 0) {
805 break;
806 }
807 }
808
809 // Grab the next input event.
810 bool deviceChanged = false;
811 while (mPendingEventIndex < mPendingEventCount) {
812 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
813 if (eventItem.data.u32 == EPOLL_ID_INOTIFY) {
814 if (eventItem.events & EPOLLIN) {
815 mPendingINotify = true;
816 } else {
817 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
818 }
819 continue;
820 }
821
822 if (eventItem.data.u32 == EPOLL_ID_WAKE) {
823 if (eventItem.events & EPOLLIN) {
824 ALOGV("awoken after wake()");
825 awoken = true;
826 char buffer[16];
827 ssize_t nRead;
828 do {
829 nRead = read(mWakeReadPipeFd, buffer, sizeof(buffer));
830 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(buffer));
831 } else {
832 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
833 eventItem.events);
834 }
835 continue;
836 }
837
838 ssize_t deviceIndex = mDevices.indexOfKey(eventItem.data.u32);
839 if (deviceIndex < 0) {
840 ALOGW("Received unexpected epoll event 0x%08x for unknown device id %d.",
841 eventItem.events, eventItem.data.u32);
842 continue;
843 }
844
845 Device* device = mDevices.valueAt(deviceIndex);
846 if (eventItem.events & EPOLLIN) {
847 int32_t readSize = read(device->fd, readBuffer,
848 sizeof(struct input_event) * capacity);
849 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
850 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -0700851 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
852 " bufferSize: %zu capacity: %zu errno: %d)\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800853 device->fd, readSize, bufferSize, capacity, errno);
854 deviceChanged = true;
855 closeDeviceLocked(device);
856 } else if (readSize < 0) {
857 if (errno != EAGAIN && errno != EINTR) {
858 ALOGW("could not get event (errno=%d)", errno);
859 }
860 } else if ((readSize % sizeof(struct input_event)) != 0) {
861 ALOGE("could not get event (wrong size: %d)", readSize);
862 } else {
863 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
864
865 size_t count = size_t(readSize) / sizeof(struct input_event);
866 for (size_t i = 0; i < count; i++) {
867 struct input_event& iev = readBuffer[i];
868 ALOGV("%s got: time=%d.%06d, type=%d, code=%d, value=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100869 device->path.c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800870 (int) iev.time.tv_sec, (int) iev.time.tv_usec,
871 iev.type, iev.code, iev.value);
872
Michael Wrightd02c5b62014-02-10 15:10:22 -0800873 // Use the time specified in the event instead of the current time
874 // so that downstream code can get more accurate estimates of
875 // event dispatch latency from the time the event is enqueued onto
876 // the evdev client buffer.
877 //
878 // The event's timestamp fortuitously uses the same monotonic clock
879 // time base as the rest of Android. The kernel event device driver
880 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
881 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
882 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
883 // system call that also queries ktime_get_ts().
884 event->when = nsecs_t(iev.time.tv_sec) * 1000000000LL
885 + nsecs_t(iev.time.tv_usec) * 1000LL;
Mark Salyzyn5aa26b22014-06-10 13:07:44 -0700886 ALOGV("event time %" PRId64 ", now %" PRId64, event->when, now);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800887
888 // Bug 7291243: Add a guard in case the kernel generates timestamps
889 // that appear to be far into the future because they were generated
890 // using the wrong clock source.
891 //
892 // This can happen because when the input device is initially opened
893 // it has a default clock source of CLOCK_REALTIME. Any input events
894 // enqueued right after the device is opened will have timestamps
895 // generated using CLOCK_REALTIME. We later set the clock source
896 // to CLOCK_MONOTONIC but it is already too late.
897 //
898 // Invalid input event timestamps can result in ANRs, crashes and
899 // and other issues that are hard to track down. We must not let them
900 // propagate through the system.
901 //
902 // Log a warning so that we notice the problem and recover gracefully.
903 if (event->when >= now + 10 * 1000000000LL) {
904 // Double-check. Time may have moved on.
905 nsecs_t time = systemTime(SYSTEM_TIME_MONOTONIC);
906 if (event->when > time) {
907 ALOGW("An input event from %s has a timestamp that appears to "
908 "have been generated using the wrong clock source "
909 "(expected CLOCK_MONOTONIC): "
Mark Salyzyn5aa26b22014-06-10 13:07:44 -0700910 "event time %" PRId64 ", current time %" PRId64
911 ", call time %" PRId64 ". "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800912 "Using current time instead.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100913 device->path.c_str(), event->when, time, now);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800914 event->when = time;
915 } else {
916 ALOGV("Event time is ok but failed the fast path and required "
917 "an extra call to systemTime: "
Mark Salyzyn5aa26b22014-06-10 13:07:44 -0700918 "event time %" PRId64 ", current time %" PRId64
919 ", call time %" PRId64 ".",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800920 event->when, time, now);
921 }
922 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800923 event->deviceId = deviceId;
924 event->type = iev.type;
925 event->code = iev.code;
926 event->value = iev.value;
927 event += 1;
928 capacity -= 1;
929 }
930 if (capacity == 0) {
931 // The result buffer is full. Reset the pending event index
932 // so we will try to read the device again on the next iteration.
933 mPendingEventIndex -= 1;
934 break;
935 }
936 }
937 } else if (eventItem.events & EPOLLHUP) {
938 ALOGI("Removing device %s due to epoll hang-up event.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100939 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800940 deviceChanged = true;
941 closeDeviceLocked(device);
942 } else {
943 ALOGW("Received unexpected epoll event 0x%08x for device %s.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100944 eventItem.events, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800945 }
946 }
947
948 // readNotify() will modify the list of devices so this must be done after
949 // processing all other events to ensure that we read all remaining events
950 // before closing the devices.
951 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
952 mPendingINotify = false;
953 readNotifyLocked();
954 deviceChanged = true;
955 }
956
957 // Report added or removed devices immediately.
958 if (deviceChanged) {
959 continue;
960 }
961
962 // Return now if we have collected any events or if we were explicitly awoken.
963 if (event != buffer || awoken) {
964 break;
965 }
966
967 // Poll for events. Mind the wake lock dance!
968 // We hold a wake lock at all times except during epoll_wait(). This works due to some
969 // subtle choreography. When a device driver has pending (unread) events, it acquires
970 // a kernel wake lock. However, once the last pending event has been read, the device
971 // driver will release the kernel wake lock. To prevent the system from going to sleep
972 // when this happens, the EventHub holds onto its own user wake lock while the client
973 // is processing events. Thus the system can only sleep if there are no events
974 // pending or currently being processed.
975 //
976 // The timeout is advisory only. If the device is asleep, it will not wake just to
977 // service the timeout.
978 mPendingEventIndex = 0;
979
980 mLock.unlock(); // release lock before poll, must be before release_wake_lock
981 release_wake_lock(WAKE_LOCK_ID);
982
983 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
984
985 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
986 mLock.lock(); // reacquire lock after poll, must be after acquire_wake_lock
987
988 if (pollResult == 0) {
989 // Timed out.
990 mPendingEventCount = 0;
991 break;
992 }
993
994 if (pollResult < 0) {
995 // An error occurred.
996 mPendingEventCount = 0;
997
998 // Sleep after errors to avoid locking up the system.
999 // Hopefully the error is transient.
1000 if (errno != EINTR) {
1001 ALOGW("poll failed (errno=%d)\n", errno);
1002 usleep(100000);
1003 }
1004 } else {
1005 // Some events occurred.
1006 mPendingEventCount = size_t(pollResult);
1007 }
1008 }
1009
1010 // All done, return the number of events we read.
1011 return event - buffer;
1012}
1013
1014void EventHub::wake() {
1015 ALOGV("wake() called");
1016
1017 ssize_t nWrite;
1018 do {
1019 nWrite = write(mWakeWritePipeFd, "W", 1);
1020 } while (nWrite == -1 && errno == EINTR);
1021
1022 if (nWrite != 1 && errno != EAGAIN) {
1023 ALOGW("Could not write wake signal, errno=%d", errno);
1024 }
1025}
1026
1027void EventHub::scanDevicesLocked() {
1028 status_t res = scanDirLocked(DEVICE_PATH);
1029 if(res < 0) {
1030 ALOGE("scan dir failed for %s\n", DEVICE_PATH);
1031 }
1032 if (mDevices.indexOfKey(VIRTUAL_KEYBOARD_ID) < 0) {
1033 createVirtualKeyboardLocked();
1034 }
1035}
1036
1037// ----------------------------------------------------------------------------
1038
1039static bool containsNonZeroByte(const uint8_t* array, uint32_t startIndex, uint32_t endIndex) {
1040 const uint8_t* end = array + endIndex;
1041 array += startIndex;
1042 while (array != end) {
1043 if (*(array++) != 0) {
1044 return true;
1045 }
1046 }
1047 return false;
1048}
1049
1050static const int32_t GAMEPAD_KEYCODES[] = {
1051 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C,
1052 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z,
1053 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1,
1054 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2,
1055 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR,
1056 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001057};
1058
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001059status_t EventHub::registerDeviceForEpollLocked(Device* device) {
1060 struct epoll_event eventItem;
1061 memset(&eventItem, 0, sizeof(eventItem));
1062 eventItem.events = EPOLLIN;
1063 if (mUsingEpollWakeup) {
1064 eventItem.events |= EPOLLWAKEUP;
1065 }
1066 eventItem.data.u32 = device->id;
1067 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, device->fd, &eventItem)) {
1068 ALOGE("Could not add device fd to epoll instance. errno=%d", errno);
1069 return -errno;
1070 }
1071 return OK;
1072}
1073
1074status_t EventHub::unregisterDeviceFromEpollLocked(Device* device) {
1075 if (device->hasValidFd()) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001076 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, device->fd, nullptr)) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001077 ALOGW("Could not remove device fd from epoll instance. errno=%d", errno);
1078 return -errno;
1079 }
1080 }
1081 return OK;
1082}
1083
Michael Wrightd02c5b62014-02-10 15:10:22 -08001084status_t EventHub::openDeviceLocked(const char *devicePath) {
1085 char buffer[80];
1086
1087 ALOGV("Opening device: %s", devicePath);
1088
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001089 int fd = open(devicePath, O_RDWR | O_CLOEXEC | O_NONBLOCK);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001090 if(fd < 0) {
1091 ALOGE("could not open %s, %s\n", devicePath, strerror(errno));
1092 return -1;
1093 }
1094
1095 InputDeviceIdentifier identifier;
1096
1097 // Get device name.
1098 if(ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
1099 //fprintf(stderr, "could not get device name for %s, %s\n", devicePath, strerror(errno));
1100 } else {
1101 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001102 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001103 }
1104
1105 // Check to see if the device is on our excluded list
1106 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001107 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001108 if (identifier.name == item) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001109 ALOGI("ignoring event id %s driver %s\n", devicePath, item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001110 close(fd);
1111 return -1;
1112 }
1113 }
1114
1115 // Get device driver version.
1116 int driverVersion;
1117 if(ioctl(fd, EVIOCGVERSION, &driverVersion)) {
1118 ALOGE("could not get driver version for %s, %s\n", devicePath, strerror(errno));
1119 close(fd);
1120 return -1;
1121 }
1122
1123 // Get device identifier.
1124 struct input_id inputId;
1125 if(ioctl(fd, EVIOCGID, &inputId)) {
1126 ALOGE("could not get device input id for %s, %s\n", devicePath, strerror(errno));
1127 close(fd);
1128 return -1;
1129 }
1130 identifier.bus = inputId.bustype;
1131 identifier.product = inputId.product;
1132 identifier.vendor = inputId.vendor;
1133 identifier.version = inputId.version;
1134
1135 // Get device physical location.
1136 if(ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
1137 //fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
1138 } else {
1139 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001140 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001141 }
1142
1143 // Get device unique id.
1144 if(ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
1145 //fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
1146 } else {
1147 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001148 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001149 }
1150
1151 // Fill in the descriptor.
1152 assignDescriptorLocked(identifier);
1153
Michael Wrightd02c5b62014-02-10 15:10:22 -08001154 // Allocate device. (The device object takes ownership of the fd at this point.)
1155 int32_t deviceId = mNextDeviceId++;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001156 Device* device = new Device(fd, deviceId, devicePath, identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001157
1158 ALOGV("add device %d: %s\n", deviceId, devicePath);
1159 ALOGV(" bus: %04x\n"
1160 " vendor %04x\n"
1161 " product %04x\n"
1162 " version %04x\n",
1163 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001164 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
1165 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
1166 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
1167 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001168 ALOGV(" driver: v%d.%d.%d\n",
1169 driverVersion >> 16, (driverVersion >> 8) & 0xff, driverVersion & 0xff);
1170
1171 // Load the configuration file for the device.
1172 loadConfigurationLocked(device);
1173
1174 // Figure out the kinds of events the device reports.
1175 ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(device->keyBitmask)), device->keyBitmask);
1176 ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(device->absBitmask)), device->absBitmask);
1177 ioctl(fd, EVIOCGBIT(EV_REL, sizeof(device->relBitmask)), device->relBitmask);
1178 ioctl(fd, EVIOCGBIT(EV_SW, sizeof(device->swBitmask)), device->swBitmask);
1179 ioctl(fd, EVIOCGBIT(EV_LED, sizeof(device->ledBitmask)), device->ledBitmask);
1180 ioctl(fd, EVIOCGBIT(EV_FF, sizeof(device->ffBitmask)), device->ffBitmask);
1181 ioctl(fd, EVIOCGPROP(sizeof(device->propBitmask)), device->propBitmask);
1182
1183 // See if this is a keyboard. Ignore everything in the button range except for
1184 // joystick and gamepad buttons which are handled like keyboards for the most part.
1185 bool haveKeyboardKeys = containsNonZeroByte(device->keyBitmask, 0, sizeof_bit_array(BTN_MISC))
1186 || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(KEY_OK),
1187 sizeof_bit_array(KEY_MAX + 1));
1188 bool haveGamepadButtons = containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_MISC),
1189 sizeof_bit_array(BTN_MOUSE))
1190 || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_JOYSTICK),
1191 sizeof_bit_array(BTN_DIGI));
1192 if (haveKeyboardKeys || haveGamepadButtons) {
1193 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1194 }
1195
1196 // See if this is a cursor device such as a trackball or mouse.
1197 if (test_bit(BTN_MOUSE, device->keyBitmask)
1198 && test_bit(REL_X, device->relBitmask)
1199 && test_bit(REL_Y, device->relBitmask)) {
1200 device->classes |= INPUT_DEVICE_CLASS_CURSOR;
1201 }
1202
Prashant Malani1941ff52015-08-11 18:29:28 -07001203 // See if this is a rotary encoder type device.
1204 String8 deviceType = String8();
1205 if (device->configuration &&
1206 device->configuration->tryGetProperty(String8("device.type"), deviceType)) {
1207 if (!deviceType.compare(String8("rotaryEncoder"))) {
1208 device->classes |= INPUT_DEVICE_CLASS_ROTARY_ENCODER;
1209 }
1210 }
1211
Michael Wrightd02c5b62014-02-10 15:10:22 -08001212 // See if this is a touch pad.
1213 // Is this a new modern multi-touch driver?
1214 if (test_bit(ABS_MT_POSITION_X, device->absBitmask)
1215 && test_bit(ABS_MT_POSITION_Y, device->absBitmask)) {
1216 // Some joysticks such as the PS3 controller report axes that conflict
1217 // with the ABS_MT range. Try to confirm that the device really is
1218 // a touch screen.
1219 if (test_bit(BTN_TOUCH, device->keyBitmask) || !haveGamepadButtons) {
1220 device->classes |= INPUT_DEVICE_CLASS_TOUCH | INPUT_DEVICE_CLASS_TOUCH_MT;
1221 }
1222 // Is this an old style single-touch driver?
1223 } else if (test_bit(BTN_TOUCH, device->keyBitmask)
1224 && test_bit(ABS_X, device->absBitmask)
1225 && test_bit(ABS_Y, device->absBitmask)) {
1226 device->classes |= INPUT_DEVICE_CLASS_TOUCH;
Michael Wright842500e2015-03-13 17:32:02 -07001227 // Is this a BT stylus?
1228 } else if ((test_bit(ABS_PRESSURE, device->absBitmask) ||
1229 test_bit(BTN_TOUCH, device->keyBitmask))
1230 && !test_bit(ABS_X, device->absBitmask)
1231 && !test_bit(ABS_Y, device->absBitmask)) {
1232 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
1233 // Keyboard will try to claim some of the buttons but we really want to reserve those so we
1234 // can fuse it with the touch screen data, so just take them back. Note this means an
1235 // external stylus cannot also be a keyboard device.
1236 device->classes &= ~INPUT_DEVICE_CLASS_KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237 }
1238
1239 // See if this device is a joystick.
1240 // Assumes that joysticks always have gamepad buttons in order to distinguish them
1241 // from other devices such as accelerometers that also have absolute axes.
1242 if (haveGamepadButtons) {
1243 uint32_t assumedClasses = device->classes | INPUT_DEVICE_CLASS_JOYSTICK;
1244 for (int i = 0; i <= ABS_MAX; i++) {
1245 if (test_bit(i, device->absBitmask)
1246 && (getAbsAxisUsage(i, assumedClasses) & INPUT_DEVICE_CLASS_JOYSTICK)) {
1247 device->classes = assumedClasses;
1248 break;
1249 }
1250 }
1251 }
1252
1253 // Check whether this device has switches.
1254 for (int i = 0; i <= SW_MAX; i++) {
1255 if (test_bit(i, device->swBitmask)) {
1256 device->classes |= INPUT_DEVICE_CLASS_SWITCH;
1257 break;
1258 }
1259 }
1260
1261 // Check whether this device supports the vibrator.
1262 if (test_bit(FF_RUMBLE, device->ffBitmask)) {
1263 device->classes |= INPUT_DEVICE_CLASS_VIBRATOR;
1264 }
1265
1266 // Configure virtual keys.
1267 if ((device->classes & INPUT_DEVICE_CLASS_TOUCH)) {
1268 // Load the virtual keys for the touch screen, if any.
1269 // We do this now so that we can make sure to load the keymap if necessary.
1270 status_t status = loadVirtualKeyMapLocked(device);
1271 if (!status) {
1272 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1273 }
1274 }
1275
1276 // Load the key map.
1277 // We need to do this for joysticks too because the key layout may specify axes.
1278 status_t keyMapStatus = NAME_NOT_FOUND;
1279 if (device->classes & (INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_JOYSTICK)) {
1280 // Load the keymap for the device.
1281 keyMapStatus = loadKeyMapLocked(device);
1282 }
1283
1284 // Configure the keyboard, gamepad or virtual keyboard.
1285 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1286 // Register the keyboard as a built-in keyboard if it is eligible.
1287 if (!keyMapStatus
1288 && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD
1289 && isEligibleBuiltInKeyboard(device->identifier,
1290 device->configuration, &device->keyMap)) {
1291 mBuiltInKeyboardId = device->id;
1292 }
1293
1294 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
1295 if (hasKeycodeLocked(device, AKEYCODE_Q)) {
1296 device->classes |= INPUT_DEVICE_CLASS_ALPHAKEY;
1297 }
1298
1299 // See if this device has a DPAD.
1300 if (hasKeycodeLocked(device, AKEYCODE_DPAD_UP) &&
1301 hasKeycodeLocked(device, AKEYCODE_DPAD_DOWN) &&
1302 hasKeycodeLocked(device, AKEYCODE_DPAD_LEFT) &&
1303 hasKeycodeLocked(device, AKEYCODE_DPAD_RIGHT) &&
1304 hasKeycodeLocked(device, AKEYCODE_DPAD_CENTER)) {
1305 device->classes |= INPUT_DEVICE_CLASS_DPAD;
1306 }
1307
1308 // See if this device has a gamepad.
1309 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES)/sizeof(GAMEPAD_KEYCODES[0]); i++) {
1310 if (hasKeycodeLocked(device, GAMEPAD_KEYCODES[i])) {
1311 device->classes |= INPUT_DEVICE_CLASS_GAMEPAD;
1312 break;
1313 }
1314 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001315 }
1316
1317 // If the device isn't recognized as something we handle, don't monitor it.
1318 if (device->classes == 0) {
1319 ALOGV("Dropping device: id=%d, path='%s', name='%s'",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001320 deviceId, devicePath, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001321 delete device;
1322 return -1;
1323 }
1324
Tim Kilbourn063ff532015-04-08 10:26:18 -07001325 // Determine whether the device has a mic.
1326 if (deviceHasMicLocked(device)) {
1327 device->classes |= INPUT_DEVICE_CLASS_MIC;
1328 }
1329
Michael Wrightd02c5b62014-02-10 15:10:22 -08001330 // Determine whether the device is external or internal.
1331 if (isExternalDeviceLocked(device)) {
1332 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL;
1333 }
1334
Michael Wright42f2c6a2014-03-12 10:33:03 -07001335 if (device->classes & (INPUT_DEVICE_CLASS_JOYSTICK | INPUT_DEVICE_CLASS_DPAD)
1336 && device->classes & INPUT_DEVICE_CLASS_GAMEPAD) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001337 device->controllerNumber = getNextControllerNumberLocked(device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001338 setLedForControllerLocked(device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001339 }
1340
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001341
1342 if (registerDeviceForEpollLocked(device) != OK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001343 delete device;
1344 return -1;
1345 }
1346
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001347 configureFd(device);
1348
1349 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=0x%x, "
1350 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001351 deviceId, fd, devicePath, device->identifier.name.c_str(),
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001352 device->classes,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001353 device->configurationFile.c_str(),
1354 device->keyMap.keyLayoutFile.c_str(),
1355 device->keyMap.keyCharacterMapFile.c_str(),
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001356 toString(mBuiltInKeyboardId == deviceId));
1357
1358 addDeviceLocked(device);
1359 return OK;
1360}
1361
1362void EventHub::configureFd(Device* device) {
1363 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
1364 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1365 // Disable kernel key repeat since we handle it ourselves
1366 unsigned int repeatRate[] = {0, 0};
1367 if (ioctl(device->fd, EVIOCSREP, repeatRate)) {
1368 ALOGW("Unable to disable kernel key repeat for %s: %s",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001369 device->path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001370 }
1371 }
1372
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001373 std::string wakeMechanism = "EPOLLWAKEUP";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001374 if (!mUsingEpollWakeup) {
1375#ifndef EVIOCSSUSPENDBLOCK
1376 // uapi headers don't include EVIOCSSUSPENDBLOCK, and future kernels
1377 // will use an epoll flag instead, so as long as we want to support
1378 // this feature, we need to be prepared to define the ioctl ourselves.
1379#define EVIOCSSUSPENDBLOCK _IOW('E', 0x91, int)
1380#endif
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001381 if (ioctl(device->fd, EVIOCSSUSPENDBLOCK, 1)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001382 wakeMechanism = "<none>";
1383 } else {
1384 wakeMechanism = "EVIOCSSUSPENDBLOCK";
1385 }
1386 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001387 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
1388 // associated with input events. This is important because the input system
1389 // uses the timestamps extensively and assumes they were recorded using the monotonic
1390 // clock.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001391 int clockId = CLOCK_MONOTONIC;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001392 bool usingClockIoctl = !ioctl(device->fd, EVIOCSCLOCKID, &clockId);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001393 ALOGI("wakeMechanism=%s, usingClockIoctl=%s", wakeMechanism.c_str(),
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001394 toString(usingClockIoctl));
1395}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001396
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001397bool EventHub::isDeviceEnabled(int32_t deviceId) {
1398 AutoMutex _l(mLock);
1399 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001400 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001401 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1402 return false;
1403 }
1404 return device->enabled;
1405}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001406
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001407status_t EventHub::enableDevice(int32_t deviceId) {
1408 AutoMutex _l(mLock);
1409 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001410 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001411 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1412 return BAD_VALUE;
1413 }
1414 if (device->enabled) {
1415 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
1416 return OK;
1417 }
1418 status_t result = device->enable();
1419 if (result != OK) {
1420 ALOGE("Failed to enable device %" PRId32, deviceId);
1421 return result;
1422 }
1423
1424 configureFd(device);
1425
1426 return registerDeviceForEpollLocked(device);
1427}
1428
1429status_t EventHub::disableDevice(int32_t deviceId) {
1430 AutoMutex _l(mLock);
1431 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001432 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001433 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1434 return BAD_VALUE;
1435 }
1436 if (!device->enabled) {
1437 ALOGW("Duplicate call to %s, input device already disabled", __func__);
1438 return OK;
1439 }
1440 unregisterDeviceFromEpollLocked(device);
1441 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001442}
1443
1444void EventHub::createVirtualKeyboardLocked() {
1445 InputDeviceIdentifier identifier;
1446 identifier.name = "Virtual";
1447 identifier.uniqueId = "<virtual>";
1448 assignDescriptorLocked(identifier);
1449
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001450 Device* device = new Device(-1, VIRTUAL_KEYBOARD_ID, "<virtual>", identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001451 device->classes = INPUT_DEVICE_CLASS_KEYBOARD
1452 | INPUT_DEVICE_CLASS_ALPHAKEY
1453 | INPUT_DEVICE_CLASS_DPAD
1454 | INPUT_DEVICE_CLASS_VIRTUAL;
1455 loadKeyMapLocked(device);
1456 addDeviceLocked(device);
1457}
1458
1459void EventHub::addDeviceLocked(Device* device) {
1460 mDevices.add(device->id, device);
1461 device->next = mOpeningDevices;
1462 mOpeningDevices = device;
1463}
1464
1465void EventHub::loadConfigurationLocked(Device* device) {
1466 device->configurationFile = getInputDeviceConfigurationFilePathByDeviceIdentifier(
1467 device->identifier, INPUT_DEVICE_CONFIGURATION_FILE_TYPE_CONFIGURATION);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001468 if (device->configurationFile.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001469 ALOGD("No input device configuration file found for device '%s'.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001470 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001471 } else {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001472 status_t status = PropertyMap::load(String8(device->configurationFile.c_str()),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001473 &device->configuration);
1474 if (status) {
1475 ALOGE("Error loading input device configuration file for device '%s'. "
1476 "Using default configuration.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001477 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001478 }
1479 }
1480}
1481
1482status_t EventHub::loadVirtualKeyMapLocked(Device* device) {
1483 // The virtual key map is supplied by the kernel as a system board property file.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001484 std::string path;
1485 path += "/sys/board_properties/virtualkeys.";
1486 path += device->identifier.name;
1487 if (access(path.c_str(), R_OK)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001488 return NAME_NOT_FOUND;
1489 }
1490 return VirtualKeyMap::load(path, &device->virtualKeyMap);
1491}
1492
1493status_t EventHub::loadKeyMapLocked(Device* device) {
1494 return device->keyMap.load(device->identifier, device->configuration);
1495}
1496
1497bool EventHub::isExternalDeviceLocked(Device* device) {
1498 if (device->configuration) {
1499 bool value;
1500 if (device->configuration->tryGetProperty(String8("device.internal"), value)) {
1501 return !value;
1502 }
1503 }
1504 return device->identifier.bus == BUS_USB || device->identifier.bus == BUS_BLUETOOTH;
1505}
1506
Tim Kilbourn063ff532015-04-08 10:26:18 -07001507bool EventHub::deviceHasMicLocked(Device* device) {
1508 if (device->configuration) {
1509 bool value;
1510 if (device->configuration->tryGetProperty(String8("audio.mic"), value)) {
1511 return value;
1512 }
1513 }
1514 return false;
1515}
1516
Michael Wrightd02c5b62014-02-10 15:10:22 -08001517int32_t EventHub::getNextControllerNumberLocked(Device* device) {
1518 if (mControllerNumbers.isFull()) {
1519 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001520 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001521 return 0;
1522 }
1523 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
1524 // one
1525 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
1526}
1527
1528void EventHub::releaseControllerNumberLocked(Device* device) {
1529 int32_t num = device->controllerNumber;
1530 device->controllerNumber= 0;
1531 if (num == 0) {
1532 return;
1533 }
1534 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
1535}
1536
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001537void EventHub::setLedForControllerLocked(Device* device) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001538 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
1539 setLedStateLocked(device, ALED_CONTROLLER_1 + i, device->controllerNumber == i + 1);
1540 }
1541}
1542
1543bool EventHub::hasKeycodeLocked(Device* device, int keycode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001544 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001545 return false;
1546 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001547
Michael Wrightd02c5b62014-02-10 15:10:22 -08001548 Vector<int32_t> scanCodes;
1549 device->keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes);
1550 const size_t N = scanCodes.size();
1551 for (size_t i=0; i<N && i<=KEY_MAX; i++) {
1552 int32_t sc = scanCodes.itemAt(i);
1553 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, device->keyBitmask)) {
1554 return true;
1555 }
1556 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001557
Michael Wrightd02c5b62014-02-10 15:10:22 -08001558 return false;
1559}
1560
1561status_t EventHub::mapLed(Device* device, int32_t led, int32_t* outScanCode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001562 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001563 return NAME_NOT_FOUND;
1564 }
1565
1566 int32_t scanCode;
1567 if(device->keyMap.keyLayoutMap->findScanCodeForLed(led, &scanCode) != NAME_NOT_FOUND) {
1568 if(scanCode >= 0 && scanCode <= LED_MAX && test_bit(scanCode, device->ledBitmask)) {
1569 *outScanCode = scanCode;
1570 return NO_ERROR;
1571 }
1572 }
1573 return NAME_NOT_FOUND;
1574}
1575
1576status_t EventHub::closeDeviceByPathLocked(const char *devicePath) {
1577 Device* device = getDeviceByPathLocked(devicePath);
1578 if (device) {
1579 closeDeviceLocked(device);
1580 return 0;
1581 }
1582 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath);
1583 return -1;
1584}
1585
1586void EventHub::closeAllDevicesLocked() {
1587 while (mDevices.size() > 0) {
1588 closeDeviceLocked(mDevices.valueAt(mDevices.size() - 1));
1589 }
1590}
1591
1592void EventHub::closeDeviceLocked(Device* device) {
1593 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=0x%x\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001594 device->path.c_str(), device->identifier.name.c_str(), device->id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001595 device->fd, device->classes);
1596
1597 if (device->id == mBuiltInKeyboardId) {
1598 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001599 device->path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001600 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
1601 }
1602
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001603 unregisterDeviceFromEpollLocked(device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001604
1605 releaseControllerNumberLocked(device);
1606
1607 mDevices.removeItem(device->id);
1608 device->close();
1609
1610 // Unlink for opening devices list if it is present.
Yi Kong9b14ac62018-07-17 13:48:38 -07001611 Device* pred = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001612 bool found = false;
Yi Kong9b14ac62018-07-17 13:48:38 -07001613 for (Device* entry = mOpeningDevices; entry != nullptr; ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001614 if (entry == device) {
1615 found = true;
1616 break;
1617 }
1618 pred = entry;
1619 entry = entry->next;
1620 }
1621 if (found) {
1622 // Unlink the device from the opening devices list then delete it.
1623 // We don't need to tell the client that the device was closed because
1624 // it does not even know it was opened in the first place.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001625 ALOGI("Device %s was immediately closed after opening.", device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001626 if (pred) {
1627 pred->next = device->next;
1628 } else {
1629 mOpeningDevices = device->next;
1630 }
1631 delete device;
1632 } else {
1633 // Link into closing devices list.
1634 // The device will be deleted later after we have informed the client.
1635 device->next = mClosingDevices;
1636 mClosingDevices = device;
1637 }
1638}
1639
1640status_t EventHub::readNotifyLocked() {
1641 int res;
1642 char devname[PATH_MAX];
1643 char *filename;
1644 char event_buf[512];
1645 int event_size;
1646 int event_pos = 0;
1647 struct inotify_event *event;
1648
1649 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
1650 res = read(mINotifyFd, event_buf, sizeof(event_buf));
1651 if(res < (int)sizeof(*event)) {
1652 if(errno == EINTR)
1653 return 0;
1654 ALOGW("could not get event, %s\n", strerror(errno));
1655 return -1;
1656 }
1657 //printf("got %d bytes of event information\n", res);
1658
1659 strcpy(devname, DEVICE_PATH);
1660 filename = devname + strlen(devname);
1661 *filename++ = '/';
1662
1663 while(res >= (int)sizeof(*event)) {
1664 event = (struct inotify_event *)(event_buf + event_pos);
1665 //printf("%d: %08x \"%s\"\n", event->wd, event->mask, event->len ? event->name : "");
1666 if(event->len) {
1667 strcpy(filename, event->name);
1668 if(event->mask & IN_CREATE) {
1669 openDeviceLocked(devname);
1670 } else {
1671 ALOGI("Removing device '%s' due to inotify event\n", devname);
1672 closeDeviceByPathLocked(devname);
1673 }
1674 }
1675 event_size = sizeof(*event) + event->len;
1676 res -= event_size;
1677 event_pos += event_size;
1678 }
1679 return 0;
1680}
1681
1682status_t EventHub::scanDirLocked(const char *dirname)
1683{
1684 char devname[PATH_MAX];
1685 char *filename;
1686 DIR *dir;
1687 struct dirent *de;
1688 dir = opendir(dirname);
Yi Kong9b14ac62018-07-17 13:48:38 -07001689 if(dir == nullptr)
Michael Wrightd02c5b62014-02-10 15:10:22 -08001690 return -1;
1691 strcpy(devname, dirname);
1692 filename = devname + strlen(devname);
1693 *filename++ = '/';
1694 while((de = readdir(dir))) {
1695 if(de->d_name[0] == '.' &&
1696 (de->d_name[1] == '\0' ||
1697 (de->d_name[1] == '.' && de->d_name[2] == '\0')))
1698 continue;
1699 strcpy(filename, de->d_name);
1700 openDeviceLocked(devname);
1701 }
1702 closedir(dir);
1703 return 0;
1704}
1705
1706void EventHub::requestReopenDevices() {
1707 ALOGV("requestReopenDevices() called");
1708
1709 AutoMutex _l(mLock);
1710 mNeedToReopenDevices = true;
1711}
1712
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001713void EventHub::dump(std::string& dump) {
1714 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001715
1716 { // acquire lock
1717 AutoMutex _l(mLock);
1718
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001719 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001720
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001721 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001722
1723 for (size_t i = 0; i < mDevices.size(); i++) {
1724 const Device* device = mDevices.valueAt(i);
1725 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001726 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001727 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001728 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001729 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001730 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001731 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001732 dump += StringPrintf(INDENT3 "Classes: 0x%08x\n", device->classes);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001733 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001734 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001735 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
1736 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001737 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001738 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001739 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08001740 "product=0x%04x, version=0x%04x\n",
1741 device->identifier.bus, device->identifier.vendor,
1742 device->identifier.product, device->identifier.version);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001743 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001744 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001745 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001746 device->keyMap.keyCharacterMapFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001747 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001748 device->configurationFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001749 dump += StringPrintf(INDENT3 "HaveKeyboardLayoutOverlay: %s\n",
Yi Kong9b14ac62018-07-17 13:48:38 -07001750 toString(device->overlayKeyMap != nullptr));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001751 }
1752 } // release lock
1753}
1754
1755void EventHub::monitor() {
1756 // Acquire and release the lock to ensure that the event hub has not deadlocked.
1757 mLock.lock();
1758 mLock.unlock();
1759}
1760
1761
1762}; // namespace android