blob: aab83ea31ce04b7a09349139a561ec4e0940a579 [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 Vishniakoue54cb852017-03-21 17:48:16 -0700150 timestampOverrideSec(0), timestampOverrideUsec(0), enabled(true),
151 isVirtual(fd < 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800152 memset(keyBitmask, 0, sizeof(keyBitmask));
153 memset(absBitmask, 0, sizeof(absBitmask));
154 memset(relBitmask, 0, sizeof(relBitmask));
155 memset(swBitmask, 0, sizeof(swBitmask));
156 memset(ledBitmask, 0, sizeof(ledBitmask));
157 memset(ffBitmask, 0, sizeof(ffBitmask));
158 memset(propBitmask, 0, sizeof(propBitmask));
159}
160
161EventHub::Device::~Device() {
162 close();
163 delete configuration;
164 delete virtualKeyMap;
165}
166
167void EventHub::Device::close() {
168 if (fd >= 0) {
169 ::close(fd);
170 fd = -1;
171 }
172}
173
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700174status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100175 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700176 if(fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100177 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700178 return -errno;
179 }
180 enabled = true;
181 return OK;
182}
183
184status_t EventHub::Device::disable() {
185 close();
186 enabled = false;
187 return OK;
188}
189
190bool EventHub::Device::hasValidFd() {
191 return !isVirtual && enabled;
192}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800193
194// --- EventHub ---
195
Michael Wrightd02c5b62014-02-10 15:10:22 -0800196const int EventHub::EPOLL_SIZE_HINT;
197const int EventHub::EPOLL_MAX_EVENTS;
198
199EventHub::EventHub(void) :
200 mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD), mNextDeviceId(1), mControllerNumbers(),
Yi Kong9b14ac62018-07-17 13:48:38 -0700201 mOpeningDevices(nullptr), mClosingDevices(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800202 mNeedToSendFinishedDeviceScan(false),
203 mNeedToReopenDevices(false), mNeedToScanDevices(true),
204 mPendingEventCount(0), mPendingEventIndex(0), mPendingINotify(false) {
205 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
206
207 mEpollFd = epoll_create(EPOLL_SIZE_HINT);
208 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance. errno=%d", errno);
209
210 mINotifyFd = inotify_init();
211 int result = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
212 LOG_ALWAYS_FATAL_IF(result < 0, "Could not register INotify for %s. errno=%d",
213 DEVICE_PATH, errno);
214
215 struct epoll_event eventItem;
216 memset(&eventItem, 0, sizeof(eventItem));
217 eventItem.events = EPOLLIN;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700218 eventItem.data.fd = mINotifyFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800219 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
220 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
221
222 int wakeFds[2];
223 result = pipe(wakeFds);
224 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
225
226 mWakeReadPipeFd = wakeFds[0];
227 mWakeWritePipeFd = wakeFds[1];
228
229 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
230 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
231 errno);
232
233 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
234 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
235 errno);
236
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700237 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800238 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
239 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
240 errno);
241
242 int major, minor;
243 getLinuxRelease(&major, &minor);
244 // EPOLLWAKEUP was introduced in kernel 3.5
245 mUsingEpollWakeup = major > 3 || (major == 3 && minor >= 5);
246}
247
248EventHub::~EventHub(void) {
249 closeAllDevicesLocked();
250
251 while (mClosingDevices) {
252 Device* device = mClosingDevices;
253 mClosingDevices = device->next;
254 delete device;
255 }
256
257 ::close(mEpollFd);
258 ::close(mINotifyFd);
259 ::close(mWakeReadPipeFd);
260 ::close(mWakeWritePipeFd);
261
262 release_wake_lock(WAKE_LOCK_ID);
263}
264
265InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
266 AutoMutex _l(mLock);
267 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700268 if (device == nullptr) return InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800269 return device->identifier;
270}
271
272uint32_t EventHub::getDeviceClasses(int32_t deviceId) const {
273 AutoMutex _l(mLock);
274 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700275 if (device == nullptr) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800276 return device->classes;
277}
278
279int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
280 AutoMutex _l(mLock);
281 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700282 if (device == nullptr) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800283 return device->controllerNumber;
284}
285
286void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
287 AutoMutex _l(mLock);
288 Device* device = getDeviceLocked(deviceId);
289 if (device && device->configuration) {
290 *outConfiguration = *device->configuration;
291 } else {
292 outConfiguration->clear();
293 }
294}
295
296status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
297 RawAbsoluteAxisInfo* outAxisInfo) const {
298 outAxisInfo->clear();
299
300 if (axis >= 0 && axis <= ABS_MAX) {
301 AutoMutex _l(mLock);
302
303 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700304 if (device && device->hasValidFd() && test_bit(axis, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800305 struct input_absinfo info;
306 if(ioctl(device->fd, EVIOCGABS(axis), &info)) {
307 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100308 axis, device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800309 return -errno;
310 }
311
312 if (info.minimum != info.maximum) {
313 outAxisInfo->valid = true;
314 outAxisInfo->minValue = info.minimum;
315 outAxisInfo->maxValue = info.maximum;
316 outAxisInfo->flat = info.flat;
317 outAxisInfo->fuzz = info.fuzz;
318 outAxisInfo->resolution = info.resolution;
319 }
320 return OK;
321 }
322 }
323 return -1;
324}
325
326bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
327 if (axis >= 0 && axis <= REL_MAX) {
328 AutoMutex _l(mLock);
329
330 Device* device = getDeviceLocked(deviceId);
331 if (device) {
332 return test_bit(axis, device->relBitmask);
333 }
334 }
335 return false;
336}
337
338bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
339 if (property >= 0 && property <= INPUT_PROP_MAX) {
340 AutoMutex _l(mLock);
341
342 Device* device = getDeviceLocked(deviceId);
343 if (device) {
344 return test_bit(property, device->propBitmask);
345 }
346 }
347 return false;
348}
349
350int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
351 if (scanCode >= 0 && scanCode <= KEY_MAX) {
352 AutoMutex _l(mLock);
353
354 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700355 if (device && device->hasValidFd() && test_bit(scanCode, device->keyBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800356 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
357 memset(keyState, 0, sizeof(keyState));
358 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
359 return test_bit(scanCode, keyState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
360 }
361 }
362 }
363 return AKEY_STATE_UNKNOWN;
364}
365
366int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
367 AutoMutex _l(mLock);
368
369 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700370 if (device && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800371 Vector<int32_t> scanCodes;
372 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode, &scanCodes);
373 if (scanCodes.size() != 0) {
374 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
375 memset(keyState, 0, sizeof(keyState));
376 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
377 for (size_t i = 0; i < scanCodes.size(); i++) {
378 int32_t sc = scanCodes.itemAt(i);
379 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, keyState)) {
380 return AKEY_STATE_DOWN;
381 }
382 }
383 return AKEY_STATE_UP;
384 }
385 }
386 }
387 return AKEY_STATE_UNKNOWN;
388}
389
390int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
391 if (sw >= 0 && sw <= SW_MAX) {
392 AutoMutex _l(mLock);
393
394 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700395 if (device && device->hasValidFd() && test_bit(sw, device->swBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800396 uint8_t swState[sizeof_bit_array(SW_MAX + 1)];
397 memset(swState, 0, sizeof(swState));
398 if (ioctl(device->fd, EVIOCGSW(sizeof(swState)), swState) >= 0) {
399 return test_bit(sw, swState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
400 }
401 }
402 }
403 return AKEY_STATE_UNKNOWN;
404}
405
406status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
407 *outValue = 0;
408
409 if (axis >= 0 && axis <= ABS_MAX) {
410 AutoMutex _l(mLock);
411
412 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700413 if (device && device->hasValidFd() && test_bit(axis, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800414 struct input_absinfo info;
415 if(ioctl(device->fd, EVIOCGABS(axis), &info)) {
416 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100417 axis, device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800418 return -errno;
419 }
420
421 *outValue = info.value;
422 return OK;
423 }
424 }
425 return -1;
426}
427
428bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes,
429 const int32_t* keyCodes, uint8_t* outFlags) const {
430 AutoMutex _l(mLock);
431
432 Device* device = getDeviceLocked(deviceId);
433 if (device && device->keyMap.haveKeyLayout()) {
434 Vector<int32_t> scanCodes;
435 for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) {
436 scanCodes.clear();
437
438 status_t err = device->keyMap.keyLayoutMap->findScanCodesForKey(
439 keyCodes[codeIndex], &scanCodes);
440 if (! err) {
441 // check the possible scan codes identified by the layout map against the
442 // map of codes actually emitted by the driver
443 for (size_t sc = 0; sc < scanCodes.size(); sc++) {
444 if (test_bit(scanCodes[sc], device->keyBitmask)) {
445 outFlags[codeIndex] = 1;
446 break;
447 }
448 }
449 }
450 }
451 return true;
452 }
453 return false;
454}
455
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700456status_t EventHub::mapKey(int32_t deviceId,
457 int32_t scanCode, int32_t usageCode, int32_t metaState,
458 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800459 AutoMutex _l(mLock);
460 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700461 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800462
463 if (device) {
464 // Check the key character map first.
465 sp<KeyCharacterMap> kcm = device->getKeyCharacterMap();
Yi Kong9b14ac62018-07-17 13:48:38 -0700466 if (kcm != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800467 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
468 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700469 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800470 }
471 }
472
473 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700474 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800475 if (!device->keyMap.keyLayoutMap->mapKey(
476 scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700477 status = NO_ERROR;
478 }
479 }
480
481 if (status == NO_ERROR) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700482 if (kcm != nullptr) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700483 kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState);
484 } else {
485 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800486 }
487 }
488 }
489
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700490 if (status != NO_ERROR) {
491 *outKeycode = 0;
492 *outFlags = 0;
493 *outMetaState = metaState;
494 }
495
496 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800497}
498
499status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
500 AutoMutex _l(mLock);
501 Device* device = getDeviceLocked(deviceId);
502
503 if (device && device->keyMap.haveKeyLayout()) {
504 status_t err = device->keyMap.keyLayoutMap->mapAxis(scanCode, outAxisInfo);
505 if (err == NO_ERROR) {
506 return NO_ERROR;
507 }
508 }
509
510 return NAME_NOT_FOUND;
511}
512
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100513void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800514 AutoMutex _l(mLock);
515
516 mExcludedDevices = devices;
517}
518
519bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
520 AutoMutex _l(mLock);
521 Device* device = getDeviceLocked(deviceId);
522 if (device && scanCode >= 0 && scanCode <= KEY_MAX) {
523 if (test_bit(scanCode, device->keyBitmask)) {
524 return true;
525 }
526 }
527 return false;
528}
529
530bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
531 AutoMutex _l(mLock);
532 Device* device = getDeviceLocked(deviceId);
533 int32_t sc;
534 if (device && mapLed(device, led, &sc) == NO_ERROR) {
535 if (test_bit(sc, device->ledBitmask)) {
536 return true;
537 }
538 }
539 return false;
540}
541
542void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
543 AutoMutex _l(mLock);
544 Device* device = getDeviceLocked(deviceId);
545 setLedStateLocked(device, led, on);
546}
547
548void EventHub::setLedStateLocked(Device* device, int32_t led, bool on) {
549 int32_t sc;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700550 if (device && device->hasValidFd() && mapLed(device, led, &sc) != NAME_NOT_FOUND) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800551 struct input_event ev;
552 ev.time.tv_sec = 0;
553 ev.time.tv_usec = 0;
554 ev.type = EV_LED;
555 ev.code = sc;
556 ev.value = on ? 1 : 0;
557
558 ssize_t nWrite;
559 do {
560 nWrite = write(device->fd, &ev, sizeof(struct input_event));
561 } while (nWrite == -1 && errno == EINTR);
562 }
563}
564
565void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
566 Vector<VirtualKeyDefinition>& outVirtualKeys) const {
567 outVirtualKeys.clear();
568
569 AutoMutex _l(mLock);
570 Device* device = getDeviceLocked(deviceId);
571 if (device && device->virtualKeyMap) {
572 outVirtualKeys.appendVector(device->virtualKeyMap->getVirtualKeys());
573 }
574}
575
576sp<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
577 AutoMutex _l(mLock);
578 Device* device = getDeviceLocked(deviceId);
579 if (device) {
580 return device->getKeyCharacterMap();
581 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700582 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800583}
584
585bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId,
586 const sp<KeyCharacterMap>& map) {
587 AutoMutex _l(mLock);
588 Device* device = getDeviceLocked(deviceId);
589 if (device) {
590 if (map != device->overlayKeyMap) {
591 device->overlayKeyMap = map;
592 device->combinedKeyMap = KeyCharacterMap::combine(
593 device->keyMap.keyCharacterMap, map);
594 return true;
595 }
596 }
597 return false;
598}
599
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100600static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
601 std::string rawDescriptor;
602 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800603 identifier.product);
604 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100605 if (!identifier.uniqueId.empty()) {
606 rawDescriptor += "uniqueId:";
607 rawDescriptor += identifier.uniqueId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800608 } else if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100609 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800610 }
611
612 if (identifier.vendor == 0 && identifier.product == 0) {
613 // If we don't know the vendor and product id, then the device is probably
614 // built-in so we need to rely on other information to uniquely identify
615 // the input device. Usually we try to avoid relying on the device name or
616 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100617 if (!identifier.name.empty()) {
618 rawDescriptor += "name:";
619 rawDescriptor += identifier.name;
620 } else if (!identifier.location.empty()) {
621 rawDescriptor += "location:";
622 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800623 }
624 }
625 identifier.descriptor = sha1(rawDescriptor);
626 return rawDescriptor;
627}
628
629void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
630 // Compute a device descriptor that uniquely identifies the device.
631 // The descriptor is assumed to be a stable identifier. Its value should not
632 // change between reboots, reconnections, firmware updates or new releases
633 // of Android. In practice we sometimes get devices that cannot be uniquely
634 // identified. In this case we enforce uniqueness between connected devices.
635 // Ideally, we also want the descriptor to be short and relatively opaque.
636
637 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100638 std::string rawDescriptor = generateDescriptor(identifier);
639 if (identifier.uniqueId.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800640 // If it didn't have a unique id check for conflicts and enforce
641 // uniqueness if necessary.
Yi Kong9b14ac62018-07-17 13:48:38 -0700642 while(getDeviceByDescriptorLocked(identifier.descriptor) != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800643 identifier.nonce++;
644 rawDescriptor = generateDescriptor(identifier);
645 }
646 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100647 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
648 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800649}
650
651void EventHub::vibrate(int32_t deviceId, nsecs_t duration) {
652 AutoMutex _l(mLock);
653 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700654 if (device && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800655 ff_effect effect;
656 memset(&effect, 0, sizeof(effect));
657 effect.type = FF_RUMBLE;
658 effect.id = device->ffEffectId;
659 effect.u.rumble.strong_magnitude = 0xc000;
660 effect.u.rumble.weak_magnitude = 0xc000;
661 effect.replay.length = (duration + 999999LL) / 1000000LL;
662 effect.replay.delay = 0;
663 if (ioctl(device->fd, EVIOCSFF, &effect)) {
664 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100665 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800666 return;
667 }
668 device->ffEffectId = effect.id;
669
670 struct input_event ev;
671 ev.time.tv_sec = 0;
672 ev.time.tv_usec = 0;
673 ev.type = EV_FF;
674 ev.code = device->ffEffectId;
675 ev.value = 1;
676 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
677 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100678 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800679 return;
680 }
681 device->ffEffectPlaying = true;
682 }
683}
684
685void EventHub::cancelVibrate(int32_t deviceId) {
686 AutoMutex _l(mLock);
687 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700688 if (device && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800689 if (device->ffEffectPlaying) {
690 device->ffEffectPlaying = false;
691
692 struct input_event ev;
693 ev.time.tv_sec = 0;
694 ev.time.tv_usec = 0;
695 ev.type = EV_FF;
696 ev.code = device->ffEffectId;
697 ev.value = 0;
698 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
699 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100700 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800701 return;
702 }
703 }
704 }
705}
706
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100707EventHub::Device* EventHub::getDeviceByDescriptorLocked(const std::string& descriptor) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800708 size_t size = mDevices.size();
709 for (size_t i = 0; i < size; i++) {
710 Device* device = mDevices.valueAt(i);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100711 if (descriptor == device->identifier.descriptor) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800712 return device;
713 }
714 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700715 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800716}
717
718EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
719 if (deviceId == BUILT_IN_KEYBOARD_ID) {
720 deviceId = mBuiltInKeyboardId;
721 }
722 ssize_t index = mDevices.indexOfKey(deviceId);
723 return index >= 0 ? mDevices.valueAt(index) : NULL;
724}
725
726EventHub::Device* EventHub::getDeviceByPathLocked(const char* devicePath) const {
727 for (size_t i = 0; i < mDevices.size(); i++) {
728 Device* device = mDevices.valueAt(i);
729 if (device->path == devicePath) {
730 return device;
731 }
732 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700733 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800734}
735
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700736EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
737 for (size_t i = 0; i < mDevices.size(); i++) {
738 Device* device = mDevices.valueAt(i);
739 if (device->fd == fd) {
740 return device;
741 }
742 }
743 return nullptr;
744}
745
Michael Wrightd02c5b62014-02-10 15:10:22 -0800746size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
747 ALOG_ASSERT(bufferSize >= 1);
748
749 AutoMutex _l(mLock);
750
751 struct input_event readBuffer[bufferSize];
752
753 RawEvent* event = buffer;
754 size_t capacity = bufferSize;
755 bool awoken = false;
756 for (;;) {
757 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
758
759 // Reopen input devices if needed.
760 if (mNeedToReopenDevices) {
761 mNeedToReopenDevices = false;
762
763 ALOGI("Reopening all input devices due to a configuration change.");
764
765 closeAllDevicesLocked();
766 mNeedToScanDevices = true;
767 break; // return to the caller before we actually rescan
768 }
769
770 // Report any devices that had last been added/removed.
771 while (mClosingDevices) {
772 Device* device = mClosingDevices;
773 ALOGV("Reporting device closed: id=%d, name=%s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100774 device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800775 mClosingDevices = device->next;
776 event->when = now;
777 event->deviceId = device->id == mBuiltInKeyboardId ? BUILT_IN_KEYBOARD_ID : device->id;
778 event->type = DEVICE_REMOVED;
779 event += 1;
780 delete device;
781 mNeedToSendFinishedDeviceScan = true;
782 if (--capacity == 0) {
783 break;
784 }
785 }
786
787 if (mNeedToScanDevices) {
788 mNeedToScanDevices = false;
789 scanDevicesLocked();
790 mNeedToSendFinishedDeviceScan = true;
791 }
792
Yi Kong9b14ac62018-07-17 13:48:38 -0700793 while (mOpeningDevices != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800794 Device* device = mOpeningDevices;
795 ALOGV("Reporting device opened: id=%d, name=%s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100796 device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800797 mOpeningDevices = device->next;
798 event->when = now;
799 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
800 event->type = DEVICE_ADDED;
801 event += 1;
802 mNeedToSendFinishedDeviceScan = true;
803 if (--capacity == 0) {
804 break;
805 }
806 }
807
808 if (mNeedToSendFinishedDeviceScan) {
809 mNeedToSendFinishedDeviceScan = false;
810 event->when = now;
811 event->type = FINISHED_DEVICE_SCAN;
812 event += 1;
813 if (--capacity == 0) {
814 break;
815 }
816 }
817
818 // Grab the next input event.
819 bool deviceChanged = false;
820 while (mPendingEventIndex < mPendingEventCount) {
821 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700822 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800823 if (eventItem.events & EPOLLIN) {
824 mPendingINotify = true;
825 } else {
826 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
827 }
828 continue;
829 }
830
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700831 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800832 if (eventItem.events & EPOLLIN) {
833 ALOGV("awoken after wake()");
834 awoken = true;
835 char buffer[16];
836 ssize_t nRead;
837 do {
838 nRead = read(mWakeReadPipeFd, buffer, sizeof(buffer));
839 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(buffer));
840 } else {
841 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
842 eventItem.events);
843 }
844 continue;
845 }
846
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700847 Device* device = getDeviceByFdLocked(eventItem.data.fd);
848 if (device == nullptr) {
849 ALOGW("Received unexpected epoll event 0x%08x for unknown device fd %d.",
850 eventItem.events, eventItem.data.fd);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800851 continue;
852 }
853
Michael Wrightd02c5b62014-02-10 15:10:22 -0800854 if (eventItem.events & EPOLLIN) {
855 int32_t readSize = read(device->fd, readBuffer,
856 sizeof(struct input_event) * capacity);
857 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
858 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -0700859 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
860 " bufferSize: %zu capacity: %zu errno: %d)\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800861 device->fd, readSize, bufferSize, capacity, errno);
862 deviceChanged = true;
863 closeDeviceLocked(device);
864 } else if (readSize < 0) {
865 if (errno != EAGAIN && errno != EINTR) {
866 ALOGW("could not get event (errno=%d)", errno);
867 }
868 } else if ((readSize % sizeof(struct input_event)) != 0) {
869 ALOGE("could not get event (wrong size: %d)", readSize);
870 } else {
871 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
872
873 size_t count = size_t(readSize) / sizeof(struct input_event);
874 for (size_t i = 0; i < count; i++) {
875 struct input_event& iev = readBuffer[i];
876 ALOGV("%s got: time=%d.%06d, type=%d, code=%d, value=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100877 device->path.c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800878 (int) iev.time.tv_sec, (int) iev.time.tv_usec,
879 iev.type, iev.code, iev.value);
880
881 // Some input devices may have a better concept of the time
882 // when an input event was actually generated than the kernel
883 // which simply timestamps all events on entry to evdev.
884 // This is a custom Android extension of the input protocol
885 // mainly intended for use with uinput based device drivers.
886 if (iev.type == EV_MSC) {
887 if (iev.code == MSC_ANDROID_TIME_SEC) {
888 device->timestampOverrideSec = iev.value;
889 continue;
890 } else if (iev.code == MSC_ANDROID_TIME_USEC) {
891 device->timestampOverrideUsec = iev.value;
892 continue;
893 }
894 }
895 if (device->timestampOverrideSec || device->timestampOverrideUsec) {
896 iev.time.tv_sec = device->timestampOverrideSec;
897 iev.time.tv_usec = device->timestampOverrideUsec;
898 if (iev.type == EV_SYN && iev.code == SYN_REPORT) {
899 device->timestampOverrideSec = 0;
900 device->timestampOverrideUsec = 0;
901 }
902 ALOGV("applied override time %d.%06d",
903 int(iev.time.tv_sec), int(iev.time.tv_usec));
904 }
905
Michael Wrightd02c5b62014-02-10 15:10:22 -0800906 // Use the time specified in the event instead of the current time
907 // so that downstream code can get more accurate estimates of
908 // event dispatch latency from the time the event is enqueued onto
909 // the evdev client buffer.
910 //
911 // The event's timestamp fortuitously uses the same monotonic clock
912 // time base as the rest of Android. The kernel event device driver
913 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
914 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
915 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
916 // system call that also queries ktime_get_ts().
917 event->when = nsecs_t(iev.time.tv_sec) * 1000000000LL
918 + nsecs_t(iev.time.tv_usec) * 1000LL;
Mark Salyzyn5aa26b22014-06-10 13:07:44 -0700919 ALOGV("event time %" PRId64 ", now %" PRId64, event->when, now);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800920
921 // Bug 7291243: Add a guard in case the kernel generates timestamps
922 // that appear to be far into the future because they were generated
923 // using the wrong clock source.
924 //
925 // This can happen because when the input device is initially opened
926 // it has a default clock source of CLOCK_REALTIME. Any input events
927 // enqueued right after the device is opened will have timestamps
928 // generated using CLOCK_REALTIME. We later set the clock source
929 // to CLOCK_MONOTONIC but it is already too late.
930 //
931 // Invalid input event timestamps can result in ANRs, crashes and
932 // and other issues that are hard to track down. We must not let them
933 // propagate through the system.
934 //
935 // Log a warning so that we notice the problem and recover gracefully.
936 if (event->when >= now + 10 * 1000000000LL) {
937 // Double-check. Time may have moved on.
938 nsecs_t time = systemTime(SYSTEM_TIME_MONOTONIC);
939 if (event->when > time) {
940 ALOGW("An input event from %s has a timestamp that appears to "
941 "have been generated using the wrong clock source "
942 "(expected CLOCK_MONOTONIC): "
Mark Salyzyn5aa26b22014-06-10 13:07:44 -0700943 "event time %" PRId64 ", current time %" PRId64
944 ", call time %" PRId64 ". "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800945 "Using current time instead.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100946 device->path.c_str(), event->when, time, now);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800947 event->when = time;
948 } else {
949 ALOGV("Event time is ok but failed the fast path and required "
950 "an extra call to systemTime: "
Mark Salyzyn5aa26b22014-06-10 13:07:44 -0700951 "event time %" PRId64 ", current time %" PRId64
952 ", call time %" PRId64 ".",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800953 event->when, time, now);
954 }
955 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800956 event->deviceId = deviceId;
957 event->type = iev.type;
958 event->code = iev.code;
959 event->value = iev.value;
960 event += 1;
961 capacity -= 1;
962 }
963 if (capacity == 0) {
964 // The result buffer is full. Reset the pending event index
965 // so we will try to read the device again on the next iteration.
966 mPendingEventIndex -= 1;
967 break;
968 }
969 }
970 } else if (eventItem.events & EPOLLHUP) {
971 ALOGI("Removing device %s due to epoll hang-up event.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100972 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800973 deviceChanged = true;
974 closeDeviceLocked(device);
975 } else {
976 ALOGW("Received unexpected epoll event 0x%08x for device %s.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100977 eventItem.events, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800978 }
979 }
980
981 // readNotify() will modify the list of devices so this must be done after
982 // processing all other events to ensure that we read all remaining events
983 // before closing the devices.
984 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
985 mPendingINotify = false;
986 readNotifyLocked();
987 deviceChanged = true;
988 }
989
990 // Report added or removed devices immediately.
991 if (deviceChanged) {
992 continue;
993 }
994
995 // Return now if we have collected any events or if we were explicitly awoken.
996 if (event != buffer || awoken) {
997 break;
998 }
999
1000 // Poll for events. Mind the wake lock dance!
1001 // We hold a wake lock at all times except during epoll_wait(). This works due to some
1002 // subtle choreography. When a device driver has pending (unread) events, it acquires
1003 // a kernel wake lock. However, once the last pending event has been read, the device
1004 // driver will release the kernel wake lock. To prevent the system from going to sleep
1005 // when this happens, the EventHub holds onto its own user wake lock while the client
1006 // is processing events. Thus the system can only sleep if there are no events
1007 // pending or currently being processed.
1008 //
1009 // The timeout is advisory only. If the device is asleep, it will not wake just to
1010 // service the timeout.
1011 mPendingEventIndex = 0;
1012
1013 mLock.unlock(); // release lock before poll, must be before release_wake_lock
1014 release_wake_lock(WAKE_LOCK_ID);
1015
1016 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1017
1018 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
1019 mLock.lock(); // reacquire lock after poll, must be after acquire_wake_lock
1020
1021 if (pollResult == 0) {
1022 // Timed out.
1023 mPendingEventCount = 0;
1024 break;
1025 }
1026
1027 if (pollResult < 0) {
1028 // An error occurred.
1029 mPendingEventCount = 0;
1030
1031 // Sleep after errors to avoid locking up the system.
1032 // Hopefully the error is transient.
1033 if (errno != EINTR) {
1034 ALOGW("poll failed (errno=%d)\n", errno);
1035 usleep(100000);
1036 }
1037 } else {
1038 // Some events occurred.
1039 mPendingEventCount = size_t(pollResult);
1040 }
1041 }
1042
1043 // All done, return the number of events we read.
1044 return event - buffer;
1045}
1046
1047void EventHub::wake() {
1048 ALOGV("wake() called");
1049
1050 ssize_t nWrite;
1051 do {
1052 nWrite = write(mWakeWritePipeFd, "W", 1);
1053 } while (nWrite == -1 && errno == EINTR);
1054
1055 if (nWrite != 1 && errno != EAGAIN) {
1056 ALOGW("Could not write wake signal, errno=%d", errno);
1057 }
1058}
1059
1060void EventHub::scanDevicesLocked() {
1061 status_t res = scanDirLocked(DEVICE_PATH);
1062 if(res < 0) {
1063 ALOGE("scan dir failed for %s\n", DEVICE_PATH);
1064 }
1065 if (mDevices.indexOfKey(VIRTUAL_KEYBOARD_ID) < 0) {
1066 createVirtualKeyboardLocked();
1067 }
1068}
1069
1070// ----------------------------------------------------------------------------
1071
1072static bool containsNonZeroByte(const uint8_t* array, uint32_t startIndex, uint32_t endIndex) {
1073 const uint8_t* end = array + endIndex;
1074 array += startIndex;
1075 while (array != end) {
1076 if (*(array++) != 0) {
1077 return true;
1078 }
1079 }
1080 return false;
1081}
1082
1083static const int32_t GAMEPAD_KEYCODES[] = {
1084 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C,
1085 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z,
1086 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1,
1087 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2,
1088 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR,
1089 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001090};
1091
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001092status_t EventHub::registerDeviceForEpollLocked(Device* device) {
1093 struct epoll_event eventItem;
1094 memset(&eventItem, 0, sizeof(eventItem));
1095 eventItem.events = EPOLLIN;
1096 if (mUsingEpollWakeup) {
1097 eventItem.events |= EPOLLWAKEUP;
1098 }
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001099 eventItem.data.fd = device->fd;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001100 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, device->fd, &eventItem)) {
1101 ALOGE("Could not add device fd to epoll instance. errno=%d", errno);
1102 return -errno;
1103 }
1104 return OK;
1105}
1106
1107status_t EventHub::unregisterDeviceFromEpollLocked(Device* device) {
1108 if (device->hasValidFd()) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001109 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, device->fd, nullptr)) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001110 ALOGW("Could not remove device fd from epoll instance. errno=%d", errno);
1111 return -errno;
1112 }
1113 }
1114 return OK;
1115}
1116
Michael Wrightd02c5b62014-02-10 15:10:22 -08001117status_t EventHub::openDeviceLocked(const char *devicePath) {
1118 char buffer[80];
1119
1120 ALOGV("Opening device: %s", devicePath);
1121
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001122 int fd = open(devicePath, O_RDWR | O_CLOEXEC | O_NONBLOCK);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001123 if(fd < 0) {
1124 ALOGE("could not open %s, %s\n", devicePath, strerror(errno));
1125 return -1;
1126 }
1127
1128 InputDeviceIdentifier identifier;
1129
1130 // Get device name.
1131 if(ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
1132 //fprintf(stderr, "could not get device name for %s, %s\n", devicePath, strerror(errno));
1133 } else {
1134 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001135 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001136 }
1137
1138 // Check to see if the device is on our excluded list
1139 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001140 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001141 if (identifier.name == item) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001142 ALOGI("ignoring event id %s driver %s\n", devicePath, item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001143 close(fd);
1144 return -1;
1145 }
1146 }
1147
1148 // Get device driver version.
1149 int driverVersion;
1150 if(ioctl(fd, EVIOCGVERSION, &driverVersion)) {
1151 ALOGE("could not get driver version for %s, %s\n", devicePath, strerror(errno));
1152 close(fd);
1153 return -1;
1154 }
1155
1156 // Get device identifier.
1157 struct input_id inputId;
1158 if(ioctl(fd, EVIOCGID, &inputId)) {
1159 ALOGE("could not get device input id for %s, %s\n", devicePath, strerror(errno));
1160 close(fd);
1161 return -1;
1162 }
1163 identifier.bus = inputId.bustype;
1164 identifier.product = inputId.product;
1165 identifier.vendor = inputId.vendor;
1166 identifier.version = inputId.version;
1167
1168 // Get device physical location.
1169 if(ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
1170 //fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
1171 } else {
1172 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001173 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001174 }
1175
1176 // Get device unique id.
1177 if(ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
1178 //fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
1179 } else {
1180 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001181 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001182 }
1183
1184 // Fill in the descriptor.
1185 assignDescriptorLocked(identifier);
1186
Michael Wrightd02c5b62014-02-10 15:10:22 -08001187 // Allocate device. (The device object takes ownership of the fd at this point.)
1188 int32_t deviceId = mNextDeviceId++;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001189 Device* device = new Device(fd, deviceId, devicePath, identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001190
1191 ALOGV("add device %d: %s\n", deviceId, devicePath);
1192 ALOGV(" bus: %04x\n"
1193 " vendor %04x\n"
1194 " product %04x\n"
1195 " version %04x\n",
1196 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001197 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
1198 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
1199 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
1200 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001201 ALOGV(" driver: v%d.%d.%d\n",
1202 driverVersion >> 16, (driverVersion >> 8) & 0xff, driverVersion & 0xff);
1203
1204 // Load the configuration file for the device.
1205 loadConfigurationLocked(device);
1206
1207 // Figure out the kinds of events the device reports.
1208 ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(device->keyBitmask)), device->keyBitmask);
1209 ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(device->absBitmask)), device->absBitmask);
1210 ioctl(fd, EVIOCGBIT(EV_REL, sizeof(device->relBitmask)), device->relBitmask);
1211 ioctl(fd, EVIOCGBIT(EV_SW, sizeof(device->swBitmask)), device->swBitmask);
1212 ioctl(fd, EVIOCGBIT(EV_LED, sizeof(device->ledBitmask)), device->ledBitmask);
1213 ioctl(fd, EVIOCGBIT(EV_FF, sizeof(device->ffBitmask)), device->ffBitmask);
1214 ioctl(fd, EVIOCGPROP(sizeof(device->propBitmask)), device->propBitmask);
1215
1216 // See if this is a keyboard. Ignore everything in the button range except for
1217 // joystick and gamepad buttons which are handled like keyboards for the most part.
1218 bool haveKeyboardKeys = containsNonZeroByte(device->keyBitmask, 0, sizeof_bit_array(BTN_MISC))
1219 || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(KEY_OK),
1220 sizeof_bit_array(KEY_MAX + 1));
1221 bool haveGamepadButtons = containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_MISC),
1222 sizeof_bit_array(BTN_MOUSE))
1223 || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_JOYSTICK),
1224 sizeof_bit_array(BTN_DIGI));
1225 if (haveKeyboardKeys || haveGamepadButtons) {
1226 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1227 }
1228
1229 // See if this is a cursor device such as a trackball or mouse.
1230 if (test_bit(BTN_MOUSE, device->keyBitmask)
1231 && test_bit(REL_X, device->relBitmask)
1232 && test_bit(REL_Y, device->relBitmask)) {
1233 device->classes |= INPUT_DEVICE_CLASS_CURSOR;
1234 }
1235
Prashant Malani1941ff52015-08-11 18:29:28 -07001236 // See if this is a rotary encoder type device.
1237 String8 deviceType = String8();
1238 if (device->configuration &&
1239 device->configuration->tryGetProperty(String8("device.type"), deviceType)) {
1240 if (!deviceType.compare(String8("rotaryEncoder"))) {
1241 device->classes |= INPUT_DEVICE_CLASS_ROTARY_ENCODER;
1242 }
1243 }
1244
Michael Wrightd02c5b62014-02-10 15:10:22 -08001245 // See if this is a touch pad.
1246 // Is this a new modern multi-touch driver?
1247 if (test_bit(ABS_MT_POSITION_X, device->absBitmask)
1248 && test_bit(ABS_MT_POSITION_Y, device->absBitmask)) {
1249 // Some joysticks such as the PS3 controller report axes that conflict
1250 // with the ABS_MT range. Try to confirm that the device really is
1251 // a touch screen.
1252 if (test_bit(BTN_TOUCH, device->keyBitmask) || !haveGamepadButtons) {
1253 device->classes |= INPUT_DEVICE_CLASS_TOUCH | INPUT_DEVICE_CLASS_TOUCH_MT;
1254 }
1255 // Is this an old style single-touch driver?
1256 } else if (test_bit(BTN_TOUCH, device->keyBitmask)
1257 && test_bit(ABS_X, device->absBitmask)
1258 && test_bit(ABS_Y, device->absBitmask)) {
1259 device->classes |= INPUT_DEVICE_CLASS_TOUCH;
Michael Wright842500e2015-03-13 17:32:02 -07001260 // Is this a BT stylus?
1261 } else if ((test_bit(ABS_PRESSURE, device->absBitmask) ||
1262 test_bit(BTN_TOUCH, device->keyBitmask))
1263 && !test_bit(ABS_X, device->absBitmask)
1264 && !test_bit(ABS_Y, device->absBitmask)) {
1265 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
1266 // Keyboard will try to claim some of the buttons but we really want to reserve those so we
1267 // can fuse it with the touch screen data, so just take them back. Note this means an
1268 // external stylus cannot also be a keyboard device.
1269 device->classes &= ~INPUT_DEVICE_CLASS_KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001270 }
1271
1272 // See if this device is a joystick.
1273 // Assumes that joysticks always have gamepad buttons in order to distinguish them
1274 // from other devices such as accelerometers that also have absolute axes.
1275 if (haveGamepadButtons) {
1276 uint32_t assumedClasses = device->classes | INPUT_DEVICE_CLASS_JOYSTICK;
1277 for (int i = 0; i <= ABS_MAX; i++) {
1278 if (test_bit(i, device->absBitmask)
1279 && (getAbsAxisUsage(i, assumedClasses) & INPUT_DEVICE_CLASS_JOYSTICK)) {
1280 device->classes = assumedClasses;
1281 break;
1282 }
1283 }
1284 }
1285
1286 // Check whether this device has switches.
1287 for (int i = 0; i <= SW_MAX; i++) {
1288 if (test_bit(i, device->swBitmask)) {
1289 device->classes |= INPUT_DEVICE_CLASS_SWITCH;
1290 break;
1291 }
1292 }
1293
1294 // Check whether this device supports the vibrator.
1295 if (test_bit(FF_RUMBLE, device->ffBitmask)) {
1296 device->classes |= INPUT_DEVICE_CLASS_VIBRATOR;
1297 }
1298
1299 // Configure virtual keys.
1300 if ((device->classes & INPUT_DEVICE_CLASS_TOUCH)) {
1301 // Load the virtual keys for the touch screen, if any.
1302 // We do this now so that we can make sure to load the keymap if necessary.
1303 status_t status = loadVirtualKeyMapLocked(device);
1304 if (!status) {
1305 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1306 }
1307 }
1308
1309 // Load the key map.
1310 // We need to do this for joysticks too because the key layout may specify axes.
1311 status_t keyMapStatus = NAME_NOT_FOUND;
1312 if (device->classes & (INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_JOYSTICK)) {
1313 // Load the keymap for the device.
1314 keyMapStatus = loadKeyMapLocked(device);
1315 }
1316
1317 // Configure the keyboard, gamepad or virtual keyboard.
1318 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1319 // Register the keyboard as a built-in keyboard if it is eligible.
1320 if (!keyMapStatus
1321 && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD
1322 && isEligibleBuiltInKeyboard(device->identifier,
1323 device->configuration, &device->keyMap)) {
1324 mBuiltInKeyboardId = device->id;
1325 }
1326
1327 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
1328 if (hasKeycodeLocked(device, AKEYCODE_Q)) {
1329 device->classes |= INPUT_DEVICE_CLASS_ALPHAKEY;
1330 }
1331
1332 // See if this device has a DPAD.
1333 if (hasKeycodeLocked(device, AKEYCODE_DPAD_UP) &&
1334 hasKeycodeLocked(device, AKEYCODE_DPAD_DOWN) &&
1335 hasKeycodeLocked(device, AKEYCODE_DPAD_LEFT) &&
1336 hasKeycodeLocked(device, AKEYCODE_DPAD_RIGHT) &&
1337 hasKeycodeLocked(device, AKEYCODE_DPAD_CENTER)) {
1338 device->classes |= INPUT_DEVICE_CLASS_DPAD;
1339 }
1340
1341 // See if this device has a gamepad.
1342 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES)/sizeof(GAMEPAD_KEYCODES[0]); i++) {
1343 if (hasKeycodeLocked(device, GAMEPAD_KEYCODES[i])) {
1344 device->classes |= INPUT_DEVICE_CLASS_GAMEPAD;
1345 break;
1346 }
1347 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001348 }
1349
1350 // If the device isn't recognized as something we handle, don't monitor it.
1351 if (device->classes == 0) {
1352 ALOGV("Dropping device: id=%d, path='%s', name='%s'",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001353 deviceId, devicePath, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001354 delete device;
1355 return -1;
1356 }
1357
Tim Kilbourn063ff532015-04-08 10:26:18 -07001358 // Determine whether the device has a mic.
1359 if (deviceHasMicLocked(device)) {
1360 device->classes |= INPUT_DEVICE_CLASS_MIC;
1361 }
1362
Michael Wrightd02c5b62014-02-10 15:10:22 -08001363 // Determine whether the device is external or internal.
1364 if (isExternalDeviceLocked(device)) {
1365 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL;
1366 }
1367
Michael Wright42f2c6a2014-03-12 10:33:03 -07001368 if (device->classes & (INPUT_DEVICE_CLASS_JOYSTICK | INPUT_DEVICE_CLASS_DPAD)
1369 && device->classes & INPUT_DEVICE_CLASS_GAMEPAD) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001370 device->controllerNumber = getNextControllerNumberLocked(device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001371 setLedForControllerLocked(device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001372 }
1373
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001374
1375 if (registerDeviceForEpollLocked(device) != OK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001376 delete device;
1377 return -1;
1378 }
1379
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001380 configureFd(device);
1381
1382 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=0x%x, "
1383 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001384 deviceId, fd, devicePath, device->identifier.name.c_str(),
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001385 device->classes,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001386 device->configurationFile.c_str(),
1387 device->keyMap.keyLayoutFile.c_str(),
1388 device->keyMap.keyCharacterMapFile.c_str(),
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001389 toString(mBuiltInKeyboardId == deviceId));
1390
1391 addDeviceLocked(device);
1392 return OK;
1393}
1394
1395void EventHub::configureFd(Device* device) {
1396 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
1397 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1398 // Disable kernel key repeat since we handle it ourselves
1399 unsigned int repeatRate[] = {0, 0};
1400 if (ioctl(device->fd, EVIOCSREP, repeatRate)) {
1401 ALOGW("Unable to disable kernel key repeat for %s: %s",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001402 device->path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001403 }
1404 }
1405
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001406 std::string wakeMechanism = "EPOLLWAKEUP";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001407 if (!mUsingEpollWakeup) {
1408#ifndef EVIOCSSUSPENDBLOCK
1409 // uapi headers don't include EVIOCSSUSPENDBLOCK, and future kernels
1410 // will use an epoll flag instead, so as long as we want to support
1411 // this feature, we need to be prepared to define the ioctl ourselves.
1412#define EVIOCSSUSPENDBLOCK _IOW('E', 0x91, int)
1413#endif
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001414 if (ioctl(device->fd, EVIOCSSUSPENDBLOCK, 1)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001415 wakeMechanism = "<none>";
1416 } else {
1417 wakeMechanism = "EVIOCSSUSPENDBLOCK";
1418 }
1419 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001420 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
1421 // associated with input events. This is important because the input system
1422 // uses the timestamps extensively and assumes they were recorded using the monotonic
1423 // clock.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001424 int clockId = CLOCK_MONOTONIC;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001425 bool usingClockIoctl = !ioctl(device->fd, EVIOCSCLOCKID, &clockId);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001426 ALOGI("wakeMechanism=%s, usingClockIoctl=%s", wakeMechanism.c_str(),
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001427 toString(usingClockIoctl));
1428}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001429
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001430bool EventHub::isDeviceEnabled(int32_t deviceId) {
1431 AutoMutex _l(mLock);
1432 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001433 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001434 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1435 return false;
1436 }
1437 return device->enabled;
1438}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001439
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001440status_t EventHub::enableDevice(int32_t deviceId) {
1441 AutoMutex _l(mLock);
1442 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001443 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001444 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1445 return BAD_VALUE;
1446 }
1447 if (device->enabled) {
1448 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
1449 return OK;
1450 }
1451 status_t result = device->enable();
1452 if (result != OK) {
1453 ALOGE("Failed to enable device %" PRId32, deviceId);
1454 return result;
1455 }
1456
1457 configureFd(device);
1458
1459 return registerDeviceForEpollLocked(device);
1460}
1461
1462status_t EventHub::disableDevice(int32_t deviceId) {
1463 AutoMutex _l(mLock);
1464 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001465 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001466 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1467 return BAD_VALUE;
1468 }
1469 if (!device->enabled) {
1470 ALOGW("Duplicate call to %s, input device already disabled", __func__);
1471 return OK;
1472 }
1473 unregisterDeviceFromEpollLocked(device);
1474 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001475}
1476
1477void EventHub::createVirtualKeyboardLocked() {
1478 InputDeviceIdentifier identifier;
1479 identifier.name = "Virtual";
1480 identifier.uniqueId = "<virtual>";
1481 assignDescriptorLocked(identifier);
1482
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001483 Device* device = new Device(-1, VIRTUAL_KEYBOARD_ID, "<virtual>", identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001484 device->classes = INPUT_DEVICE_CLASS_KEYBOARD
1485 | INPUT_DEVICE_CLASS_ALPHAKEY
1486 | INPUT_DEVICE_CLASS_DPAD
1487 | INPUT_DEVICE_CLASS_VIRTUAL;
1488 loadKeyMapLocked(device);
1489 addDeviceLocked(device);
1490}
1491
1492void EventHub::addDeviceLocked(Device* device) {
1493 mDevices.add(device->id, device);
1494 device->next = mOpeningDevices;
1495 mOpeningDevices = device;
1496}
1497
1498void EventHub::loadConfigurationLocked(Device* device) {
1499 device->configurationFile = getInputDeviceConfigurationFilePathByDeviceIdentifier(
1500 device->identifier, INPUT_DEVICE_CONFIGURATION_FILE_TYPE_CONFIGURATION);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001501 if (device->configurationFile.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001502 ALOGD("No input device configuration file found for device '%s'.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001503 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001504 } else {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001505 status_t status = PropertyMap::load(String8(device->configurationFile.c_str()),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001506 &device->configuration);
1507 if (status) {
1508 ALOGE("Error loading input device configuration file for device '%s'. "
1509 "Using default configuration.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001510 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001511 }
1512 }
1513}
1514
1515status_t EventHub::loadVirtualKeyMapLocked(Device* device) {
1516 // The virtual key map is supplied by the kernel as a system board property file.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001517 std::string path;
1518 path += "/sys/board_properties/virtualkeys.";
1519 path += device->identifier.name;
1520 if (access(path.c_str(), R_OK)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001521 return NAME_NOT_FOUND;
1522 }
1523 return VirtualKeyMap::load(path, &device->virtualKeyMap);
1524}
1525
1526status_t EventHub::loadKeyMapLocked(Device* device) {
1527 return device->keyMap.load(device->identifier, device->configuration);
1528}
1529
1530bool EventHub::isExternalDeviceLocked(Device* device) {
1531 if (device->configuration) {
1532 bool value;
1533 if (device->configuration->tryGetProperty(String8("device.internal"), value)) {
1534 return !value;
1535 }
1536 }
1537 return device->identifier.bus == BUS_USB || device->identifier.bus == BUS_BLUETOOTH;
1538}
1539
Tim Kilbourn063ff532015-04-08 10:26:18 -07001540bool EventHub::deviceHasMicLocked(Device* device) {
1541 if (device->configuration) {
1542 bool value;
1543 if (device->configuration->tryGetProperty(String8("audio.mic"), value)) {
1544 return value;
1545 }
1546 }
1547 return false;
1548}
1549
Michael Wrightd02c5b62014-02-10 15:10:22 -08001550int32_t EventHub::getNextControllerNumberLocked(Device* device) {
1551 if (mControllerNumbers.isFull()) {
1552 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001553 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001554 return 0;
1555 }
1556 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
1557 // one
1558 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
1559}
1560
1561void EventHub::releaseControllerNumberLocked(Device* device) {
1562 int32_t num = device->controllerNumber;
1563 device->controllerNumber= 0;
1564 if (num == 0) {
1565 return;
1566 }
1567 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
1568}
1569
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001570void EventHub::setLedForControllerLocked(Device* device) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001571 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
1572 setLedStateLocked(device, ALED_CONTROLLER_1 + i, device->controllerNumber == i + 1);
1573 }
1574}
1575
1576bool EventHub::hasKeycodeLocked(Device* device, int keycode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001577 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001578 return false;
1579 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001580
Michael Wrightd02c5b62014-02-10 15:10:22 -08001581 Vector<int32_t> scanCodes;
1582 device->keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes);
1583 const size_t N = scanCodes.size();
1584 for (size_t i=0; i<N && i<=KEY_MAX; i++) {
1585 int32_t sc = scanCodes.itemAt(i);
1586 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, device->keyBitmask)) {
1587 return true;
1588 }
1589 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001590
Michael Wrightd02c5b62014-02-10 15:10:22 -08001591 return false;
1592}
1593
1594status_t EventHub::mapLed(Device* device, int32_t led, int32_t* outScanCode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001595 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001596 return NAME_NOT_FOUND;
1597 }
1598
1599 int32_t scanCode;
1600 if(device->keyMap.keyLayoutMap->findScanCodeForLed(led, &scanCode) != NAME_NOT_FOUND) {
1601 if(scanCode >= 0 && scanCode <= LED_MAX && test_bit(scanCode, device->ledBitmask)) {
1602 *outScanCode = scanCode;
1603 return NO_ERROR;
1604 }
1605 }
1606 return NAME_NOT_FOUND;
1607}
1608
1609status_t EventHub::closeDeviceByPathLocked(const char *devicePath) {
1610 Device* device = getDeviceByPathLocked(devicePath);
1611 if (device) {
1612 closeDeviceLocked(device);
1613 return 0;
1614 }
1615 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath);
1616 return -1;
1617}
1618
1619void EventHub::closeAllDevicesLocked() {
1620 while (mDevices.size() > 0) {
1621 closeDeviceLocked(mDevices.valueAt(mDevices.size() - 1));
1622 }
1623}
1624
1625void EventHub::closeDeviceLocked(Device* device) {
1626 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=0x%x\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001627 device->path.c_str(), device->identifier.name.c_str(), device->id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001628 device->fd, device->classes);
1629
1630 if (device->id == mBuiltInKeyboardId) {
1631 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001632 device->path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001633 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
1634 }
1635
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001636 unregisterDeviceFromEpollLocked(device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001637
1638 releaseControllerNumberLocked(device);
1639
1640 mDevices.removeItem(device->id);
1641 device->close();
1642
1643 // Unlink for opening devices list if it is present.
Yi Kong9b14ac62018-07-17 13:48:38 -07001644 Device* pred = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001645 bool found = false;
Yi Kong9b14ac62018-07-17 13:48:38 -07001646 for (Device* entry = mOpeningDevices; entry != nullptr; ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001647 if (entry == device) {
1648 found = true;
1649 break;
1650 }
1651 pred = entry;
1652 entry = entry->next;
1653 }
1654 if (found) {
1655 // Unlink the device from the opening devices list then delete it.
1656 // We don't need to tell the client that the device was closed because
1657 // it does not even know it was opened in the first place.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001658 ALOGI("Device %s was immediately closed after opening.", device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001659 if (pred) {
1660 pred->next = device->next;
1661 } else {
1662 mOpeningDevices = device->next;
1663 }
1664 delete device;
1665 } else {
1666 // Link into closing devices list.
1667 // The device will be deleted later after we have informed the client.
1668 device->next = mClosingDevices;
1669 mClosingDevices = device;
1670 }
1671}
1672
1673status_t EventHub::readNotifyLocked() {
1674 int res;
1675 char devname[PATH_MAX];
1676 char *filename;
1677 char event_buf[512];
1678 int event_size;
1679 int event_pos = 0;
1680 struct inotify_event *event;
1681
1682 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
1683 res = read(mINotifyFd, event_buf, sizeof(event_buf));
1684 if(res < (int)sizeof(*event)) {
1685 if(errno == EINTR)
1686 return 0;
1687 ALOGW("could not get event, %s\n", strerror(errno));
1688 return -1;
1689 }
1690 //printf("got %d bytes of event information\n", res);
1691
1692 strcpy(devname, DEVICE_PATH);
1693 filename = devname + strlen(devname);
1694 *filename++ = '/';
1695
1696 while(res >= (int)sizeof(*event)) {
1697 event = (struct inotify_event *)(event_buf + event_pos);
1698 //printf("%d: %08x \"%s\"\n", event->wd, event->mask, event->len ? event->name : "");
1699 if(event->len) {
1700 strcpy(filename, event->name);
1701 if(event->mask & IN_CREATE) {
1702 openDeviceLocked(devname);
1703 } else {
1704 ALOGI("Removing device '%s' due to inotify event\n", devname);
1705 closeDeviceByPathLocked(devname);
1706 }
1707 }
1708 event_size = sizeof(*event) + event->len;
1709 res -= event_size;
1710 event_pos += event_size;
1711 }
1712 return 0;
1713}
1714
1715status_t EventHub::scanDirLocked(const char *dirname)
1716{
1717 char devname[PATH_MAX];
1718 char *filename;
1719 DIR *dir;
1720 struct dirent *de;
1721 dir = opendir(dirname);
Yi Kong9b14ac62018-07-17 13:48:38 -07001722 if(dir == nullptr)
Michael Wrightd02c5b62014-02-10 15:10:22 -08001723 return -1;
1724 strcpy(devname, dirname);
1725 filename = devname + strlen(devname);
1726 *filename++ = '/';
1727 while((de = readdir(dir))) {
1728 if(de->d_name[0] == '.' &&
1729 (de->d_name[1] == '\0' ||
1730 (de->d_name[1] == '.' && de->d_name[2] == '\0')))
1731 continue;
1732 strcpy(filename, de->d_name);
1733 openDeviceLocked(devname);
1734 }
1735 closedir(dir);
1736 return 0;
1737}
1738
1739void EventHub::requestReopenDevices() {
1740 ALOGV("requestReopenDevices() called");
1741
1742 AutoMutex _l(mLock);
1743 mNeedToReopenDevices = true;
1744}
1745
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001746void EventHub::dump(std::string& dump) {
1747 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001748
1749 { // acquire lock
1750 AutoMutex _l(mLock);
1751
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001752 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001753
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001754 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001755
1756 for (size_t i = 0; i < mDevices.size(); i++) {
1757 const Device* device = mDevices.valueAt(i);
1758 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001759 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001760 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001761 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001762 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001763 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001764 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001765 dump += StringPrintf(INDENT3 "Classes: 0x%08x\n", device->classes);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001766 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001767 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001768 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
1769 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001770 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001771 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001772 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08001773 "product=0x%04x, version=0x%04x\n",
1774 device->identifier.bus, device->identifier.vendor,
1775 device->identifier.product, device->identifier.version);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001776 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001777 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001778 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001779 device->keyMap.keyCharacterMapFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001780 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001781 device->configurationFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001782 dump += StringPrintf(INDENT3 "HaveKeyboardLayoutOverlay: %s\n",
Yi Kong9b14ac62018-07-17 13:48:38 -07001783 toString(device->overlayKeyMap != nullptr));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001784 }
1785 } // release lock
1786}
1787
1788void EventHub::monitor() {
1789 // Acquire and release the lock to ensure that the event hub has not deadlocked.
1790 mLock.lock();
1791 mLock.unlock();
1792}
1793
1794
1795}; // namespace android