blob: 5709e1e19f55ba96ab80b0a391d71ea90055e720 [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
Michael Wrightd02c5b62014-02-10 15:10:22 -0800195const int EventHub::EPOLL_SIZE_HINT;
196const int EventHub::EPOLL_MAX_EVENTS;
197
198EventHub::EventHub(void) :
199 mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD), mNextDeviceId(1), mControllerNumbers(),
Yi Kong9b14ac62018-07-17 13:48:38 -0700200 mOpeningDevices(nullptr), mClosingDevices(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800201 mNeedToSendFinishedDeviceScan(false),
202 mNeedToReopenDevices(false), mNeedToScanDevices(true),
203 mPendingEventCount(0), mPendingEventIndex(0), mPendingINotify(false) {
204 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
205
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800206 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800207 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance. errno=%d", errno);
208
209 mINotifyFd = inotify_init();
210 int result = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
211 LOG_ALWAYS_FATAL_IF(result < 0, "Could not register INotify for %s. errno=%d",
212 DEVICE_PATH, errno);
213
214 struct epoll_event eventItem;
215 memset(&eventItem, 0, sizeof(eventItem));
216 eventItem.events = EPOLLIN;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700217 eventItem.data.fd = mINotifyFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800218 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
219 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
220
221 int wakeFds[2];
222 result = pipe(wakeFds);
223 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
224
225 mWakeReadPipeFd = wakeFds[0];
226 mWakeWritePipeFd = wakeFds[1];
227
228 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
229 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
230 errno);
231
232 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
233 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
234 errno);
235
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700236 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800237 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
238 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
239 errno);
240
241 int major, minor;
242 getLinuxRelease(&major, &minor);
243 // EPOLLWAKEUP was introduced in kernel 3.5
244 mUsingEpollWakeup = major > 3 || (major == 3 && minor >= 5);
245}
246
247EventHub::~EventHub(void) {
248 closeAllDevicesLocked();
249
250 while (mClosingDevices) {
251 Device* device = mClosingDevices;
252 mClosingDevices = device->next;
253 delete device;
254 }
255
256 ::close(mEpollFd);
257 ::close(mINotifyFd);
258 ::close(mWakeReadPipeFd);
259 ::close(mWakeWritePipeFd);
260
261 release_wake_lock(WAKE_LOCK_ID);
262}
263
264InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
265 AutoMutex _l(mLock);
266 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700267 if (device == nullptr) return InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800268 return device->identifier;
269}
270
271uint32_t EventHub::getDeviceClasses(int32_t deviceId) const {
272 AutoMutex _l(mLock);
273 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700274 if (device == nullptr) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800275 return device->classes;
276}
277
278int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
279 AutoMutex _l(mLock);
280 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700281 if (device == nullptr) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800282 return device->controllerNumber;
283}
284
285void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
286 AutoMutex _l(mLock);
287 Device* device = getDeviceLocked(deviceId);
288 if (device && device->configuration) {
289 *outConfiguration = *device->configuration;
290 } else {
291 outConfiguration->clear();
292 }
293}
294
295status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
296 RawAbsoluteAxisInfo* outAxisInfo) const {
297 outAxisInfo->clear();
298
299 if (axis >= 0 && axis <= ABS_MAX) {
300 AutoMutex _l(mLock);
301
302 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700303 if (device && device->hasValidFd() && test_bit(axis, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800304 struct input_absinfo info;
305 if(ioctl(device->fd, EVIOCGABS(axis), &info)) {
306 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100307 axis, device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800308 return -errno;
309 }
310
311 if (info.minimum != info.maximum) {
312 outAxisInfo->valid = true;
313 outAxisInfo->minValue = info.minimum;
314 outAxisInfo->maxValue = info.maximum;
315 outAxisInfo->flat = info.flat;
316 outAxisInfo->fuzz = info.fuzz;
317 outAxisInfo->resolution = info.resolution;
318 }
319 return OK;
320 }
321 }
322 return -1;
323}
324
325bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
326 if (axis >= 0 && axis <= REL_MAX) {
327 AutoMutex _l(mLock);
328
329 Device* device = getDeviceLocked(deviceId);
330 if (device) {
331 return test_bit(axis, device->relBitmask);
332 }
333 }
334 return false;
335}
336
337bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
338 if (property >= 0 && property <= INPUT_PROP_MAX) {
339 AutoMutex _l(mLock);
340
341 Device* device = getDeviceLocked(deviceId);
342 if (device) {
343 return test_bit(property, device->propBitmask);
344 }
345 }
346 return false;
347}
348
349int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
350 if (scanCode >= 0 && scanCode <= KEY_MAX) {
351 AutoMutex _l(mLock);
352
353 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700354 if (device && device->hasValidFd() && test_bit(scanCode, device->keyBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800355 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
356 memset(keyState, 0, sizeof(keyState));
357 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
358 return test_bit(scanCode, keyState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
359 }
360 }
361 }
362 return AKEY_STATE_UNKNOWN;
363}
364
365int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
366 AutoMutex _l(mLock);
367
368 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700369 if (device && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800370 Vector<int32_t> scanCodes;
371 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode, &scanCodes);
372 if (scanCodes.size() != 0) {
373 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
374 memset(keyState, 0, sizeof(keyState));
375 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
376 for (size_t i = 0; i < scanCodes.size(); i++) {
377 int32_t sc = scanCodes.itemAt(i);
378 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, keyState)) {
379 return AKEY_STATE_DOWN;
380 }
381 }
382 return AKEY_STATE_UP;
383 }
384 }
385 }
386 return AKEY_STATE_UNKNOWN;
387}
388
389int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
390 if (sw >= 0 && sw <= SW_MAX) {
391 AutoMutex _l(mLock);
392
393 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700394 if (device && device->hasValidFd() && test_bit(sw, device->swBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800395 uint8_t swState[sizeof_bit_array(SW_MAX + 1)];
396 memset(swState, 0, sizeof(swState));
397 if (ioctl(device->fd, EVIOCGSW(sizeof(swState)), swState) >= 0) {
398 return test_bit(sw, swState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
399 }
400 }
401 }
402 return AKEY_STATE_UNKNOWN;
403}
404
405status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
406 *outValue = 0;
407
408 if (axis >= 0 && axis <= ABS_MAX) {
409 AutoMutex _l(mLock);
410
411 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700412 if (device && device->hasValidFd() && test_bit(axis, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800413 struct input_absinfo info;
414 if(ioctl(device->fd, EVIOCGABS(axis), &info)) {
415 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100416 axis, device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800417 return -errno;
418 }
419
420 *outValue = info.value;
421 return OK;
422 }
423 }
424 return -1;
425}
426
427bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes,
428 const int32_t* keyCodes, uint8_t* outFlags) const {
429 AutoMutex _l(mLock);
430
431 Device* device = getDeviceLocked(deviceId);
432 if (device && device->keyMap.haveKeyLayout()) {
433 Vector<int32_t> scanCodes;
434 for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) {
435 scanCodes.clear();
436
437 status_t err = device->keyMap.keyLayoutMap->findScanCodesForKey(
438 keyCodes[codeIndex], &scanCodes);
439 if (! err) {
440 // check the possible scan codes identified by the layout map against the
441 // map of codes actually emitted by the driver
442 for (size_t sc = 0; sc < scanCodes.size(); sc++) {
443 if (test_bit(scanCodes[sc], device->keyBitmask)) {
444 outFlags[codeIndex] = 1;
445 break;
446 }
447 }
448 }
449 }
450 return true;
451 }
452 return false;
453}
454
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700455status_t EventHub::mapKey(int32_t deviceId,
456 int32_t scanCode, int32_t usageCode, int32_t metaState,
457 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800458 AutoMutex _l(mLock);
459 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700460 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800461
462 if (device) {
463 // Check the key character map first.
464 sp<KeyCharacterMap> kcm = device->getKeyCharacterMap();
Yi Kong9b14ac62018-07-17 13:48:38 -0700465 if (kcm != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800466 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
467 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700468 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800469 }
470 }
471
472 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700473 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800474 if (!device->keyMap.keyLayoutMap->mapKey(
475 scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700476 status = NO_ERROR;
477 }
478 }
479
480 if (status == NO_ERROR) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700481 if (kcm != nullptr) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700482 kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState);
483 } else {
484 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800485 }
486 }
487 }
488
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700489 if (status != NO_ERROR) {
490 *outKeycode = 0;
491 *outFlags = 0;
492 *outMetaState = metaState;
493 }
494
495 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800496}
497
498status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
499 AutoMutex _l(mLock);
500 Device* device = getDeviceLocked(deviceId);
501
502 if (device && device->keyMap.haveKeyLayout()) {
503 status_t err = device->keyMap.keyLayoutMap->mapAxis(scanCode, outAxisInfo);
504 if (err == NO_ERROR) {
505 return NO_ERROR;
506 }
507 }
508
509 return NAME_NOT_FOUND;
510}
511
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100512void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800513 AutoMutex _l(mLock);
514
515 mExcludedDevices = devices;
516}
517
518bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
519 AutoMutex _l(mLock);
520 Device* device = getDeviceLocked(deviceId);
521 if (device && scanCode >= 0 && scanCode <= KEY_MAX) {
522 if (test_bit(scanCode, device->keyBitmask)) {
523 return true;
524 }
525 }
526 return false;
527}
528
529bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
530 AutoMutex _l(mLock);
531 Device* device = getDeviceLocked(deviceId);
532 int32_t sc;
533 if (device && mapLed(device, led, &sc) == NO_ERROR) {
534 if (test_bit(sc, device->ledBitmask)) {
535 return true;
536 }
537 }
538 return false;
539}
540
541void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
542 AutoMutex _l(mLock);
543 Device* device = getDeviceLocked(deviceId);
544 setLedStateLocked(device, led, on);
545}
546
547void EventHub::setLedStateLocked(Device* device, int32_t led, bool on) {
548 int32_t sc;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700549 if (device && device->hasValidFd() && mapLed(device, led, &sc) != NAME_NOT_FOUND) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800550 struct input_event ev;
551 ev.time.tv_sec = 0;
552 ev.time.tv_usec = 0;
553 ev.type = EV_LED;
554 ev.code = sc;
555 ev.value = on ? 1 : 0;
556
557 ssize_t nWrite;
558 do {
559 nWrite = write(device->fd, &ev, sizeof(struct input_event));
560 } while (nWrite == -1 && errno == EINTR);
561 }
562}
563
564void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
565 Vector<VirtualKeyDefinition>& outVirtualKeys) const {
566 outVirtualKeys.clear();
567
568 AutoMutex _l(mLock);
569 Device* device = getDeviceLocked(deviceId);
570 if (device && device->virtualKeyMap) {
571 outVirtualKeys.appendVector(device->virtualKeyMap->getVirtualKeys());
572 }
573}
574
575sp<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
576 AutoMutex _l(mLock);
577 Device* device = getDeviceLocked(deviceId);
578 if (device) {
579 return device->getKeyCharacterMap();
580 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700581 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800582}
583
584bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId,
585 const sp<KeyCharacterMap>& map) {
586 AutoMutex _l(mLock);
587 Device* device = getDeviceLocked(deviceId);
588 if (device) {
589 if (map != device->overlayKeyMap) {
590 device->overlayKeyMap = map;
591 device->combinedKeyMap = KeyCharacterMap::combine(
592 device->keyMap.keyCharacterMap, map);
593 return true;
594 }
595 }
596 return false;
597}
598
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100599static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
600 std::string rawDescriptor;
601 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800602 identifier.product);
603 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100604 if (!identifier.uniqueId.empty()) {
605 rawDescriptor += "uniqueId:";
606 rawDescriptor += identifier.uniqueId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800607 } else if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100608 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800609 }
610
611 if (identifier.vendor == 0 && identifier.product == 0) {
612 // If we don't know the vendor and product id, then the device is probably
613 // built-in so we need to rely on other information to uniquely identify
614 // the input device. Usually we try to avoid relying on the device name or
615 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100616 if (!identifier.name.empty()) {
617 rawDescriptor += "name:";
618 rawDescriptor += identifier.name;
619 } else if (!identifier.location.empty()) {
620 rawDescriptor += "location:";
621 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800622 }
623 }
624 identifier.descriptor = sha1(rawDescriptor);
625 return rawDescriptor;
626}
627
628void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
629 // Compute a device descriptor that uniquely identifies the device.
630 // The descriptor is assumed to be a stable identifier. Its value should not
631 // change between reboots, reconnections, firmware updates or new releases
632 // of Android. In practice we sometimes get devices that cannot be uniquely
633 // identified. In this case we enforce uniqueness between connected devices.
634 // Ideally, we also want the descriptor to be short and relatively opaque.
635
636 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100637 std::string rawDescriptor = generateDescriptor(identifier);
638 if (identifier.uniqueId.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800639 // If it didn't have a unique id check for conflicts and enforce
640 // uniqueness if necessary.
Yi Kong9b14ac62018-07-17 13:48:38 -0700641 while(getDeviceByDescriptorLocked(identifier.descriptor) != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800642 identifier.nonce++;
643 rawDescriptor = generateDescriptor(identifier);
644 }
645 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100646 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
647 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800648}
649
650void EventHub::vibrate(int32_t deviceId, nsecs_t duration) {
651 AutoMutex _l(mLock);
652 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700653 if (device && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800654 ff_effect effect;
655 memset(&effect, 0, sizeof(effect));
656 effect.type = FF_RUMBLE;
657 effect.id = device->ffEffectId;
658 effect.u.rumble.strong_magnitude = 0xc000;
659 effect.u.rumble.weak_magnitude = 0xc000;
660 effect.replay.length = (duration + 999999LL) / 1000000LL;
661 effect.replay.delay = 0;
662 if (ioctl(device->fd, EVIOCSFF, &effect)) {
663 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100664 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800665 return;
666 }
667 device->ffEffectId = effect.id;
668
669 struct input_event ev;
670 ev.time.tv_sec = 0;
671 ev.time.tv_usec = 0;
672 ev.type = EV_FF;
673 ev.code = device->ffEffectId;
674 ev.value = 1;
675 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
676 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100677 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800678 return;
679 }
680 device->ffEffectPlaying = true;
681 }
682}
683
684void EventHub::cancelVibrate(int32_t deviceId) {
685 AutoMutex _l(mLock);
686 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700687 if (device && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800688 if (device->ffEffectPlaying) {
689 device->ffEffectPlaying = false;
690
691 struct input_event ev;
692 ev.time.tv_sec = 0;
693 ev.time.tv_usec = 0;
694 ev.type = EV_FF;
695 ev.code = device->ffEffectId;
696 ev.value = 0;
697 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
698 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100699 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800700 return;
701 }
702 }
703 }
704}
705
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100706EventHub::Device* EventHub::getDeviceByDescriptorLocked(const std::string& descriptor) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800707 size_t size = mDevices.size();
708 for (size_t i = 0; i < size; i++) {
709 Device* device = mDevices.valueAt(i);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100710 if (descriptor == device->identifier.descriptor) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800711 return device;
712 }
713 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700714 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800715}
716
717EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
718 if (deviceId == BUILT_IN_KEYBOARD_ID) {
719 deviceId = mBuiltInKeyboardId;
720 }
721 ssize_t index = mDevices.indexOfKey(deviceId);
722 return index >= 0 ? mDevices.valueAt(index) : NULL;
723}
724
725EventHub::Device* EventHub::getDeviceByPathLocked(const char* devicePath) const {
726 for (size_t i = 0; i < mDevices.size(); i++) {
727 Device* device = mDevices.valueAt(i);
728 if (device->path == devicePath) {
729 return device;
730 }
731 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700732 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800733}
734
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700735EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
736 for (size_t i = 0; i < mDevices.size(); i++) {
737 Device* device = mDevices.valueAt(i);
738 if (device->fd == fd) {
739 return device;
740 }
741 }
742 return nullptr;
743}
744
Michael Wrightd02c5b62014-02-10 15:10:22 -0800745size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
746 ALOG_ASSERT(bufferSize >= 1);
747
748 AutoMutex _l(mLock);
749
750 struct input_event readBuffer[bufferSize];
751
752 RawEvent* event = buffer;
753 size_t capacity = bufferSize;
754 bool awoken = false;
755 for (;;) {
756 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
757
758 // Reopen input devices if needed.
759 if (mNeedToReopenDevices) {
760 mNeedToReopenDevices = false;
761
762 ALOGI("Reopening all input devices due to a configuration change.");
763
764 closeAllDevicesLocked();
765 mNeedToScanDevices = true;
766 break; // return to the caller before we actually rescan
767 }
768
769 // Report any devices that had last been added/removed.
770 while (mClosingDevices) {
771 Device* device = mClosingDevices;
772 ALOGV("Reporting device closed: id=%d, name=%s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100773 device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800774 mClosingDevices = device->next;
775 event->when = now;
776 event->deviceId = device->id == mBuiltInKeyboardId ? BUILT_IN_KEYBOARD_ID : device->id;
777 event->type = DEVICE_REMOVED;
778 event += 1;
779 delete device;
780 mNeedToSendFinishedDeviceScan = true;
781 if (--capacity == 0) {
782 break;
783 }
784 }
785
786 if (mNeedToScanDevices) {
787 mNeedToScanDevices = false;
788 scanDevicesLocked();
789 mNeedToSendFinishedDeviceScan = true;
790 }
791
Yi Kong9b14ac62018-07-17 13:48:38 -0700792 while (mOpeningDevices != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800793 Device* device = mOpeningDevices;
794 ALOGV("Reporting device opened: id=%d, name=%s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100795 device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800796 mOpeningDevices = device->next;
797 event->when = now;
798 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
799 event->type = DEVICE_ADDED;
800 event += 1;
801 mNeedToSendFinishedDeviceScan = true;
802 if (--capacity == 0) {
803 break;
804 }
805 }
806
807 if (mNeedToSendFinishedDeviceScan) {
808 mNeedToSendFinishedDeviceScan = false;
809 event->when = now;
810 event->type = FINISHED_DEVICE_SCAN;
811 event += 1;
812 if (--capacity == 0) {
813 break;
814 }
815 }
816
817 // Grab the next input event.
818 bool deviceChanged = false;
819 while (mPendingEventIndex < mPendingEventCount) {
820 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700821 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800822 if (eventItem.events & EPOLLIN) {
823 mPendingINotify = true;
824 } else {
825 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
826 }
827 continue;
828 }
829
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700830 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800831 if (eventItem.events & EPOLLIN) {
832 ALOGV("awoken after wake()");
833 awoken = true;
834 char buffer[16];
835 ssize_t nRead;
836 do {
837 nRead = read(mWakeReadPipeFd, buffer, sizeof(buffer));
838 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(buffer));
839 } else {
840 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
841 eventItem.events);
842 }
843 continue;
844 }
845
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700846 Device* device = getDeviceByFdLocked(eventItem.data.fd);
847 if (device == nullptr) {
848 ALOGW("Received unexpected epoll event 0x%08x for unknown device fd %d.",
849 eventItem.events, eventItem.data.fd);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800850 continue;
851 }
852
Michael Wrightd02c5b62014-02-10 15:10:22 -0800853 if (eventItem.events & EPOLLIN) {
854 int32_t readSize = read(device->fd, readBuffer,
855 sizeof(struct input_event) * capacity);
856 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
857 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -0700858 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
859 " bufferSize: %zu capacity: %zu errno: %d)\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800860 device->fd, readSize, bufferSize, capacity, errno);
861 deviceChanged = true;
862 closeDeviceLocked(device);
863 } else if (readSize < 0) {
864 if (errno != EAGAIN && errno != EINTR) {
865 ALOGW("could not get event (errno=%d)", errno);
866 }
867 } else if ((readSize % sizeof(struct input_event)) != 0) {
868 ALOGE("could not get event (wrong size: %d)", readSize);
869 } else {
870 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
871
872 size_t count = size_t(readSize) / sizeof(struct input_event);
873 for (size_t i = 0; i < count; i++) {
874 struct input_event& iev = readBuffer[i];
875 ALOGV("%s got: time=%d.%06d, type=%d, code=%d, value=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100876 device->path.c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800877 (int) iev.time.tv_sec, (int) iev.time.tv_usec,
878 iev.type, iev.code, iev.value);
879
Michael Wrightd02c5b62014-02-10 15:10:22 -0800880 // Use the time specified in the event instead of the current time
881 // so that downstream code can get more accurate estimates of
882 // event dispatch latency from the time the event is enqueued onto
883 // the evdev client buffer.
884 //
885 // The event's timestamp fortuitously uses the same monotonic clock
886 // time base as the rest of Android. The kernel event device driver
887 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
888 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
889 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
890 // system call that also queries ktime_get_ts().
891 event->when = nsecs_t(iev.time.tv_sec) * 1000000000LL
892 + nsecs_t(iev.time.tv_usec) * 1000LL;
Mark Salyzyn5aa26b22014-06-10 13:07:44 -0700893 ALOGV("event time %" PRId64 ", now %" PRId64, event->when, now);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800894
895 // Bug 7291243: Add a guard in case the kernel generates timestamps
896 // that appear to be far into the future because they were generated
897 // using the wrong clock source.
898 //
899 // This can happen because when the input device is initially opened
900 // it has a default clock source of CLOCK_REALTIME. Any input events
901 // enqueued right after the device is opened will have timestamps
902 // generated using CLOCK_REALTIME. We later set the clock source
903 // to CLOCK_MONOTONIC but it is already too late.
904 //
905 // Invalid input event timestamps can result in ANRs, crashes and
906 // and other issues that are hard to track down. We must not let them
907 // propagate through the system.
908 //
909 // Log a warning so that we notice the problem and recover gracefully.
910 if (event->when >= now + 10 * 1000000000LL) {
911 // Double-check. Time may have moved on.
912 nsecs_t time = systemTime(SYSTEM_TIME_MONOTONIC);
913 if (event->when > time) {
914 ALOGW("An input event from %s has a timestamp that appears to "
915 "have been generated using the wrong clock source "
916 "(expected CLOCK_MONOTONIC): "
Mark Salyzyn5aa26b22014-06-10 13:07:44 -0700917 "event time %" PRId64 ", current time %" PRId64
918 ", call time %" PRId64 ". "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800919 "Using current time instead.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100920 device->path.c_str(), event->when, time, now);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800921 event->when = time;
922 } else {
923 ALOGV("Event time is ok but failed the fast path and required "
924 "an extra call to systemTime: "
Mark Salyzyn5aa26b22014-06-10 13:07:44 -0700925 "event time %" PRId64 ", current time %" PRId64
926 ", call time %" PRId64 ".",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800927 event->when, time, now);
928 }
929 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800930 event->deviceId = deviceId;
931 event->type = iev.type;
932 event->code = iev.code;
933 event->value = iev.value;
934 event += 1;
935 capacity -= 1;
936 }
937 if (capacity == 0) {
938 // The result buffer is full. Reset the pending event index
939 // so we will try to read the device again on the next iteration.
940 mPendingEventIndex -= 1;
941 break;
942 }
943 }
944 } else if (eventItem.events & EPOLLHUP) {
945 ALOGI("Removing device %s due to epoll hang-up event.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100946 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800947 deviceChanged = true;
948 closeDeviceLocked(device);
949 } else {
950 ALOGW("Received unexpected epoll event 0x%08x for device %s.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100951 eventItem.events, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800952 }
953 }
954
955 // readNotify() will modify the list of devices so this must be done after
956 // processing all other events to ensure that we read all remaining events
957 // before closing the devices.
958 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
959 mPendingINotify = false;
960 readNotifyLocked();
961 deviceChanged = true;
962 }
963
964 // Report added or removed devices immediately.
965 if (deviceChanged) {
966 continue;
967 }
968
969 // Return now if we have collected any events or if we were explicitly awoken.
970 if (event != buffer || awoken) {
971 break;
972 }
973
974 // Poll for events. Mind the wake lock dance!
975 // We hold a wake lock at all times except during epoll_wait(). This works due to some
976 // subtle choreography. When a device driver has pending (unread) events, it acquires
977 // a kernel wake lock. However, once the last pending event has been read, the device
978 // driver will release the kernel wake lock. To prevent the system from going to sleep
979 // when this happens, the EventHub holds onto its own user wake lock while the client
980 // is processing events. Thus the system can only sleep if there are no events
981 // pending or currently being processed.
982 //
983 // The timeout is advisory only. If the device is asleep, it will not wake just to
984 // service the timeout.
985 mPendingEventIndex = 0;
986
987 mLock.unlock(); // release lock before poll, must be before release_wake_lock
988 release_wake_lock(WAKE_LOCK_ID);
989
990 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
991
992 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
993 mLock.lock(); // reacquire lock after poll, must be after acquire_wake_lock
994
995 if (pollResult == 0) {
996 // Timed out.
997 mPendingEventCount = 0;
998 break;
999 }
1000
1001 if (pollResult < 0) {
1002 // An error occurred.
1003 mPendingEventCount = 0;
1004
1005 // Sleep after errors to avoid locking up the system.
1006 // Hopefully the error is transient.
1007 if (errno != EINTR) {
1008 ALOGW("poll failed (errno=%d)\n", errno);
1009 usleep(100000);
1010 }
1011 } else {
1012 // Some events occurred.
1013 mPendingEventCount = size_t(pollResult);
1014 }
1015 }
1016
1017 // All done, return the number of events we read.
1018 return event - buffer;
1019}
1020
1021void EventHub::wake() {
1022 ALOGV("wake() called");
1023
1024 ssize_t nWrite;
1025 do {
1026 nWrite = write(mWakeWritePipeFd, "W", 1);
1027 } while (nWrite == -1 && errno == EINTR);
1028
1029 if (nWrite != 1 && errno != EAGAIN) {
1030 ALOGW("Could not write wake signal, errno=%d", errno);
1031 }
1032}
1033
1034void EventHub::scanDevicesLocked() {
1035 status_t res = scanDirLocked(DEVICE_PATH);
1036 if(res < 0) {
1037 ALOGE("scan dir failed for %s\n", DEVICE_PATH);
1038 }
1039 if (mDevices.indexOfKey(VIRTUAL_KEYBOARD_ID) < 0) {
1040 createVirtualKeyboardLocked();
1041 }
1042}
1043
1044// ----------------------------------------------------------------------------
1045
1046static bool containsNonZeroByte(const uint8_t* array, uint32_t startIndex, uint32_t endIndex) {
1047 const uint8_t* end = array + endIndex;
1048 array += startIndex;
1049 while (array != end) {
1050 if (*(array++) != 0) {
1051 return true;
1052 }
1053 }
1054 return false;
1055}
1056
1057static const int32_t GAMEPAD_KEYCODES[] = {
1058 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C,
1059 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z,
1060 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1,
1061 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2,
1062 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR,
1063 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001064};
1065
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001066status_t EventHub::registerDeviceForEpollLocked(Device* device) {
1067 struct epoll_event eventItem;
1068 memset(&eventItem, 0, sizeof(eventItem));
1069 eventItem.events = EPOLLIN;
1070 if (mUsingEpollWakeup) {
1071 eventItem.events |= EPOLLWAKEUP;
1072 }
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001073 eventItem.data.fd = device->fd;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001074 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, device->fd, &eventItem)) {
1075 ALOGE("Could not add device fd to epoll instance. errno=%d", errno);
1076 return -errno;
1077 }
1078 return OK;
1079}
1080
1081status_t EventHub::unregisterDeviceFromEpollLocked(Device* device) {
1082 if (device->hasValidFd()) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001083 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, device->fd, nullptr)) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001084 ALOGW("Could not remove device fd from epoll instance. errno=%d", errno);
1085 return -errno;
1086 }
1087 }
1088 return OK;
1089}
1090
Michael Wrightd02c5b62014-02-10 15:10:22 -08001091status_t EventHub::openDeviceLocked(const char *devicePath) {
1092 char buffer[80];
1093
1094 ALOGV("Opening device: %s", devicePath);
1095
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001096 int fd = open(devicePath, O_RDWR | O_CLOEXEC | O_NONBLOCK);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001097 if(fd < 0) {
1098 ALOGE("could not open %s, %s\n", devicePath, strerror(errno));
1099 return -1;
1100 }
1101
1102 InputDeviceIdentifier identifier;
1103
1104 // Get device name.
1105 if(ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
1106 //fprintf(stderr, "could not get device name for %s, %s\n", devicePath, strerror(errno));
1107 } else {
1108 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001109 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001110 }
1111
1112 // Check to see if the device is on our excluded list
1113 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001114 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001115 if (identifier.name == item) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001116 ALOGI("ignoring event id %s driver %s\n", devicePath, item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001117 close(fd);
1118 return -1;
1119 }
1120 }
1121
1122 // Get device driver version.
1123 int driverVersion;
1124 if(ioctl(fd, EVIOCGVERSION, &driverVersion)) {
1125 ALOGE("could not get driver version for %s, %s\n", devicePath, strerror(errno));
1126 close(fd);
1127 return -1;
1128 }
1129
1130 // Get device identifier.
1131 struct input_id inputId;
1132 if(ioctl(fd, EVIOCGID, &inputId)) {
1133 ALOGE("could not get device input id for %s, %s\n", devicePath, strerror(errno));
1134 close(fd);
1135 return -1;
1136 }
1137 identifier.bus = inputId.bustype;
1138 identifier.product = inputId.product;
1139 identifier.vendor = inputId.vendor;
1140 identifier.version = inputId.version;
1141
1142 // Get device physical location.
1143 if(ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
1144 //fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
1145 } else {
1146 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001147 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001148 }
1149
1150 // Get device unique id.
1151 if(ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
1152 //fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
1153 } else {
1154 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001155 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001156 }
1157
1158 // Fill in the descriptor.
1159 assignDescriptorLocked(identifier);
1160
Michael Wrightd02c5b62014-02-10 15:10:22 -08001161 // Allocate device. (The device object takes ownership of the fd at this point.)
1162 int32_t deviceId = mNextDeviceId++;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001163 Device* device = new Device(fd, deviceId, devicePath, identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001164
1165 ALOGV("add device %d: %s\n", deviceId, devicePath);
1166 ALOGV(" bus: %04x\n"
1167 " vendor %04x\n"
1168 " product %04x\n"
1169 " version %04x\n",
1170 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001171 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
1172 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
1173 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
1174 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001175 ALOGV(" driver: v%d.%d.%d\n",
1176 driverVersion >> 16, (driverVersion >> 8) & 0xff, driverVersion & 0xff);
1177
1178 // Load the configuration file for the device.
1179 loadConfigurationLocked(device);
1180
1181 // Figure out the kinds of events the device reports.
1182 ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(device->keyBitmask)), device->keyBitmask);
1183 ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(device->absBitmask)), device->absBitmask);
1184 ioctl(fd, EVIOCGBIT(EV_REL, sizeof(device->relBitmask)), device->relBitmask);
1185 ioctl(fd, EVIOCGBIT(EV_SW, sizeof(device->swBitmask)), device->swBitmask);
1186 ioctl(fd, EVIOCGBIT(EV_LED, sizeof(device->ledBitmask)), device->ledBitmask);
1187 ioctl(fd, EVIOCGBIT(EV_FF, sizeof(device->ffBitmask)), device->ffBitmask);
1188 ioctl(fd, EVIOCGPROP(sizeof(device->propBitmask)), device->propBitmask);
1189
1190 // See if this is a keyboard. Ignore everything in the button range except for
1191 // joystick and gamepad buttons which are handled like keyboards for the most part.
1192 bool haveKeyboardKeys = containsNonZeroByte(device->keyBitmask, 0, sizeof_bit_array(BTN_MISC))
1193 || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(KEY_OK),
1194 sizeof_bit_array(KEY_MAX + 1));
1195 bool haveGamepadButtons = containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_MISC),
1196 sizeof_bit_array(BTN_MOUSE))
1197 || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_JOYSTICK),
1198 sizeof_bit_array(BTN_DIGI));
1199 if (haveKeyboardKeys || haveGamepadButtons) {
1200 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1201 }
1202
1203 // See if this is a cursor device such as a trackball or mouse.
1204 if (test_bit(BTN_MOUSE, device->keyBitmask)
1205 && test_bit(REL_X, device->relBitmask)
1206 && test_bit(REL_Y, device->relBitmask)) {
1207 device->classes |= INPUT_DEVICE_CLASS_CURSOR;
1208 }
1209
Prashant Malani1941ff52015-08-11 18:29:28 -07001210 // See if this is a rotary encoder type device.
1211 String8 deviceType = String8();
1212 if (device->configuration &&
1213 device->configuration->tryGetProperty(String8("device.type"), deviceType)) {
1214 if (!deviceType.compare(String8("rotaryEncoder"))) {
1215 device->classes |= INPUT_DEVICE_CLASS_ROTARY_ENCODER;
1216 }
1217 }
1218
Michael Wrightd02c5b62014-02-10 15:10:22 -08001219 // See if this is a touch pad.
1220 // Is this a new modern multi-touch driver?
1221 if (test_bit(ABS_MT_POSITION_X, device->absBitmask)
1222 && test_bit(ABS_MT_POSITION_Y, device->absBitmask)) {
1223 // Some joysticks such as the PS3 controller report axes that conflict
1224 // with the ABS_MT range. Try to confirm that the device really is
1225 // a touch screen.
1226 if (test_bit(BTN_TOUCH, device->keyBitmask) || !haveGamepadButtons) {
1227 device->classes |= INPUT_DEVICE_CLASS_TOUCH | INPUT_DEVICE_CLASS_TOUCH_MT;
1228 }
1229 // Is this an old style single-touch driver?
1230 } else if (test_bit(BTN_TOUCH, device->keyBitmask)
1231 && test_bit(ABS_X, device->absBitmask)
1232 && test_bit(ABS_Y, device->absBitmask)) {
1233 device->classes |= INPUT_DEVICE_CLASS_TOUCH;
Michael Wright842500e2015-03-13 17:32:02 -07001234 // Is this a BT stylus?
1235 } else if ((test_bit(ABS_PRESSURE, device->absBitmask) ||
1236 test_bit(BTN_TOUCH, device->keyBitmask))
1237 && !test_bit(ABS_X, device->absBitmask)
1238 && !test_bit(ABS_Y, device->absBitmask)) {
1239 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
1240 // Keyboard will try to claim some of the buttons but we really want to reserve those so we
1241 // can fuse it with the touch screen data, so just take them back. Note this means an
1242 // external stylus cannot also be a keyboard device.
1243 device->classes &= ~INPUT_DEVICE_CLASS_KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001244 }
1245
1246 // See if this device is a joystick.
1247 // Assumes that joysticks always have gamepad buttons in order to distinguish them
1248 // from other devices such as accelerometers that also have absolute axes.
1249 if (haveGamepadButtons) {
1250 uint32_t assumedClasses = device->classes | INPUT_DEVICE_CLASS_JOYSTICK;
1251 for (int i = 0; i <= ABS_MAX; i++) {
1252 if (test_bit(i, device->absBitmask)
1253 && (getAbsAxisUsage(i, assumedClasses) & INPUT_DEVICE_CLASS_JOYSTICK)) {
1254 device->classes = assumedClasses;
1255 break;
1256 }
1257 }
1258 }
1259
1260 // Check whether this device has switches.
1261 for (int i = 0; i <= SW_MAX; i++) {
1262 if (test_bit(i, device->swBitmask)) {
1263 device->classes |= INPUT_DEVICE_CLASS_SWITCH;
1264 break;
1265 }
1266 }
1267
1268 // Check whether this device supports the vibrator.
1269 if (test_bit(FF_RUMBLE, device->ffBitmask)) {
1270 device->classes |= INPUT_DEVICE_CLASS_VIBRATOR;
1271 }
1272
1273 // Configure virtual keys.
1274 if ((device->classes & INPUT_DEVICE_CLASS_TOUCH)) {
1275 // Load the virtual keys for the touch screen, if any.
1276 // We do this now so that we can make sure to load the keymap if necessary.
1277 status_t status = loadVirtualKeyMapLocked(device);
1278 if (!status) {
1279 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1280 }
1281 }
1282
1283 // Load the key map.
1284 // We need to do this for joysticks too because the key layout may specify axes.
1285 status_t keyMapStatus = NAME_NOT_FOUND;
1286 if (device->classes & (INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_JOYSTICK)) {
1287 // Load the keymap for the device.
1288 keyMapStatus = loadKeyMapLocked(device);
1289 }
1290
1291 // Configure the keyboard, gamepad or virtual keyboard.
1292 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1293 // Register the keyboard as a built-in keyboard if it is eligible.
1294 if (!keyMapStatus
1295 && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD
1296 && isEligibleBuiltInKeyboard(device->identifier,
1297 device->configuration, &device->keyMap)) {
1298 mBuiltInKeyboardId = device->id;
1299 }
1300
1301 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
1302 if (hasKeycodeLocked(device, AKEYCODE_Q)) {
1303 device->classes |= INPUT_DEVICE_CLASS_ALPHAKEY;
1304 }
1305
1306 // See if this device has a DPAD.
1307 if (hasKeycodeLocked(device, AKEYCODE_DPAD_UP) &&
1308 hasKeycodeLocked(device, AKEYCODE_DPAD_DOWN) &&
1309 hasKeycodeLocked(device, AKEYCODE_DPAD_LEFT) &&
1310 hasKeycodeLocked(device, AKEYCODE_DPAD_RIGHT) &&
1311 hasKeycodeLocked(device, AKEYCODE_DPAD_CENTER)) {
1312 device->classes |= INPUT_DEVICE_CLASS_DPAD;
1313 }
1314
1315 // See if this device has a gamepad.
1316 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES)/sizeof(GAMEPAD_KEYCODES[0]); i++) {
1317 if (hasKeycodeLocked(device, GAMEPAD_KEYCODES[i])) {
1318 device->classes |= INPUT_DEVICE_CLASS_GAMEPAD;
1319 break;
1320 }
1321 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001322 }
1323
1324 // If the device isn't recognized as something we handle, don't monitor it.
1325 if (device->classes == 0) {
1326 ALOGV("Dropping device: id=%d, path='%s', name='%s'",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001327 deviceId, devicePath, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001328 delete device;
1329 return -1;
1330 }
1331
Tim Kilbourn063ff532015-04-08 10:26:18 -07001332 // Determine whether the device has a mic.
1333 if (deviceHasMicLocked(device)) {
1334 device->classes |= INPUT_DEVICE_CLASS_MIC;
1335 }
1336
Michael Wrightd02c5b62014-02-10 15:10:22 -08001337 // Determine whether the device is external or internal.
1338 if (isExternalDeviceLocked(device)) {
1339 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL;
1340 }
1341
Michael Wright42f2c6a2014-03-12 10:33:03 -07001342 if (device->classes & (INPUT_DEVICE_CLASS_JOYSTICK | INPUT_DEVICE_CLASS_DPAD)
1343 && device->classes & INPUT_DEVICE_CLASS_GAMEPAD) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001344 device->controllerNumber = getNextControllerNumberLocked(device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001345 setLedForControllerLocked(device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001346 }
1347
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001348
1349 if (registerDeviceForEpollLocked(device) != OK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001350 delete device;
1351 return -1;
1352 }
1353
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001354 configureFd(device);
1355
1356 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=0x%x, "
1357 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001358 deviceId, fd, devicePath, device->identifier.name.c_str(),
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001359 device->classes,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001360 device->configurationFile.c_str(),
1361 device->keyMap.keyLayoutFile.c_str(),
1362 device->keyMap.keyCharacterMapFile.c_str(),
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001363 toString(mBuiltInKeyboardId == deviceId));
1364
1365 addDeviceLocked(device);
1366 return OK;
1367}
1368
1369void EventHub::configureFd(Device* device) {
1370 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
1371 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1372 // Disable kernel key repeat since we handle it ourselves
1373 unsigned int repeatRate[] = {0, 0};
1374 if (ioctl(device->fd, EVIOCSREP, repeatRate)) {
1375 ALOGW("Unable to disable kernel key repeat for %s: %s",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001376 device->path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001377 }
1378 }
1379
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001380 std::string wakeMechanism = "EPOLLWAKEUP";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001381 if (!mUsingEpollWakeup) {
1382#ifndef EVIOCSSUSPENDBLOCK
1383 // uapi headers don't include EVIOCSSUSPENDBLOCK, and future kernels
1384 // will use an epoll flag instead, so as long as we want to support
1385 // this feature, we need to be prepared to define the ioctl ourselves.
1386#define EVIOCSSUSPENDBLOCK _IOW('E', 0x91, int)
1387#endif
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001388 if (ioctl(device->fd, EVIOCSSUSPENDBLOCK, 1)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001389 wakeMechanism = "<none>";
1390 } else {
1391 wakeMechanism = "EVIOCSSUSPENDBLOCK";
1392 }
1393 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001394 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
1395 // associated with input events. This is important because the input system
1396 // uses the timestamps extensively and assumes they were recorded using the monotonic
1397 // clock.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001398 int clockId = CLOCK_MONOTONIC;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001399 bool usingClockIoctl = !ioctl(device->fd, EVIOCSCLOCKID, &clockId);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001400 ALOGI("wakeMechanism=%s, usingClockIoctl=%s", wakeMechanism.c_str(),
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001401 toString(usingClockIoctl));
1402}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001403
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001404bool EventHub::isDeviceEnabled(int32_t deviceId) {
1405 AutoMutex _l(mLock);
1406 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001407 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001408 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1409 return false;
1410 }
1411 return device->enabled;
1412}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001413
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001414status_t EventHub::enableDevice(int32_t deviceId) {
1415 AutoMutex _l(mLock);
1416 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001417 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001418 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1419 return BAD_VALUE;
1420 }
1421 if (device->enabled) {
1422 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
1423 return OK;
1424 }
1425 status_t result = device->enable();
1426 if (result != OK) {
1427 ALOGE("Failed to enable device %" PRId32, deviceId);
1428 return result;
1429 }
1430
1431 configureFd(device);
1432
1433 return registerDeviceForEpollLocked(device);
1434}
1435
1436status_t EventHub::disableDevice(int32_t deviceId) {
1437 AutoMutex _l(mLock);
1438 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001439 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001440 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1441 return BAD_VALUE;
1442 }
1443 if (!device->enabled) {
1444 ALOGW("Duplicate call to %s, input device already disabled", __func__);
1445 return OK;
1446 }
1447 unregisterDeviceFromEpollLocked(device);
1448 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001449}
1450
1451void EventHub::createVirtualKeyboardLocked() {
1452 InputDeviceIdentifier identifier;
1453 identifier.name = "Virtual";
1454 identifier.uniqueId = "<virtual>";
1455 assignDescriptorLocked(identifier);
1456
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001457 Device* device = new Device(-1, VIRTUAL_KEYBOARD_ID, "<virtual>", identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001458 device->classes = INPUT_DEVICE_CLASS_KEYBOARD
1459 | INPUT_DEVICE_CLASS_ALPHAKEY
1460 | INPUT_DEVICE_CLASS_DPAD
1461 | INPUT_DEVICE_CLASS_VIRTUAL;
1462 loadKeyMapLocked(device);
1463 addDeviceLocked(device);
1464}
1465
1466void EventHub::addDeviceLocked(Device* device) {
1467 mDevices.add(device->id, device);
1468 device->next = mOpeningDevices;
1469 mOpeningDevices = device;
1470}
1471
1472void EventHub::loadConfigurationLocked(Device* device) {
1473 device->configurationFile = getInputDeviceConfigurationFilePathByDeviceIdentifier(
1474 device->identifier, INPUT_DEVICE_CONFIGURATION_FILE_TYPE_CONFIGURATION);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001475 if (device->configurationFile.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001476 ALOGD("No input device configuration file found for device '%s'.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001477 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001478 } else {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001479 status_t status = PropertyMap::load(String8(device->configurationFile.c_str()),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480 &device->configuration);
1481 if (status) {
1482 ALOGE("Error loading input device configuration file for device '%s'. "
1483 "Using default configuration.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001484 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001485 }
1486 }
1487}
1488
1489status_t EventHub::loadVirtualKeyMapLocked(Device* device) {
1490 // The virtual key map is supplied by the kernel as a system board property file.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001491 std::string path;
1492 path += "/sys/board_properties/virtualkeys.";
1493 path += device->identifier.name;
1494 if (access(path.c_str(), R_OK)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001495 return NAME_NOT_FOUND;
1496 }
1497 return VirtualKeyMap::load(path, &device->virtualKeyMap);
1498}
1499
1500status_t EventHub::loadKeyMapLocked(Device* device) {
1501 return device->keyMap.load(device->identifier, device->configuration);
1502}
1503
1504bool EventHub::isExternalDeviceLocked(Device* device) {
1505 if (device->configuration) {
1506 bool value;
1507 if (device->configuration->tryGetProperty(String8("device.internal"), value)) {
1508 return !value;
1509 }
1510 }
1511 return device->identifier.bus == BUS_USB || device->identifier.bus == BUS_BLUETOOTH;
1512}
1513
Tim Kilbourn063ff532015-04-08 10:26:18 -07001514bool EventHub::deviceHasMicLocked(Device* device) {
1515 if (device->configuration) {
1516 bool value;
1517 if (device->configuration->tryGetProperty(String8("audio.mic"), value)) {
1518 return value;
1519 }
1520 }
1521 return false;
1522}
1523
Michael Wrightd02c5b62014-02-10 15:10:22 -08001524int32_t EventHub::getNextControllerNumberLocked(Device* device) {
1525 if (mControllerNumbers.isFull()) {
1526 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001527 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001528 return 0;
1529 }
1530 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
1531 // one
1532 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
1533}
1534
1535void EventHub::releaseControllerNumberLocked(Device* device) {
1536 int32_t num = device->controllerNumber;
1537 device->controllerNumber= 0;
1538 if (num == 0) {
1539 return;
1540 }
1541 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
1542}
1543
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001544void EventHub::setLedForControllerLocked(Device* device) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001545 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
1546 setLedStateLocked(device, ALED_CONTROLLER_1 + i, device->controllerNumber == i + 1);
1547 }
1548}
1549
1550bool EventHub::hasKeycodeLocked(Device* device, int keycode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001551 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001552 return false;
1553 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001554
Michael Wrightd02c5b62014-02-10 15:10:22 -08001555 Vector<int32_t> scanCodes;
1556 device->keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes);
1557 const size_t N = scanCodes.size();
1558 for (size_t i=0; i<N && i<=KEY_MAX; i++) {
1559 int32_t sc = scanCodes.itemAt(i);
1560 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, device->keyBitmask)) {
1561 return true;
1562 }
1563 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001564
Michael Wrightd02c5b62014-02-10 15:10:22 -08001565 return false;
1566}
1567
1568status_t EventHub::mapLed(Device* device, int32_t led, int32_t* outScanCode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001569 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001570 return NAME_NOT_FOUND;
1571 }
1572
1573 int32_t scanCode;
1574 if(device->keyMap.keyLayoutMap->findScanCodeForLed(led, &scanCode) != NAME_NOT_FOUND) {
1575 if(scanCode >= 0 && scanCode <= LED_MAX && test_bit(scanCode, device->ledBitmask)) {
1576 *outScanCode = scanCode;
1577 return NO_ERROR;
1578 }
1579 }
1580 return NAME_NOT_FOUND;
1581}
1582
1583status_t EventHub::closeDeviceByPathLocked(const char *devicePath) {
1584 Device* device = getDeviceByPathLocked(devicePath);
1585 if (device) {
1586 closeDeviceLocked(device);
1587 return 0;
1588 }
1589 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath);
1590 return -1;
1591}
1592
1593void EventHub::closeAllDevicesLocked() {
1594 while (mDevices.size() > 0) {
1595 closeDeviceLocked(mDevices.valueAt(mDevices.size() - 1));
1596 }
1597}
1598
1599void EventHub::closeDeviceLocked(Device* device) {
1600 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=0x%x\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001601 device->path.c_str(), device->identifier.name.c_str(), device->id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001602 device->fd, device->classes);
1603
1604 if (device->id == mBuiltInKeyboardId) {
1605 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001606 device->path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001607 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
1608 }
1609
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001610 unregisterDeviceFromEpollLocked(device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001611
1612 releaseControllerNumberLocked(device);
1613
1614 mDevices.removeItem(device->id);
1615 device->close();
1616
1617 // Unlink for opening devices list if it is present.
Yi Kong9b14ac62018-07-17 13:48:38 -07001618 Device* pred = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001619 bool found = false;
Yi Kong9b14ac62018-07-17 13:48:38 -07001620 for (Device* entry = mOpeningDevices; entry != nullptr; ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001621 if (entry == device) {
1622 found = true;
1623 break;
1624 }
1625 pred = entry;
1626 entry = entry->next;
1627 }
1628 if (found) {
1629 // Unlink the device from the opening devices list then delete it.
1630 // We don't need to tell the client that the device was closed because
1631 // it does not even know it was opened in the first place.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001632 ALOGI("Device %s was immediately closed after opening.", device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001633 if (pred) {
1634 pred->next = device->next;
1635 } else {
1636 mOpeningDevices = device->next;
1637 }
1638 delete device;
1639 } else {
1640 // Link into closing devices list.
1641 // The device will be deleted later after we have informed the client.
1642 device->next = mClosingDevices;
1643 mClosingDevices = device;
1644 }
1645}
1646
1647status_t EventHub::readNotifyLocked() {
1648 int res;
1649 char devname[PATH_MAX];
1650 char *filename;
1651 char event_buf[512];
1652 int event_size;
1653 int event_pos = 0;
1654 struct inotify_event *event;
1655
1656 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
1657 res = read(mINotifyFd, event_buf, sizeof(event_buf));
1658 if(res < (int)sizeof(*event)) {
1659 if(errno == EINTR)
1660 return 0;
1661 ALOGW("could not get event, %s\n", strerror(errno));
1662 return -1;
1663 }
1664 //printf("got %d bytes of event information\n", res);
1665
1666 strcpy(devname, DEVICE_PATH);
1667 filename = devname + strlen(devname);
1668 *filename++ = '/';
1669
1670 while(res >= (int)sizeof(*event)) {
1671 event = (struct inotify_event *)(event_buf + event_pos);
1672 //printf("%d: %08x \"%s\"\n", event->wd, event->mask, event->len ? event->name : "");
1673 if(event->len) {
1674 strcpy(filename, event->name);
1675 if(event->mask & IN_CREATE) {
1676 openDeviceLocked(devname);
1677 } else {
1678 ALOGI("Removing device '%s' due to inotify event\n", devname);
1679 closeDeviceByPathLocked(devname);
1680 }
1681 }
1682 event_size = sizeof(*event) + event->len;
1683 res -= event_size;
1684 event_pos += event_size;
1685 }
1686 return 0;
1687}
1688
1689status_t EventHub::scanDirLocked(const char *dirname)
1690{
1691 char devname[PATH_MAX];
1692 char *filename;
1693 DIR *dir;
1694 struct dirent *de;
1695 dir = opendir(dirname);
Yi Kong9b14ac62018-07-17 13:48:38 -07001696 if(dir == nullptr)
Michael Wrightd02c5b62014-02-10 15:10:22 -08001697 return -1;
1698 strcpy(devname, dirname);
1699 filename = devname + strlen(devname);
1700 *filename++ = '/';
1701 while((de = readdir(dir))) {
1702 if(de->d_name[0] == '.' &&
1703 (de->d_name[1] == '\0' ||
1704 (de->d_name[1] == '.' && de->d_name[2] == '\0')))
1705 continue;
1706 strcpy(filename, de->d_name);
1707 openDeviceLocked(devname);
1708 }
1709 closedir(dir);
1710 return 0;
1711}
1712
1713void EventHub::requestReopenDevices() {
1714 ALOGV("requestReopenDevices() called");
1715
1716 AutoMutex _l(mLock);
1717 mNeedToReopenDevices = true;
1718}
1719
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001720void EventHub::dump(std::string& dump) {
1721 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001722
1723 { // acquire lock
1724 AutoMutex _l(mLock);
1725
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001726 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001727
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001728 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001729
1730 for (size_t i = 0; i < mDevices.size(); i++) {
1731 const Device* device = mDevices.valueAt(i);
1732 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001733 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001734 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001735 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001736 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001737 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001738 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001739 dump += StringPrintf(INDENT3 "Classes: 0x%08x\n", device->classes);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001740 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001741 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001742 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
1743 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001744 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001745 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001746 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08001747 "product=0x%04x, version=0x%04x\n",
1748 device->identifier.bus, device->identifier.vendor,
1749 device->identifier.product, device->identifier.version);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001750 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001751 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001752 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001753 device->keyMap.keyCharacterMapFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001754 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001755 device->configurationFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001756 dump += StringPrintf(INDENT3 "HaveKeyboardLayoutOverlay: %s\n",
Yi Kong9b14ac62018-07-17 13:48:38 -07001757 toString(device->overlayKeyMap != nullptr));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001758 }
1759 } // release lock
1760}
1761
1762void EventHub::monitor() {
1763 // Acquire and release the lock to ensure that the event hub has not deadlocked.
1764 mLock.lock();
1765 mLock.unlock();
1766}
1767
1768
1769}; // namespace android