blob: 904580fabc32629024137cb5ae5fe5511473bb25 [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>
Dan Albert677d87e2014-06-16 17:31:28 -070043#include <openssl/sha.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080044#include <utils/Log.h>
45#include <utils/Timers.h>
46#include <utils/threads.h>
47#include <utils/Errors.h>
48
Michael Wrightd02c5b62014-02-10 15:10:22 -080049#include <input/KeyLayoutMap.h>
50#include <input/KeyCharacterMap.h>
51#include <input/VirtualKeyMap.h>
52
Michael Wrightd02c5b62014-02-10 15:10:22 -080053/* this macro is used to tell if "bit" is set in "array"
54 * it selects a byte from the array, and does a boolean AND
55 * operation with a byte that only has the relevant bit set.
56 * eg. to check for the 12th bit, we do (array[1] & 1<<4)
57 */
Chih-Hung Hsieh4a186d42016-05-20 11:33:26 -070058#define test_bit(bit, array) ((array)[(bit)/8] & (1<<((bit)%8)))
Michael Wrightd02c5b62014-02-10 15:10:22 -080059
60/* 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 -070061#define sizeof_bit_array(bits) (((bits) + 7) / 8)
Michael Wrightd02c5b62014-02-10 15:10:22 -080062
63#define INDENT " "
64#define INDENT2 " "
65#define INDENT3 " "
66
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080067using android::base::StringPrintf;
68
Michael Wrightd02c5b62014-02-10 15:10:22 -080069namespace android {
70
Siarhei Vishniakou25920312018-12-12 15:24:44 -080071static constexpr bool DEBUG = false;
72
Michael Wrightd02c5b62014-02-10 15:10:22 -080073static const char *WAKE_LOCK_ID = "KeyEvents";
74static const char *DEVICE_PATH = "/dev/input";
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080075// v4l2 devices go directly into /dev
76static const char *VIDEO_DEVICE_PATH = "/dev";
Michael Wrightd02c5b62014-02-10 15:10:22 -080077
Michael Wrightd02c5b62014-02-10 15:10:22 -080078static inline const char* toString(bool value) {
79 return value ? "true" : "false";
80}
81
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010082static std::string sha1(const std::string& in) {
Dan Albert677d87e2014-06-16 17:31:28 -070083 SHA_CTX ctx;
84 SHA1_Init(&ctx);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010085 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
Dan Albert677d87e2014-06-16 17:31:28 -070086 u_char digest[SHA_DIGEST_LENGTH];
87 SHA1_Final(digest, &ctx);
Michael Wrightd02c5b62014-02-10 15:10:22 -080088
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010089 std::string out;
Dan Albert677d87e2014-06-16 17:31:28 -070090 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010091 out += StringPrintf("%02x", digest[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -080092 }
93 return out;
94}
95
96static void getLinuxRelease(int* major, int* minor) {
97 struct utsname info;
98 if (uname(&info) || sscanf(info.release, "%d.%d", major, minor) <= 0) {
99 *major = 0, *minor = 0;
100 ALOGE("Could not get linux version: %s", strerror(errno));
101 }
102}
103
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800104/**
105 * Return true if name matches "v4l-touch*"
106 */
107static bool isV4lTouchNode(const char* name) {
108 return strstr(name, "v4l-touch") == name;
109}
110
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800111static nsecs_t processEventTimestamp(const struct input_event& event) {
112 // Use the time specified in the event instead of the current time
113 // so that downstream code can get more accurate estimates of
114 // event dispatch latency from the time the event is enqueued onto
115 // the evdev client buffer.
116 //
117 // The event's timestamp fortuitously uses the same monotonic clock
118 // time base as the rest of Android. The kernel event device driver
119 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
120 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
121 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
122 // system call that also queries ktime_get_ts().
123
124 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.time.tv_sec) +
125 microseconds_to_nanoseconds(event.time.tv_usec);
126 return inputEventTime;
127}
128
Michael Wrightd02c5b62014-02-10 15:10:22 -0800129// --- Global Functions ---
130
131uint32_t getAbsAxisUsage(int32_t axis, uint32_t deviceClasses) {
132 // Touch devices get dibs on touch-related axes.
133 if (deviceClasses & INPUT_DEVICE_CLASS_TOUCH) {
134 switch (axis) {
135 case ABS_X:
136 case ABS_Y:
137 case ABS_PRESSURE:
138 case ABS_TOOL_WIDTH:
139 case ABS_DISTANCE:
140 case ABS_TILT_X:
141 case ABS_TILT_Y:
142 case ABS_MT_SLOT:
143 case ABS_MT_TOUCH_MAJOR:
144 case ABS_MT_TOUCH_MINOR:
145 case ABS_MT_WIDTH_MAJOR:
146 case ABS_MT_WIDTH_MINOR:
147 case ABS_MT_ORIENTATION:
148 case ABS_MT_POSITION_X:
149 case ABS_MT_POSITION_Y:
150 case ABS_MT_TOOL_TYPE:
151 case ABS_MT_BLOB_ID:
152 case ABS_MT_TRACKING_ID:
153 case ABS_MT_PRESSURE:
154 case ABS_MT_DISTANCE:
155 return INPUT_DEVICE_CLASS_TOUCH;
156 }
157 }
158
Michael Wright842500e2015-03-13 17:32:02 -0700159 // External stylus gets the pressure axis
160 if (deviceClasses & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
161 if (axis == ABS_PRESSURE) {
162 return INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
163 }
164 }
165
Michael Wrightd02c5b62014-02-10 15:10:22 -0800166 // Joystick devices get the rest.
167 return deviceClasses & INPUT_DEVICE_CLASS_JOYSTICK;
168}
169
170// --- EventHub::Device ---
171
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100172EventHub::Device::Device(int fd, int32_t id, const std::string& path,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800173 const InputDeviceIdentifier& identifier) :
Yi Kong9b14ac62018-07-17 13:48:38 -0700174 next(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800175 fd(fd), id(id), path(path), identifier(identifier),
Yi Kong9b14ac62018-07-17 13:48:38 -0700176 classes(0), configuration(nullptr), virtualKeyMap(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800177 ffEffectPlaying(false), ffEffectId(-1), controllerNumber(0),
Siarhei Vishniakou88786812018-11-09 15:36:21 -0800178 enabled(true), isVirtual(fd < 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800179 memset(keyBitmask, 0, sizeof(keyBitmask));
180 memset(absBitmask, 0, sizeof(absBitmask));
181 memset(relBitmask, 0, sizeof(relBitmask));
182 memset(swBitmask, 0, sizeof(swBitmask));
183 memset(ledBitmask, 0, sizeof(ledBitmask));
184 memset(ffBitmask, 0, sizeof(ffBitmask));
185 memset(propBitmask, 0, sizeof(propBitmask));
186}
187
188EventHub::Device::~Device() {
189 close();
190 delete configuration;
191 delete virtualKeyMap;
192}
193
194void EventHub::Device::close() {
195 if (fd >= 0) {
196 ::close(fd);
197 fd = -1;
198 }
199}
200
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700201status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100202 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700203 if(fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100204 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700205 return -errno;
206 }
207 enabled = true;
208 return OK;
209}
210
211status_t EventHub::Device::disable() {
212 close();
213 enabled = false;
214 return OK;
215}
216
217bool EventHub::Device::hasValidFd() {
218 return !isVirtual && enabled;
219}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800220
221// --- EventHub ---
222
Michael Wrightd02c5b62014-02-10 15:10:22 -0800223const int EventHub::EPOLL_SIZE_HINT;
224const int EventHub::EPOLL_MAX_EVENTS;
225
226EventHub::EventHub(void) :
227 mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD), mNextDeviceId(1), mControllerNumbers(),
Yi Kong9b14ac62018-07-17 13:48:38 -0700228 mOpeningDevices(nullptr), mClosingDevices(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800229 mNeedToSendFinishedDeviceScan(false),
230 mNeedToReopenDevices(false), mNeedToScanDevices(true),
231 mPendingEventCount(0), mPendingEventIndex(0), mPendingINotify(false) {
232 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
233
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800234 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800235 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800236
237 mINotifyFd = inotify_init();
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800238 mInputWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
239 LOG_ALWAYS_FATAL_IF(mInputWd < 0, "Could not register INotify for %s: %s",
240 DEVICE_PATH, strerror(errno));
241 mVideoWd = inotify_add_watch(mINotifyFd, VIDEO_DEVICE_PATH, IN_DELETE | IN_CREATE);
242 LOG_ALWAYS_FATAL_IF(mVideoWd < 0, "Could not register INotify for %s: %s",
243 VIDEO_DEVICE_PATH, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800244
245 struct epoll_event eventItem;
246 memset(&eventItem, 0, sizeof(eventItem));
247 eventItem.events = EPOLLIN;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700248 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800249 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800250 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
251
252 int wakeFds[2];
253 result = pipe(wakeFds);
254 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
255
256 mWakeReadPipeFd = wakeFds[0];
257 mWakeWritePipeFd = wakeFds[1];
258
259 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
260 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
261 errno);
262
263 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
264 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
265 errno);
266
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700267 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800268 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
269 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
270 errno);
271
272 int major, minor;
273 getLinuxRelease(&major, &minor);
274 // EPOLLWAKEUP was introduced in kernel 3.5
275 mUsingEpollWakeup = major > 3 || (major == 3 && minor >= 5);
276}
277
278EventHub::~EventHub(void) {
279 closeAllDevicesLocked();
280
281 while (mClosingDevices) {
282 Device* device = mClosingDevices;
283 mClosingDevices = device->next;
284 delete device;
285 }
286
287 ::close(mEpollFd);
288 ::close(mINotifyFd);
289 ::close(mWakeReadPipeFd);
290 ::close(mWakeWritePipeFd);
291
292 release_wake_lock(WAKE_LOCK_ID);
293}
294
295InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
296 AutoMutex _l(mLock);
297 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700298 if (device == nullptr) return InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800299 return device->identifier;
300}
301
302uint32_t EventHub::getDeviceClasses(int32_t deviceId) const {
303 AutoMutex _l(mLock);
304 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700305 if (device == nullptr) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800306 return device->classes;
307}
308
309int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
310 AutoMutex _l(mLock);
311 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700312 if (device == nullptr) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800313 return device->controllerNumber;
314}
315
316void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
317 AutoMutex _l(mLock);
318 Device* device = getDeviceLocked(deviceId);
319 if (device && device->configuration) {
320 *outConfiguration = *device->configuration;
321 } else {
322 outConfiguration->clear();
323 }
324}
325
326status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
327 RawAbsoluteAxisInfo* outAxisInfo) const {
328 outAxisInfo->clear();
329
330 if (axis >= 0 && axis <= ABS_MAX) {
331 AutoMutex _l(mLock);
332
333 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700334 if (device && device->hasValidFd() && test_bit(axis, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800335 struct input_absinfo info;
336 if(ioctl(device->fd, EVIOCGABS(axis), &info)) {
337 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100338 axis, device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800339 return -errno;
340 }
341
342 if (info.minimum != info.maximum) {
343 outAxisInfo->valid = true;
344 outAxisInfo->minValue = info.minimum;
345 outAxisInfo->maxValue = info.maximum;
346 outAxisInfo->flat = info.flat;
347 outAxisInfo->fuzz = info.fuzz;
348 outAxisInfo->resolution = info.resolution;
349 }
350 return OK;
351 }
352 }
353 return -1;
354}
355
356bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
357 if (axis >= 0 && axis <= REL_MAX) {
358 AutoMutex _l(mLock);
359
360 Device* device = getDeviceLocked(deviceId);
361 if (device) {
362 return test_bit(axis, device->relBitmask);
363 }
364 }
365 return false;
366}
367
368bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
369 if (property >= 0 && property <= INPUT_PROP_MAX) {
370 AutoMutex _l(mLock);
371
372 Device* device = getDeviceLocked(deviceId);
373 if (device) {
374 return test_bit(property, device->propBitmask);
375 }
376 }
377 return false;
378}
379
380int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
381 if (scanCode >= 0 && scanCode <= KEY_MAX) {
382 AutoMutex _l(mLock);
383
384 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700385 if (device && device->hasValidFd() && test_bit(scanCode, device->keyBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800386 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
387 memset(keyState, 0, sizeof(keyState));
388 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
389 return test_bit(scanCode, keyState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
390 }
391 }
392 }
393 return AKEY_STATE_UNKNOWN;
394}
395
396int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
397 AutoMutex _l(mLock);
398
399 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700400 if (device && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800401 Vector<int32_t> scanCodes;
402 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode, &scanCodes);
403 if (scanCodes.size() != 0) {
404 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
405 memset(keyState, 0, sizeof(keyState));
406 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
407 for (size_t i = 0; i < scanCodes.size(); i++) {
408 int32_t sc = scanCodes.itemAt(i);
409 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, keyState)) {
410 return AKEY_STATE_DOWN;
411 }
412 }
413 return AKEY_STATE_UP;
414 }
415 }
416 }
417 return AKEY_STATE_UNKNOWN;
418}
419
420int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
421 if (sw >= 0 && sw <= SW_MAX) {
422 AutoMutex _l(mLock);
423
424 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700425 if (device && device->hasValidFd() && test_bit(sw, device->swBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800426 uint8_t swState[sizeof_bit_array(SW_MAX + 1)];
427 memset(swState, 0, sizeof(swState));
428 if (ioctl(device->fd, EVIOCGSW(sizeof(swState)), swState) >= 0) {
429 return test_bit(sw, swState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
430 }
431 }
432 }
433 return AKEY_STATE_UNKNOWN;
434}
435
436status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
437 *outValue = 0;
438
439 if (axis >= 0 && axis <= ABS_MAX) {
440 AutoMutex _l(mLock);
441
442 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700443 if (device && device->hasValidFd() && test_bit(axis, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800444 struct input_absinfo info;
445 if(ioctl(device->fd, EVIOCGABS(axis), &info)) {
446 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100447 axis, device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800448 return -errno;
449 }
450
451 *outValue = info.value;
452 return OK;
453 }
454 }
455 return -1;
456}
457
458bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes,
459 const int32_t* keyCodes, uint8_t* outFlags) const {
460 AutoMutex _l(mLock);
461
462 Device* device = getDeviceLocked(deviceId);
463 if (device && device->keyMap.haveKeyLayout()) {
464 Vector<int32_t> scanCodes;
465 for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) {
466 scanCodes.clear();
467
468 status_t err = device->keyMap.keyLayoutMap->findScanCodesForKey(
469 keyCodes[codeIndex], &scanCodes);
470 if (! err) {
471 // check the possible scan codes identified by the layout map against the
472 // map of codes actually emitted by the driver
473 for (size_t sc = 0; sc < scanCodes.size(); sc++) {
474 if (test_bit(scanCodes[sc], device->keyBitmask)) {
475 outFlags[codeIndex] = 1;
476 break;
477 }
478 }
479 }
480 }
481 return true;
482 }
483 return false;
484}
485
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700486status_t EventHub::mapKey(int32_t deviceId,
487 int32_t scanCode, int32_t usageCode, int32_t metaState,
488 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800489 AutoMutex _l(mLock);
490 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700491 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800492
493 if (device) {
494 // Check the key character map first.
495 sp<KeyCharacterMap> kcm = device->getKeyCharacterMap();
Yi Kong9b14ac62018-07-17 13:48:38 -0700496 if (kcm != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800497 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
498 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700499 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800500 }
501 }
502
503 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700504 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800505 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700506 status = NO_ERROR;
507 }
508 }
509
510 if (status == NO_ERROR) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700511 if (kcm != nullptr) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700512 kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState);
513 } else {
514 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800515 }
516 }
517 }
518
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700519 if (status != NO_ERROR) {
520 *outKeycode = 0;
521 *outFlags = 0;
522 *outMetaState = metaState;
523 }
524
525 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800526}
527
528status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
529 AutoMutex _l(mLock);
530 Device* device = getDeviceLocked(deviceId);
531
532 if (device && device->keyMap.haveKeyLayout()) {
533 status_t err = device->keyMap.keyLayoutMap->mapAxis(scanCode, outAxisInfo);
534 if (err == NO_ERROR) {
535 return NO_ERROR;
536 }
537 }
538
539 return NAME_NOT_FOUND;
540}
541
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100542void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800543 AutoMutex _l(mLock);
544
545 mExcludedDevices = devices;
546}
547
548bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
549 AutoMutex _l(mLock);
550 Device* device = getDeviceLocked(deviceId);
551 if (device && scanCode >= 0 && scanCode <= KEY_MAX) {
552 if (test_bit(scanCode, device->keyBitmask)) {
553 return true;
554 }
555 }
556 return false;
557}
558
559bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
560 AutoMutex _l(mLock);
561 Device* device = getDeviceLocked(deviceId);
562 int32_t sc;
563 if (device && mapLed(device, led, &sc) == NO_ERROR) {
564 if (test_bit(sc, device->ledBitmask)) {
565 return true;
566 }
567 }
568 return false;
569}
570
571void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
572 AutoMutex _l(mLock);
573 Device* device = getDeviceLocked(deviceId);
574 setLedStateLocked(device, led, on);
575}
576
577void EventHub::setLedStateLocked(Device* device, int32_t led, bool on) {
578 int32_t sc;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700579 if (device && device->hasValidFd() && mapLed(device, led, &sc) != NAME_NOT_FOUND) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800580 struct input_event ev;
581 ev.time.tv_sec = 0;
582 ev.time.tv_usec = 0;
583 ev.type = EV_LED;
584 ev.code = sc;
585 ev.value = on ? 1 : 0;
586
587 ssize_t nWrite;
588 do {
589 nWrite = write(device->fd, &ev, sizeof(struct input_event));
590 } while (nWrite == -1 && errno == EINTR);
591 }
592}
593
594void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
595 Vector<VirtualKeyDefinition>& outVirtualKeys) const {
596 outVirtualKeys.clear();
597
598 AutoMutex _l(mLock);
599 Device* device = getDeviceLocked(deviceId);
600 if (device && device->virtualKeyMap) {
601 outVirtualKeys.appendVector(device->virtualKeyMap->getVirtualKeys());
602 }
603}
604
605sp<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
606 AutoMutex _l(mLock);
607 Device* device = getDeviceLocked(deviceId);
608 if (device) {
609 return device->getKeyCharacterMap();
610 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700611 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800612}
613
614bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId,
615 const sp<KeyCharacterMap>& map) {
616 AutoMutex _l(mLock);
617 Device* device = getDeviceLocked(deviceId);
618 if (device) {
619 if (map != device->overlayKeyMap) {
620 device->overlayKeyMap = map;
621 device->combinedKeyMap = KeyCharacterMap::combine(
622 device->keyMap.keyCharacterMap, map);
623 return true;
624 }
625 }
626 return false;
627}
628
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100629static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
630 std::string rawDescriptor;
631 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800632 identifier.product);
633 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100634 if (!identifier.uniqueId.empty()) {
635 rawDescriptor += "uniqueId:";
636 rawDescriptor += identifier.uniqueId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800637 } else if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100638 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800639 }
640
641 if (identifier.vendor == 0 && identifier.product == 0) {
642 // If we don't know the vendor and product id, then the device is probably
643 // built-in so we need to rely on other information to uniquely identify
644 // the input device. Usually we try to avoid relying on the device name or
645 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100646 if (!identifier.name.empty()) {
647 rawDescriptor += "name:";
648 rawDescriptor += identifier.name;
649 } else if (!identifier.location.empty()) {
650 rawDescriptor += "location:";
651 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800652 }
653 }
654 identifier.descriptor = sha1(rawDescriptor);
655 return rawDescriptor;
656}
657
658void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
659 // Compute a device descriptor that uniquely identifies the device.
660 // The descriptor is assumed to be a stable identifier. Its value should not
661 // change between reboots, reconnections, firmware updates or new releases
662 // of Android. In practice we sometimes get devices that cannot be uniquely
663 // identified. In this case we enforce uniqueness between connected devices.
664 // Ideally, we also want the descriptor to be short and relatively opaque.
665
666 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100667 std::string rawDescriptor = generateDescriptor(identifier);
668 if (identifier.uniqueId.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800669 // If it didn't have a unique id check for conflicts and enforce
670 // uniqueness if necessary.
Yi Kong9b14ac62018-07-17 13:48:38 -0700671 while(getDeviceByDescriptorLocked(identifier.descriptor) != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800672 identifier.nonce++;
673 rawDescriptor = generateDescriptor(identifier);
674 }
675 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100676 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
677 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800678}
679
680void EventHub::vibrate(int32_t deviceId, nsecs_t duration) {
681 AutoMutex _l(mLock);
682 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700683 if (device && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800684 ff_effect effect;
685 memset(&effect, 0, sizeof(effect));
686 effect.type = FF_RUMBLE;
687 effect.id = device->ffEffectId;
688 effect.u.rumble.strong_magnitude = 0xc000;
689 effect.u.rumble.weak_magnitude = 0xc000;
690 effect.replay.length = (duration + 999999LL) / 1000000LL;
691 effect.replay.delay = 0;
692 if (ioctl(device->fd, EVIOCSFF, &effect)) {
693 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100694 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800695 return;
696 }
697 device->ffEffectId = effect.id;
698
699 struct input_event ev;
700 ev.time.tv_sec = 0;
701 ev.time.tv_usec = 0;
702 ev.type = EV_FF;
703 ev.code = device->ffEffectId;
704 ev.value = 1;
705 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
706 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100707 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800708 return;
709 }
710 device->ffEffectPlaying = true;
711 }
712}
713
714void EventHub::cancelVibrate(int32_t deviceId) {
715 AutoMutex _l(mLock);
716 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700717 if (device && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800718 if (device->ffEffectPlaying) {
719 device->ffEffectPlaying = false;
720
721 struct input_event ev;
722 ev.time.tv_sec = 0;
723 ev.time.tv_usec = 0;
724 ev.type = EV_FF;
725 ev.code = device->ffEffectId;
726 ev.value = 0;
727 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
728 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100729 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800730 return;
731 }
732 }
733 }
734}
735
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100736EventHub::Device* EventHub::getDeviceByDescriptorLocked(const std::string& descriptor) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800737 size_t size = mDevices.size();
738 for (size_t i = 0; i < size; i++) {
739 Device* device = mDevices.valueAt(i);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100740 if (descriptor == device->identifier.descriptor) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800741 return device;
742 }
743 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700744 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800745}
746
747EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
748 if (deviceId == BUILT_IN_KEYBOARD_ID) {
749 deviceId = mBuiltInKeyboardId;
750 }
751 ssize_t index = mDevices.indexOfKey(deviceId);
752 return index >= 0 ? mDevices.valueAt(index) : NULL;
753}
754
755EventHub::Device* EventHub::getDeviceByPathLocked(const char* devicePath) const {
756 for (size_t i = 0; i < mDevices.size(); i++) {
757 Device* device = mDevices.valueAt(i);
758 if (device->path == devicePath) {
759 return device;
760 }
761 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700762 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800763}
764
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700765EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
766 for (size_t i = 0; i < mDevices.size(); i++) {
767 Device* device = mDevices.valueAt(i);
768 if (device->fd == fd) {
769 return device;
770 }
771 }
772 return nullptr;
773}
774
Michael Wrightd02c5b62014-02-10 15:10:22 -0800775size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
776 ALOG_ASSERT(bufferSize >= 1);
777
778 AutoMutex _l(mLock);
779
780 struct input_event readBuffer[bufferSize];
781
782 RawEvent* event = buffer;
783 size_t capacity = bufferSize;
784 bool awoken = false;
785 for (;;) {
786 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
787
788 // Reopen input devices if needed.
789 if (mNeedToReopenDevices) {
790 mNeedToReopenDevices = false;
791
792 ALOGI("Reopening all input devices due to a configuration change.");
793
794 closeAllDevicesLocked();
795 mNeedToScanDevices = true;
796 break; // return to the caller before we actually rescan
797 }
798
799 // Report any devices that had last been added/removed.
800 while (mClosingDevices) {
801 Device* device = mClosingDevices;
802 ALOGV("Reporting device closed: id=%d, name=%s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100803 device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800804 mClosingDevices = device->next;
805 event->when = now;
806 event->deviceId = device->id == mBuiltInKeyboardId ? BUILT_IN_KEYBOARD_ID : device->id;
807 event->type = DEVICE_REMOVED;
808 event += 1;
809 delete device;
810 mNeedToSendFinishedDeviceScan = true;
811 if (--capacity == 0) {
812 break;
813 }
814 }
815
816 if (mNeedToScanDevices) {
817 mNeedToScanDevices = false;
818 scanDevicesLocked();
819 mNeedToSendFinishedDeviceScan = true;
820 }
821
Yi Kong9b14ac62018-07-17 13:48:38 -0700822 while (mOpeningDevices != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800823 Device* device = mOpeningDevices;
824 ALOGV("Reporting device opened: id=%d, name=%s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100825 device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800826 mOpeningDevices = device->next;
827 event->when = now;
828 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
829 event->type = DEVICE_ADDED;
830 event += 1;
831 mNeedToSendFinishedDeviceScan = true;
832 if (--capacity == 0) {
833 break;
834 }
835 }
836
837 if (mNeedToSendFinishedDeviceScan) {
838 mNeedToSendFinishedDeviceScan = false;
839 event->when = now;
840 event->type = FINISHED_DEVICE_SCAN;
841 event += 1;
842 if (--capacity == 0) {
843 break;
844 }
845 }
846
847 // Grab the next input event.
848 bool deviceChanged = false;
849 while (mPendingEventIndex < mPendingEventCount) {
850 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700851 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800852 if (eventItem.events & EPOLLIN) {
853 mPendingINotify = true;
854 } else {
855 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
856 }
857 continue;
858 }
859
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700860 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800861 if (eventItem.events & EPOLLIN) {
862 ALOGV("awoken after wake()");
863 awoken = true;
864 char buffer[16];
865 ssize_t nRead;
866 do {
867 nRead = read(mWakeReadPipeFd, buffer, sizeof(buffer));
868 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(buffer));
869 } else {
870 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
871 eventItem.events);
872 }
873 continue;
874 }
875
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700876 Device* device = getDeviceByFdLocked(eventItem.data.fd);
877 if (device == nullptr) {
878 ALOGW("Received unexpected epoll event 0x%08x for unknown device fd %d.",
879 eventItem.events, eventItem.data.fd);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800880 continue;
881 }
882
Michael Wrightd02c5b62014-02-10 15:10:22 -0800883 if (eventItem.events & EPOLLIN) {
884 int32_t readSize = read(device->fd, readBuffer,
885 sizeof(struct input_event) * capacity);
886 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
887 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -0700888 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
889 " bufferSize: %zu capacity: %zu errno: %d)\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800890 device->fd, readSize, bufferSize, capacity, errno);
891 deviceChanged = true;
892 closeDeviceLocked(device);
893 } else if (readSize < 0) {
894 if (errno != EAGAIN && errno != EINTR) {
895 ALOGW("could not get event (errno=%d)", errno);
896 }
897 } else if ((readSize % sizeof(struct input_event)) != 0) {
898 ALOGE("could not get event (wrong size: %d)", readSize);
899 } else {
900 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
901
902 size_t count = size_t(readSize) / sizeof(struct input_event);
903 for (size_t i = 0; i < count; i++) {
904 struct input_event& iev = readBuffer[i];
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800905 event->when = processEventTimestamp(iev);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800906 event->deviceId = deviceId;
907 event->type = iev.type;
908 event->code = iev.code;
909 event->value = iev.value;
910 event += 1;
911 capacity -= 1;
912 }
913 if (capacity == 0) {
914 // The result buffer is full. Reset the pending event index
915 // so we will try to read the device again on the next iteration.
916 mPendingEventIndex -= 1;
917 break;
918 }
919 }
920 } else if (eventItem.events & EPOLLHUP) {
921 ALOGI("Removing device %s due to epoll hang-up event.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100922 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800923 deviceChanged = true;
924 closeDeviceLocked(device);
925 } else {
926 ALOGW("Received unexpected epoll event 0x%08x for device %s.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100927 eventItem.events, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800928 }
929 }
930
931 // readNotify() will modify the list of devices so this must be done after
932 // processing all other events to ensure that we read all remaining events
933 // before closing the devices.
934 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
935 mPendingINotify = false;
936 readNotifyLocked();
937 deviceChanged = true;
938 }
939
940 // Report added or removed devices immediately.
941 if (deviceChanged) {
942 continue;
943 }
944
945 // Return now if we have collected any events or if we were explicitly awoken.
946 if (event != buffer || awoken) {
947 break;
948 }
949
950 // Poll for events. Mind the wake lock dance!
951 // We hold a wake lock at all times except during epoll_wait(). This works due to some
952 // subtle choreography. When a device driver has pending (unread) events, it acquires
953 // a kernel wake lock. However, once the last pending event has been read, the device
954 // driver will release the kernel wake lock. To prevent the system from going to sleep
955 // when this happens, the EventHub holds onto its own user wake lock while the client
956 // is processing events. Thus the system can only sleep if there are no events
957 // pending or currently being processed.
958 //
959 // The timeout is advisory only. If the device is asleep, it will not wake just to
960 // service the timeout.
961 mPendingEventIndex = 0;
962
963 mLock.unlock(); // release lock before poll, must be before release_wake_lock
964 release_wake_lock(WAKE_LOCK_ID);
965
966 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
967
968 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
969 mLock.lock(); // reacquire lock after poll, must be after acquire_wake_lock
970
971 if (pollResult == 0) {
972 // Timed out.
973 mPendingEventCount = 0;
974 break;
975 }
976
977 if (pollResult < 0) {
978 // An error occurred.
979 mPendingEventCount = 0;
980
981 // Sleep after errors to avoid locking up the system.
982 // Hopefully the error is transient.
983 if (errno != EINTR) {
984 ALOGW("poll failed (errno=%d)\n", errno);
985 usleep(100000);
986 }
987 } else {
988 // Some events occurred.
989 mPendingEventCount = size_t(pollResult);
990 }
991 }
992
993 // All done, return the number of events we read.
994 return event - buffer;
995}
996
997void EventHub::wake() {
998 ALOGV("wake() called");
999
1000 ssize_t nWrite;
1001 do {
1002 nWrite = write(mWakeWritePipeFd, "W", 1);
1003 } while (nWrite == -1 && errno == EINTR);
1004
1005 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001006 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001007 }
1008}
1009
1010void EventHub::scanDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001011 status_t result = scanDirLocked(DEVICE_PATH);
1012 if(result < 0) {
1013 ALOGE("scan dir failed for %s", DEVICE_PATH);
1014 }
1015 result = scanVideoDirLocked(VIDEO_DEVICE_PATH);
1016 if (result != OK) {
1017 ALOGE("scan video dir failed for %s", VIDEO_DEVICE_PATH);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001018 }
1019 if (mDevices.indexOfKey(VIRTUAL_KEYBOARD_ID) < 0) {
1020 createVirtualKeyboardLocked();
1021 }
1022}
1023
1024// ----------------------------------------------------------------------------
1025
1026static bool containsNonZeroByte(const uint8_t* array, uint32_t startIndex, uint32_t endIndex) {
1027 const uint8_t* end = array + endIndex;
1028 array += startIndex;
1029 while (array != end) {
1030 if (*(array++) != 0) {
1031 return true;
1032 }
1033 }
1034 return false;
1035}
1036
1037static const int32_t GAMEPAD_KEYCODES[] = {
1038 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C,
1039 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z,
1040 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1,
1041 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2,
1042 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR,
1043 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001044};
1045
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001046status_t EventHub::registerFdForEpoll(int fd) {
1047 struct epoll_event eventItem = {};
1048 eventItem.events = EPOLLIN | EPOLLWAKEUP;
1049 eventItem.data.fd = fd;
1050 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1051 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001052 return -errno;
1053 }
1054 return OK;
1055}
1056
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001057status_t EventHub::unregisterFdFromEpoll(int fd) {
1058 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
1059 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
1060 return -errno;
1061 }
1062 return OK;
1063}
1064
1065status_t EventHub::registerDeviceForEpollLocked(Device* device) {
1066 if (device == nullptr) {
1067 if (DEBUG) {
1068 LOG_ALWAYS_FATAL("Cannot call registerDeviceForEpollLocked with null Device");
1069 }
1070 return BAD_VALUE;
1071 }
1072 status_t result = registerFdForEpoll(device->fd);
1073 if (result != OK) {
1074 ALOGE("Could not add input device fd to epoll for device %" PRId32, device->id);
1075 }
1076 return result;
1077}
1078
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001079status_t EventHub::unregisterDeviceFromEpollLocked(Device* device) {
1080 if (device->hasValidFd()) {
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001081 status_t result = unregisterFdFromEpoll(device->fd);
1082 if (result != OK) {
1083 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device->id);
1084 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001085 }
1086 }
1087 return OK;
1088}
1089
Michael Wrightd02c5b62014-02-10 15:10:22 -08001090status_t EventHub::openDeviceLocked(const char *devicePath) {
1091 char buffer[80];
1092
1093 ALOGV("Opening device: %s", devicePath);
1094
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001095 int fd = open(devicePath, O_RDWR | O_CLOEXEC | O_NONBLOCK);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001096 if(fd < 0) {
1097 ALOGE("could not open %s, %s\n", devicePath, strerror(errno));
1098 return -1;
1099 }
1100
1101 InputDeviceIdentifier identifier;
1102
1103 // Get device name.
1104 if(ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001105 ALOGE("Could not get device name for %s: %s", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001106 } else {
1107 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001108 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001109 }
1110
1111 // Check to see if the device is on our excluded list
1112 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001113 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001114 if (identifier.name == item) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001115 ALOGI("ignoring event id %s driver %s\n", devicePath, item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001116 close(fd);
1117 return -1;
1118 }
1119 }
1120
1121 // Get device driver version.
1122 int driverVersion;
1123 if(ioctl(fd, EVIOCGVERSION, &driverVersion)) {
1124 ALOGE("could not get driver version for %s, %s\n", devicePath, strerror(errno));
1125 close(fd);
1126 return -1;
1127 }
1128
1129 // Get device identifier.
1130 struct input_id inputId;
1131 if(ioctl(fd, EVIOCGID, &inputId)) {
1132 ALOGE("could not get device input id for %s, %s\n", devicePath, strerror(errno));
1133 close(fd);
1134 return -1;
1135 }
1136 identifier.bus = inputId.bustype;
1137 identifier.product = inputId.product;
1138 identifier.vendor = inputId.vendor;
1139 identifier.version = inputId.version;
1140
1141 // Get device physical location.
1142 if(ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
1143 //fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
1144 } else {
1145 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001146 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001147 }
1148
1149 // Get device unique id.
1150 if(ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
1151 //fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
1152 } else {
1153 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001154 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001155 }
1156
1157 // Fill in the descriptor.
1158 assignDescriptorLocked(identifier);
1159
Michael Wrightd02c5b62014-02-10 15:10:22 -08001160 // Allocate device. (The device object takes ownership of the fd at this point.)
1161 int32_t deviceId = mNextDeviceId++;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001162 Device* device = new Device(fd, deviceId, devicePath, identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001163
1164 ALOGV("add device %d: %s\n", deviceId, devicePath);
1165 ALOGV(" bus: %04x\n"
1166 " vendor %04x\n"
1167 " product %04x\n"
1168 " version %04x\n",
1169 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001170 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
1171 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
1172 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
1173 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001174 ALOGV(" driver: v%d.%d.%d\n",
1175 driverVersion >> 16, (driverVersion >> 8) & 0xff, driverVersion & 0xff);
1176
1177 // Load the configuration file for the device.
1178 loadConfigurationLocked(device);
1179
1180 // Figure out the kinds of events the device reports.
1181 ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(device->keyBitmask)), device->keyBitmask);
1182 ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(device->absBitmask)), device->absBitmask);
1183 ioctl(fd, EVIOCGBIT(EV_REL, sizeof(device->relBitmask)), device->relBitmask);
1184 ioctl(fd, EVIOCGBIT(EV_SW, sizeof(device->swBitmask)), device->swBitmask);
1185 ioctl(fd, EVIOCGBIT(EV_LED, sizeof(device->ledBitmask)), device->ledBitmask);
1186 ioctl(fd, EVIOCGBIT(EV_FF, sizeof(device->ffBitmask)), device->ffBitmask);
1187 ioctl(fd, EVIOCGPROP(sizeof(device->propBitmask)), device->propBitmask);
1188
1189 // See if this is a keyboard. Ignore everything in the button range except for
1190 // joystick and gamepad buttons which are handled like keyboards for the most part.
1191 bool haveKeyboardKeys = containsNonZeroByte(device->keyBitmask, 0, sizeof_bit_array(BTN_MISC))
1192 || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(KEY_OK),
1193 sizeof_bit_array(KEY_MAX + 1));
1194 bool haveGamepadButtons = containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_MISC),
1195 sizeof_bit_array(BTN_MOUSE))
1196 || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_JOYSTICK),
1197 sizeof_bit_array(BTN_DIGI));
1198 if (haveKeyboardKeys || haveGamepadButtons) {
1199 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1200 }
1201
1202 // See if this is a cursor device such as a trackball or mouse.
1203 if (test_bit(BTN_MOUSE, device->keyBitmask)
1204 && test_bit(REL_X, device->relBitmask)
1205 && test_bit(REL_Y, device->relBitmask)) {
1206 device->classes |= INPUT_DEVICE_CLASS_CURSOR;
1207 }
1208
Prashant Malani1941ff52015-08-11 18:29:28 -07001209 // See if this is a rotary encoder type device.
1210 String8 deviceType = String8();
1211 if (device->configuration &&
1212 device->configuration->tryGetProperty(String8("device.type"), deviceType)) {
1213 if (!deviceType.compare(String8("rotaryEncoder"))) {
1214 device->classes |= INPUT_DEVICE_CLASS_ROTARY_ENCODER;
1215 }
1216 }
1217
Michael Wrightd02c5b62014-02-10 15:10:22 -08001218 // See if this is a touch pad.
1219 // Is this a new modern multi-touch driver?
1220 if (test_bit(ABS_MT_POSITION_X, device->absBitmask)
1221 && test_bit(ABS_MT_POSITION_Y, device->absBitmask)) {
1222 // Some joysticks such as the PS3 controller report axes that conflict
1223 // with the ABS_MT range. Try to confirm that the device really is
1224 // a touch screen.
1225 if (test_bit(BTN_TOUCH, device->keyBitmask) || !haveGamepadButtons) {
1226 device->classes |= INPUT_DEVICE_CLASS_TOUCH | INPUT_DEVICE_CLASS_TOUCH_MT;
1227 }
1228 // Is this an old style single-touch driver?
1229 } else if (test_bit(BTN_TOUCH, device->keyBitmask)
1230 && test_bit(ABS_X, device->absBitmask)
1231 && test_bit(ABS_Y, device->absBitmask)) {
1232 device->classes |= INPUT_DEVICE_CLASS_TOUCH;
Michael Wright842500e2015-03-13 17:32:02 -07001233 // Is this a BT stylus?
1234 } else if ((test_bit(ABS_PRESSURE, device->absBitmask) ||
1235 test_bit(BTN_TOUCH, device->keyBitmask))
1236 && !test_bit(ABS_X, device->absBitmask)
1237 && !test_bit(ABS_Y, device->absBitmask)) {
1238 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
1239 // Keyboard will try to claim some of the buttons but we really want to reserve those so we
1240 // can fuse it with the touch screen data, so just take them back. Note this means an
1241 // external stylus cannot also be a keyboard device.
1242 device->classes &= ~INPUT_DEVICE_CLASS_KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243 }
1244
1245 // See if this device is a joystick.
1246 // Assumes that joysticks always have gamepad buttons in order to distinguish them
1247 // from other devices such as accelerometers that also have absolute axes.
1248 if (haveGamepadButtons) {
1249 uint32_t assumedClasses = device->classes | INPUT_DEVICE_CLASS_JOYSTICK;
1250 for (int i = 0; i <= ABS_MAX; i++) {
1251 if (test_bit(i, device->absBitmask)
1252 && (getAbsAxisUsage(i, assumedClasses) & INPUT_DEVICE_CLASS_JOYSTICK)) {
1253 device->classes = assumedClasses;
1254 break;
1255 }
1256 }
1257 }
1258
1259 // Check whether this device has switches.
1260 for (int i = 0; i <= SW_MAX; i++) {
1261 if (test_bit(i, device->swBitmask)) {
1262 device->classes |= INPUT_DEVICE_CLASS_SWITCH;
1263 break;
1264 }
1265 }
1266
1267 // Check whether this device supports the vibrator.
1268 if (test_bit(FF_RUMBLE, device->ffBitmask)) {
1269 device->classes |= INPUT_DEVICE_CLASS_VIBRATOR;
1270 }
1271
1272 // Configure virtual keys.
1273 if ((device->classes & INPUT_DEVICE_CLASS_TOUCH)) {
1274 // Load the virtual keys for the touch screen, if any.
1275 // We do this now so that we can make sure to load the keymap if necessary.
1276 status_t status = loadVirtualKeyMapLocked(device);
1277 if (!status) {
1278 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1279 }
1280 }
1281
1282 // Load the key map.
1283 // We need to do this for joysticks too because the key layout may specify axes.
1284 status_t keyMapStatus = NAME_NOT_FOUND;
1285 if (device->classes & (INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_JOYSTICK)) {
1286 // Load the keymap for the device.
1287 keyMapStatus = loadKeyMapLocked(device);
1288 }
1289
1290 // Configure the keyboard, gamepad or virtual keyboard.
1291 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1292 // Register the keyboard as a built-in keyboard if it is eligible.
1293 if (!keyMapStatus
1294 && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD
1295 && isEligibleBuiltInKeyboard(device->identifier,
1296 device->configuration, &device->keyMap)) {
1297 mBuiltInKeyboardId = device->id;
1298 }
1299
1300 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
1301 if (hasKeycodeLocked(device, AKEYCODE_Q)) {
1302 device->classes |= INPUT_DEVICE_CLASS_ALPHAKEY;
1303 }
1304
1305 // See if this device has a DPAD.
1306 if (hasKeycodeLocked(device, AKEYCODE_DPAD_UP) &&
1307 hasKeycodeLocked(device, AKEYCODE_DPAD_DOWN) &&
1308 hasKeycodeLocked(device, AKEYCODE_DPAD_LEFT) &&
1309 hasKeycodeLocked(device, AKEYCODE_DPAD_RIGHT) &&
1310 hasKeycodeLocked(device, AKEYCODE_DPAD_CENTER)) {
1311 device->classes |= INPUT_DEVICE_CLASS_DPAD;
1312 }
1313
1314 // See if this device has a gamepad.
1315 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES)/sizeof(GAMEPAD_KEYCODES[0]); i++) {
1316 if (hasKeycodeLocked(device, GAMEPAD_KEYCODES[i])) {
1317 device->classes |= INPUT_DEVICE_CLASS_GAMEPAD;
1318 break;
1319 }
1320 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001321 }
1322
1323 // If the device isn't recognized as something we handle, don't monitor it.
1324 if (device->classes == 0) {
1325 ALOGV("Dropping device: id=%d, path='%s', name='%s'",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001326 deviceId, devicePath, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001327 delete device;
1328 return -1;
1329 }
1330
Tim Kilbourn063ff532015-04-08 10:26:18 -07001331 // Determine whether the device has a mic.
1332 if (deviceHasMicLocked(device)) {
1333 device->classes |= INPUT_DEVICE_CLASS_MIC;
1334 }
1335
Michael Wrightd02c5b62014-02-10 15:10:22 -08001336 // Determine whether the device is external or internal.
1337 if (isExternalDeviceLocked(device)) {
1338 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL;
1339 }
1340
Michael Wright42f2c6a2014-03-12 10:33:03 -07001341 if (device->classes & (INPUT_DEVICE_CLASS_JOYSTICK | INPUT_DEVICE_CLASS_DPAD)
1342 && device->classes & INPUT_DEVICE_CLASS_GAMEPAD) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001343 device->controllerNumber = getNextControllerNumberLocked(device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001344 setLedForControllerLocked(device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001345 }
1346
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001347
1348 if (registerDeviceForEpollLocked(device) != OK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001349 delete device;
1350 return -1;
1351 }
1352
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001353 configureFd(device);
1354
1355 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=0x%x, "
1356 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001357 deviceId, fd, devicePath, device->identifier.name.c_str(),
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001358 device->classes,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001359 device->configurationFile.c_str(),
1360 device->keyMap.keyLayoutFile.c_str(),
1361 device->keyMap.keyCharacterMapFile.c_str(),
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001362 toString(mBuiltInKeyboardId == deviceId));
1363
1364 addDeviceLocked(device);
1365 return OK;
1366}
1367
1368void EventHub::configureFd(Device* device) {
1369 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
1370 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1371 // Disable kernel key repeat since we handle it ourselves
1372 unsigned int repeatRate[] = {0, 0};
1373 if (ioctl(device->fd, EVIOCSREP, repeatRate)) {
1374 ALOGW("Unable to disable kernel key repeat for %s: %s",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001375 device->path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001376 }
1377 }
1378
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001379 std::string wakeMechanism = "EPOLLWAKEUP";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001380 if (!mUsingEpollWakeup) {
1381#ifndef EVIOCSSUSPENDBLOCK
1382 // uapi headers don't include EVIOCSSUSPENDBLOCK, and future kernels
1383 // will use an epoll flag instead, so as long as we want to support
1384 // this feature, we need to be prepared to define the ioctl ourselves.
1385#define EVIOCSSUSPENDBLOCK _IOW('E', 0x91, int)
1386#endif
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001387 if (ioctl(device->fd, EVIOCSSUSPENDBLOCK, 1)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001388 wakeMechanism = "<none>";
1389 } else {
1390 wakeMechanism = "EVIOCSSUSPENDBLOCK";
1391 }
1392 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001393 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
1394 // associated with input events. This is important because the input system
1395 // uses the timestamps extensively and assumes they were recorded using the monotonic
1396 // clock.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001397 int clockId = CLOCK_MONOTONIC;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001398 bool usingClockIoctl = !ioctl(device->fd, EVIOCSCLOCKID, &clockId);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001399 ALOGI("wakeMechanism=%s, usingClockIoctl=%s", wakeMechanism.c_str(),
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001400 toString(usingClockIoctl));
1401}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001402
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001403void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
1404 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
1405 if (!videoDevice) {
1406 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
1407 return;
1408 }
1409 ALOGI("Adding video device %s to list of unattached video devices",
1410 videoDevice->getName().c_str());
1411 mUnattachedVideoDevices.push_back(std::move(videoDevice));
1412}
1413
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001414bool EventHub::isDeviceEnabled(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 false;
1420 }
1421 return device->enabled;
1422}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001423
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001424status_t EventHub::enableDevice(int32_t deviceId) {
1425 AutoMutex _l(mLock);
1426 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001427 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001428 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1429 return BAD_VALUE;
1430 }
1431 if (device->enabled) {
1432 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
1433 return OK;
1434 }
1435 status_t result = device->enable();
1436 if (result != OK) {
1437 ALOGE("Failed to enable device %" PRId32, deviceId);
1438 return result;
1439 }
1440
1441 configureFd(device);
1442
1443 return registerDeviceForEpollLocked(device);
1444}
1445
1446status_t EventHub::disableDevice(int32_t deviceId) {
1447 AutoMutex _l(mLock);
1448 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001449 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001450 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1451 return BAD_VALUE;
1452 }
1453 if (!device->enabled) {
1454 ALOGW("Duplicate call to %s, input device already disabled", __func__);
1455 return OK;
1456 }
1457 unregisterDeviceFromEpollLocked(device);
1458 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001459}
1460
1461void EventHub::createVirtualKeyboardLocked() {
1462 InputDeviceIdentifier identifier;
1463 identifier.name = "Virtual";
1464 identifier.uniqueId = "<virtual>";
1465 assignDescriptorLocked(identifier);
1466
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001467 Device* device = new Device(-1, VIRTUAL_KEYBOARD_ID, "<virtual>", identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001468 device->classes = INPUT_DEVICE_CLASS_KEYBOARD
1469 | INPUT_DEVICE_CLASS_ALPHAKEY
1470 | INPUT_DEVICE_CLASS_DPAD
1471 | INPUT_DEVICE_CLASS_VIRTUAL;
1472 loadKeyMapLocked(device);
1473 addDeviceLocked(device);
1474}
1475
1476void EventHub::addDeviceLocked(Device* device) {
1477 mDevices.add(device->id, device);
1478 device->next = mOpeningDevices;
1479 mOpeningDevices = device;
1480}
1481
1482void EventHub::loadConfigurationLocked(Device* device) {
1483 device->configurationFile = getInputDeviceConfigurationFilePathByDeviceIdentifier(
1484 device->identifier, INPUT_DEVICE_CONFIGURATION_FILE_TYPE_CONFIGURATION);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001485 if (device->configurationFile.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001486 ALOGD("No input device configuration file found for device '%s'.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001487 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001488 } else {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001489 status_t status = PropertyMap::load(String8(device->configurationFile.c_str()),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001490 &device->configuration);
1491 if (status) {
1492 ALOGE("Error loading input device configuration file for device '%s'. "
1493 "Using default configuration.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001494 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001495 }
1496 }
1497}
1498
1499status_t EventHub::loadVirtualKeyMapLocked(Device* device) {
1500 // The virtual key map is supplied by the kernel as a system board property file.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001501 std::string path;
1502 path += "/sys/board_properties/virtualkeys.";
1503 path += device->identifier.name;
1504 if (access(path.c_str(), R_OK)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001505 return NAME_NOT_FOUND;
1506 }
1507 return VirtualKeyMap::load(path, &device->virtualKeyMap);
1508}
1509
1510status_t EventHub::loadKeyMapLocked(Device* device) {
1511 return device->keyMap.load(device->identifier, device->configuration);
1512}
1513
1514bool EventHub::isExternalDeviceLocked(Device* device) {
1515 if (device->configuration) {
1516 bool value;
1517 if (device->configuration->tryGetProperty(String8("device.internal"), value)) {
1518 return !value;
1519 }
1520 }
1521 return device->identifier.bus == BUS_USB || device->identifier.bus == BUS_BLUETOOTH;
1522}
1523
Tim Kilbourn063ff532015-04-08 10:26:18 -07001524bool EventHub::deviceHasMicLocked(Device* device) {
1525 if (device->configuration) {
1526 bool value;
1527 if (device->configuration->tryGetProperty(String8("audio.mic"), value)) {
1528 return value;
1529 }
1530 }
1531 return false;
1532}
1533
Michael Wrightd02c5b62014-02-10 15:10:22 -08001534int32_t EventHub::getNextControllerNumberLocked(Device* device) {
1535 if (mControllerNumbers.isFull()) {
1536 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001537 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001538 return 0;
1539 }
1540 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
1541 // one
1542 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
1543}
1544
1545void EventHub::releaseControllerNumberLocked(Device* device) {
1546 int32_t num = device->controllerNumber;
1547 device->controllerNumber= 0;
1548 if (num == 0) {
1549 return;
1550 }
1551 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
1552}
1553
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001554void EventHub::setLedForControllerLocked(Device* device) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001555 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
1556 setLedStateLocked(device, ALED_CONTROLLER_1 + i, device->controllerNumber == i + 1);
1557 }
1558}
1559
1560bool EventHub::hasKeycodeLocked(Device* device, int keycode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001561 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001562 return false;
1563 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001564
Michael Wrightd02c5b62014-02-10 15:10:22 -08001565 Vector<int32_t> scanCodes;
1566 device->keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes);
1567 const size_t N = scanCodes.size();
1568 for (size_t i=0; i<N && i<=KEY_MAX; i++) {
1569 int32_t sc = scanCodes.itemAt(i);
1570 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, device->keyBitmask)) {
1571 return true;
1572 }
1573 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001574
Michael Wrightd02c5b62014-02-10 15:10:22 -08001575 return false;
1576}
1577
1578status_t EventHub::mapLed(Device* device, int32_t led, int32_t* outScanCode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001579 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001580 return NAME_NOT_FOUND;
1581 }
1582
1583 int32_t scanCode;
1584 if(device->keyMap.keyLayoutMap->findScanCodeForLed(led, &scanCode) != NAME_NOT_FOUND) {
1585 if(scanCode >= 0 && scanCode <= LED_MAX && test_bit(scanCode, device->ledBitmask)) {
1586 *outScanCode = scanCode;
1587 return NO_ERROR;
1588 }
1589 }
1590 return NAME_NOT_FOUND;
1591}
1592
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001593void EventHub::closeDeviceByPathLocked(const char *devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001594 Device* device = getDeviceByPathLocked(devicePath);
1595 if (device) {
1596 closeDeviceLocked(device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001597 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001598 }
1599 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001600}
1601
1602void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
1603 mUnattachedVideoDevices.erase(std::remove_if(mUnattachedVideoDevices.begin(),
1604 mUnattachedVideoDevices.end(), [&devicePath](
1605 const std::unique_ptr<TouchVideoDevice>& videoDevice) {
1606 return videoDevice->getPath() == devicePath; }), mUnattachedVideoDevices.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001607}
1608
1609void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001610 mUnattachedVideoDevices.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001611 while (mDevices.size() > 0) {
1612 closeDeviceLocked(mDevices.valueAt(mDevices.size() - 1));
1613 }
1614}
1615
1616void EventHub::closeDeviceLocked(Device* device) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001617 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=0x%x",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001618 device->path.c_str(), device->identifier.name.c_str(), device->id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001619 device->fd, device->classes);
1620
1621 if (device->id == mBuiltInKeyboardId) {
1622 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001623 device->path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001624 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
1625 }
1626
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001627 unregisterDeviceFromEpollLocked(device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001628
1629 releaseControllerNumberLocked(device);
1630
1631 mDevices.removeItem(device->id);
1632 device->close();
1633
1634 // Unlink for opening devices list if it is present.
Yi Kong9b14ac62018-07-17 13:48:38 -07001635 Device* pred = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001636 bool found = false;
Yi Kong9b14ac62018-07-17 13:48:38 -07001637 for (Device* entry = mOpeningDevices; entry != nullptr; ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001638 if (entry == device) {
1639 found = true;
1640 break;
1641 }
1642 pred = entry;
1643 entry = entry->next;
1644 }
1645 if (found) {
1646 // Unlink the device from the opening devices list then delete it.
1647 // We don't need to tell the client that the device was closed because
1648 // it does not even know it was opened in the first place.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001649 ALOGI("Device %s was immediately closed after opening.", device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001650 if (pred) {
1651 pred->next = device->next;
1652 } else {
1653 mOpeningDevices = device->next;
1654 }
1655 delete device;
1656 } else {
1657 // Link into closing devices list.
1658 // The device will be deleted later after we have informed the client.
1659 device->next = mClosingDevices;
1660 mClosingDevices = device;
1661 }
1662}
1663
1664status_t EventHub::readNotifyLocked() {
1665 int res;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001666 char event_buf[512];
1667 int event_size;
1668 int event_pos = 0;
1669 struct inotify_event *event;
1670
1671 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
1672 res = read(mINotifyFd, event_buf, sizeof(event_buf));
1673 if(res < (int)sizeof(*event)) {
1674 if(errno == EINTR)
1675 return 0;
1676 ALOGW("could not get event, %s\n", strerror(errno));
1677 return -1;
1678 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001679
1680 while(res >= (int)sizeof(*event)) {
1681 event = (struct inotify_event *)(event_buf + event_pos);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001682 if(event->len) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001683 if (event->wd == mInputWd) {
1684 std::string filename = StringPrintf("%s/%s", DEVICE_PATH, event->name);
1685 if(event->mask & IN_CREATE) {
1686 openDeviceLocked(filename.c_str());
1687 } else {
1688 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
1689 closeDeviceByPathLocked(filename.c_str());
1690 }
1691 }
1692 else if (event->wd == mVideoWd) {
1693 if (isV4lTouchNode(event->name)) {
1694 std::string filename = StringPrintf("%s/%s", VIDEO_DEVICE_PATH, event->name);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001695 if (event->mask & IN_CREATE) {
1696 openVideoDeviceLocked(filename);
1697 } else {
1698 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
1699 closeVideoDeviceByPathLocked(filename);
1700 }
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001701 }
1702 }
1703 else {
1704 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event->wd);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001705 }
1706 }
1707 event_size = sizeof(*event) + event->len;
1708 res -= event_size;
1709 event_pos += event_size;
1710 }
1711 return 0;
1712}
1713
1714status_t EventHub::scanDirLocked(const char *dirname)
1715{
1716 char devname[PATH_MAX];
1717 char *filename;
1718 DIR *dir;
1719 struct dirent *de;
1720 dir = opendir(dirname);
Yi Kong9b14ac62018-07-17 13:48:38 -07001721 if(dir == nullptr)
Michael Wrightd02c5b62014-02-10 15:10:22 -08001722 return -1;
1723 strcpy(devname, dirname);
1724 filename = devname + strlen(devname);
1725 *filename++ = '/';
1726 while((de = readdir(dir))) {
1727 if(de->d_name[0] == '.' &&
1728 (de->d_name[1] == '\0' ||
1729 (de->d_name[1] == '.' && de->d_name[2] == '\0')))
1730 continue;
1731 strcpy(filename, de->d_name);
1732 openDeviceLocked(devname);
1733 }
1734 closedir(dir);
1735 return 0;
1736}
1737
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001738/**
1739 * Look for all dirname/v4l-touch* devices, and open them.
1740 */
1741status_t EventHub::scanVideoDirLocked(const std::string& dirname)
1742{
1743 DIR* dir;
1744 struct dirent* de;
1745 dir = opendir(dirname.c_str());
1746 if(!dir) {
1747 ALOGE("Could not open video directory %s", dirname.c_str());
1748 return BAD_VALUE;
1749 }
1750
1751 while((de = readdir(dir))) {
1752 const char* name = de->d_name;
1753 if (isV4lTouchNode(name)) {
1754 ALOGI("Found touch video device %s", name);
1755 openVideoDeviceLocked(dirname + "/" + name);
1756 }
1757 }
1758 closedir(dir);
1759 return OK;
1760}
1761
Michael Wrightd02c5b62014-02-10 15:10:22 -08001762void EventHub::requestReopenDevices() {
1763 ALOGV("requestReopenDevices() called");
1764
1765 AutoMutex _l(mLock);
1766 mNeedToReopenDevices = true;
1767}
1768
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001769void EventHub::dump(std::string& dump) {
1770 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001771
1772 { // acquire lock
1773 AutoMutex _l(mLock);
1774
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001775 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001776
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001777 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001778
1779 for (size_t i = 0; i < mDevices.size(); i++) {
1780 const Device* device = mDevices.valueAt(i);
1781 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001782 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001783 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001784 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001785 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001786 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001787 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001788 dump += StringPrintf(INDENT3 "Classes: 0x%08x\n", device->classes);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001789 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001790 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001791 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
1792 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001793 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001794 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001795 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08001796 "product=0x%04x, version=0x%04x\n",
1797 device->identifier.bus, device->identifier.vendor,
1798 device->identifier.product, device->identifier.version);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001799 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001800 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001801 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001802 device->keyMap.keyCharacterMapFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001803 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001804 device->configurationFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001805 dump += StringPrintf(INDENT3 "HaveKeyboardLayoutOverlay: %s\n",
Yi Kong9b14ac62018-07-17 13:48:38 -07001806 toString(device->overlayKeyMap != nullptr));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001807 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001808
1809 dump += INDENT "Unattached video devices:\n";
1810 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
1811 dump += INDENT2 + videoDevice->dump() + "\n";
1812 }
1813 if (mUnattachedVideoDevices.empty()) {
1814 dump += INDENT2 "<none>\n";
1815 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001816 } // release lock
1817}
1818
1819void EventHub::monitor() {
1820 // Acquire and release the lock to ensure that the event hub has not deadlocked.
1821 mLock.lock();
1822 mLock.unlock();
1823}
1824
1825
1826}; // namespace android