blob: a3ecebcc7a0b4f8d2517e18d6710f99f5171f526 [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) {
1006 ALOGW("Could not write wake signal, errno=%d", errno);
1007 }
1008}
1009
1010void EventHub::scanDevicesLocked() {
1011 status_t res = scanDirLocked(DEVICE_PATH);
1012 if(res < 0) {
1013 ALOGE("scan dir failed for %s\n", DEVICE_PATH);
1014 }
1015 if (mDevices.indexOfKey(VIRTUAL_KEYBOARD_ID) < 0) {
1016 createVirtualKeyboardLocked();
1017 }
1018}
1019
1020// ----------------------------------------------------------------------------
1021
1022static bool containsNonZeroByte(const uint8_t* array, uint32_t startIndex, uint32_t endIndex) {
1023 const uint8_t* end = array + endIndex;
1024 array += startIndex;
1025 while (array != end) {
1026 if (*(array++) != 0) {
1027 return true;
1028 }
1029 }
1030 return false;
1031}
1032
1033static const int32_t GAMEPAD_KEYCODES[] = {
1034 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C,
1035 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z,
1036 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1,
1037 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2,
1038 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR,
1039 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001040};
1041
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001042status_t EventHub::registerFdForEpoll(int fd) {
1043 struct epoll_event eventItem = {};
1044 eventItem.events = EPOLLIN | EPOLLWAKEUP;
1045 eventItem.data.fd = fd;
1046 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1047 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001048 return -errno;
1049 }
1050 return OK;
1051}
1052
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001053status_t EventHub::unregisterFdFromEpoll(int fd) {
1054 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
1055 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
1056 return -errno;
1057 }
1058 return OK;
1059}
1060
1061status_t EventHub::registerDeviceForEpollLocked(Device* device) {
1062 if (device == nullptr) {
1063 if (DEBUG) {
1064 LOG_ALWAYS_FATAL("Cannot call registerDeviceForEpollLocked with null Device");
1065 }
1066 return BAD_VALUE;
1067 }
1068 status_t result = registerFdForEpoll(device->fd);
1069 if (result != OK) {
1070 ALOGE("Could not add input device fd to epoll for device %" PRId32, device->id);
1071 }
1072 return result;
1073}
1074
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001075status_t EventHub::unregisterDeviceFromEpollLocked(Device* device) {
1076 if (device->hasValidFd()) {
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001077 status_t result = unregisterFdFromEpoll(device->fd);
1078 if (result != OK) {
1079 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device->id);
1080 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001081 }
1082 }
1083 return OK;
1084}
1085
Michael Wrightd02c5b62014-02-10 15:10:22 -08001086status_t EventHub::openDeviceLocked(const char *devicePath) {
1087 char buffer[80];
1088
1089 ALOGV("Opening device: %s", devicePath);
1090
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001091 int fd = open(devicePath, O_RDWR | O_CLOEXEC | O_NONBLOCK);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001092 if(fd < 0) {
1093 ALOGE("could not open %s, %s\n", devicePath, strerror(errno));
1094 return -1;
1095 }
1096
1097 InputDeviceIdentifier identifier;
1098
1099 // Get device name.
1100 if(ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001101 ALOGE("Could not get device name for %s: %s", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001102 } else {
1103 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001104 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001105 }
1106
1107 // Check to see if the device is on our excluded list
1108 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001109 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001110 if (identifier.name == item) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001111 ALOGI("ignoring event id %s driver %s\n", devicePath, item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001112 close(fd);
1113 return -1;
1114 }
1115 }
1116
1117 // Get device driver version.
1118 int driverVersion;
1119 if(ioctl(fd, EVIOCGVERSION, &driverVersion)) {
1120 ALOGE("could not get driver version for %s, %s\n", devicePath, strerror(errno));
1121 close(fd);
1122 return -1;
1123 }
1124
1125 // Get device identifier.
1126 struct input_id inputId;
1127 if(ioctl(fd, EVIOCGID, &inputId)) {
1128 ALOGE("could not get device input id for %s, %s\n", devicePath, strerror(errno));
1129 close(fd);
1130 return -1;
1131 }
1132 identifier.bus = inputId.bustype;
1133 identifier.product = inputId.product;
1134 identifier.vendor = inputId.vendor;
1135 identifier.version = inputId.version;
1136
1137 // Get device physical location.
1138 if(ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
1139 //fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
1140 } else {
1141 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001142 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001143 }
1144
1145 // Get device unique id.
1146 if(ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
1147 //fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
1148 } else {
1149 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001150 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001151 }
1152
1153 // Fill in the descriptor.
1154 assignDescriptorLocked(identifier);
1155
Michael Wrightd02c5b62014-02-10 15:10:22 -08001156 // Allocate device. (The device object takes ownership of the fd at this point.)
1157 int32_t deviceId = mNextDeviceId++;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001158 Device* device = new Device(fd, deviceId, devicePath, identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001159
1160 ALOGV("add device %d: %s\n", deviceId, devicePath);
1161 ALOGV(" bus: %04x\n"
1162 " vendor %04x\n"
1163 " product %04x\n"
1164 " version %04x\n",
1165 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001166 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
1167 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
1168 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
1169 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001170 ALOGV(" driver: v%d.%d.%d\n",
1171 driverVersion >> 16, (driverVersion >> 8) & 0xff, driverVersion & 0xff);
1172
1173 // Load the configuration file for the device.
1174 loadConfigurationLocked(device);
1175
1176 // Figure out the kinds of events the device reports.
1177 ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(device->keyBitmask)), device->keyBitmask);
1178 ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(device->absBitmask)), device->absBitmask);
1179 ioctl(fd, EVIOCGBIT(EV_REL, sizeof(device->relBitmask)), device->relBitmask);
1180 ioctl(fd, EVIOCGBIT(EV_SW, sizeof(device->swBitmask)), device->swBitmask);
1181 ioctl(fd, EVIOCGBIT(EV_LED, sizeof(device->ledBitmask)), device->ledBitmask);
1182 ioctl(fd, EVIOCGBIT(EV_FF, sizeof(device->ffBitmask)), device->ffBitmask);
1183 ioctl(fd, EVIOCGPROP(sizeof(device->propBitmask)), device->propBitmask);
1184
1185 // See if this is a keyboard. Ignore everything in the button range except for
1186 // joystick and gamepad buttons which are handled like keyboards for the most part.
1187 bool haveKeyboardKeys = containsNonZeroByte(device->keyBitmask, 0, sizeof_bit_array(BTN_MISC))
1188 || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(KEY_OK),
1189 sizeof_bit_array(KEY_MAX + 1));
1190 bool haveGamepadButtons = containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_MISC),
1191 sizeof_bit_array(BTN_MOUSE))
1192 || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_JOYSTICK),
1193 sizeof_bit_array(BTN_DIGI));
1194 if (haveKeyboardKeys || haveGamepadButtons) {
1195 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1196 }
1197
1198 // See if this is a cursor device such as a trackball or mouse.
1199 if (test_bit(BTN_MOUSE, device->keyBitmask)
1200 && test_bit(REL_X, device->relBitmask)
1201 && test_bit(REL_Y, device->relBitmask)) {
1202 device->classes |= INPUT_DEVICE_CLASS_CURSOR;
1203 }
1204
Prashant Malani1941ff52015-08-11 18:29:28 -07001205 // See if this is a rotary encoder type device.
1206 String8 deviceType = String8();
1207 if (device->configuration &&
1208 device->configuration->tryGetProperty(String8("device.type"), deviceType)) {
1209 if (!deviceType.compare(String8("rotaryEncoder"))) {
1210 device->classes |= INPUT_DEVICE_CLASS_ROTARY_ENCODER;
1211 }
1212 }
1213
Michael Wrightd02c5b62014-02-10 15:10:22 -08001214 // See if this is a touch pad.
1215 // Is this a new modern multi-touch driver?
1216 if (test_bit(ABS_MT_POSITION_X, device->absBitmask)
1217 && test_bit(ABS_MT_POSITION_Y, device->absBitmask)) {
1218 // Some joysticks such as the PS3 controller report axes that conflict
1219 // with the ABS_MT range. Try to confirm that the device really is
1220 // a touch screen.
1221 if (test_bit(BTN_TOUCH, device->keyBitmask) || !haveGamepadButtons) {
1222 device->classes |= INPUT_DEVICE_CLASS_TOUCH | INPUT_DEVICE_CLASS_TOUCH_MT;
1223 }
1224 // Is this an old style single-touch driver?
1225 } else if (test_bit(BTN_TOUCH, device->keyBitmask)
1226 && test_bit(ABS_X, device->absBitmask)
1227 && test_bit(ABS_Y, device->absBitmask)) {
1228 device->classes |= INPUT_DEVICE_CLASS_TOUCH;
Michael Wright842500e2015-03-13 17:32:02 -07001229 // Is this a BT stylus?
1230 } else if ((test_bit(ABS_PRESSURE, device->absBitmask) ||
1231 test_bit(BTN_TOUCH, device->keyBitmask))
1232 && !test_bit(ABS_X, device->absBitmask)
1233 && !test_bit(ABS_Y, device->absBitmask)) {
1234 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
1235 // Keyboard will try to claim some of the buttons but we really want to reserve those so we
1236 // can fuse it with the touch screen data, so just take them back. Note this means an
1237 // external stylus cannot also be a keyboard device.
1238 device->classes &= ~INPUT_DEVICE_CLASS_KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001239 }
1240
1241 // See if this device is a joystick.
1242 // Assumes that joysticks always have gamepad buttons in order to distinguish them
1243 // from other devices such as accelerometers that also have absolute axes.
1244 if (haveGamepadButtons) {
1245 uint32_t assumedClasses = device->classes | INPUT_DEVICE_CLASS_JOYSTICK;
1246 for (int i = 0; i <= ABS_MAX; i++) {
1247 if (test_bit(i, device->absBitmask)
1248 && (getAbsAxisUsage(i, assumedClasses) & INPUT_DEVICE_CLASS_JOYSTICK)) {
1249 device->classes = assumedClasses;
1250 break;
1251 }
1252 }
1253 }
1254
1255 // Check whether this device has switches.
1256 for (int i = 0; i <= SW_MAX; i++) {
1257 if (test_bit(i, device->swBitmask)) {
1258 device->classes |= INPUT_DEVICE_CLASS_SWITCH;
1259 break;
1260 }
1261 }
1262
1263 // Check whether this device supports the vibrator.
1264 if (test_bit(FF_RUMBLE, device->ffBitmask)) {
1265 device->classes |= INPUT_DEVICE_CLASS_VIBRATOR;
1266 }
1267
1268 // Configure virtual keys.
1269 if ((device->classes & INPUT_DEVICE_CLASS_TOUCH)) {
1270 // Load the virtual keys for the touch screen, if any.
1271 // We do this now so that we can make sure to load the keymap if necessary.
1272 status_t status = loadVirtualKeyMapLocked(device);
1273 if (!status) {
1274 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1275 }
1276 }
1277
1278 // Load the key map.
1279 // We need to do this for joysticks too because the key layout may specify axes.
1280 status_t keyMapStatus = NAME_NOT_FOUND;
1281 if (device->classes & (INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_JOYSTICK)) {
1282 // Load the keymap for the device.
1283 keyMapStatus = loadKeyMapLocked(device);
1284 }
1285
1286 // Configure the keyboard, gamepad or virtual keyboard.
1287 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1288 // Register the keyboard as a built-in keyboard if it is eligible.
1289 if (!keyMapStatus
1290 && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD
1291 && isEligibleBuiltInKeyboard(device->identifier,
1292 device->configuration, &device->keyMap)) {
1293 mBuiltInKeyboardId = device->id;
1294 }
1295
1296 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
1297 if (hasKeycodeLocked(device, AKEYCODE_Q)) {
1298 device->classes |= INPUT_DEVICE_CLASS_ALPHAKEY;
1299 }
1300
1301 // See if this device has a DPAD.
1302 if (hasKeycodeLocked(device, AKEYCODE_DPAD_UP) &&
1303 hasKeycodeLocked(device, AKEYCODE_DPAD_DOWN) &&
1304 hasKeycodeLocked(device, AKEYCODE_DPAD_LEFT) &&
1305 hasKeycodeLocked(device, AKEYCODE_DPAD_RIGHT) &&
1306 hasKeycodeLocked(device, AKEYCODE_DPAD_CENTER)) {
1307 device->classes |= INPUT_DEVICE_CLASS_DPAD;
1308 }
1309
1310 // See if this device has a gamepad.
1311 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES)/sizeof(GAMEPAD_KEYCODES[0]); i++) {
1312 if (hasKeycodeLocked(device, GAMEPAD_KEYCODES[i])) {
1313 device->classes |= INPUT_DEVICE_CLASS_GAMEPAD;
1314 break;
1315 }
1316 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001317 }
1318
1319 // If the device isn't recognized as something we handle, don't monitor it.
1320 if (device->classes == 0) {
1321 ALOGV("Dropping device: id=%d, path='%s', name='%s'",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001322 deviceId, devicePath, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001323 delete device;
1324 return -1;
1325 }
1326
Tim Kilbourn063ff532015-04-08 10:26:18 -07001327 // Determine whether the device has a mic.
1328 if (deviceHasMicLocked(device)) {
1329 device->classes |= INPUT_DEVICE_CLASS_MIC;
1330 }
1331
Michael Wrightd02c5b62014-02-10 15:10:22 -08001332 // Determine whether the device is external or internal.
1333 if (isExternalDeviceLocked(device)) {
1334 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL;
1335 }
1336
Michael Wright42f2c6a2014-03-12 10:33:03 -07001337 if (device->classes & (INPUT_DEVICE_CLASS_JOYSTICK | INPUT_DEVICE_CLASS_DPAD)
1338 && device->classes & INPUT_DEVICE_CLASS_GAMEPAD) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001339 device->controllerNumber = getNextControllerNumberLocked(device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001340 setLedForControllerLocked(device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001341 }
1342
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001343
1344 if (registerDeviceForEpollLocked(device) != OK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001345 delete device;
1346 return -1;
1347 }
1348
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001349 configureFd(device);
1350
1351 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=0x%x, "
1352 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001353 deviceId, fd, devicePath, device->identifier.name.c_str(),
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001354 device->classes,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001355 device->configurationFile.c_str(),
1356 device->keyMap.keyLayoutFile.c_str(),
1357 device->keyMap.keyCharacterMapFile.c_str(),
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001358 toString(mBuiltInKeyboardId == deviceId));
1359
1360 addDeviceLocked(device);
1361 return OK;
1362}
1363
1364void EventHub::configureFd(Device* device) {
1365 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
1366 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1367 // Disable kernel key repeat since we handle it ourselves
1368 unsigned int repeatRate[] = {0, 0};
1369 if (ioctl(device->fd, EVIOCSREP, repeatRate)) {
1370 ALOGW("Unable to disable kernel key repeat for %s: %s",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001371 device->path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001372 }
1373 }
1374
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001375 std::string wakeMechanism = "EPOLLWAKEUP";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001376 if (!mUsingEpollWakeup) {
1377#ifndef EVIOCSSUSPENDBLOCK
1378 // uapi headers don't include EVIOCSSUSPENDBLOCK, and future kernels
1379 // will use an epoll flag instead, so as long as we want to support
1380 // this feature, we need to be prepared to define the ioctl ourselves.
1381#define EVIOCSSUSPENDBLOCK _IOW('E', 0x91, int)
1382#endif
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001383 if (ioctl(device->fd, EVIOCSSUSPENDBLOCK, 1)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001384 wakeMechanism = "<none>";
1385 } else {
1386 wakeMechanism = "EVIOCSSUSPENDBLOCK";
1387 }
1388 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001389 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
1390 // associated with input events. This is important because the input system
1391 // uses the timestamps extensively and assumes they were recorded using the monotonic
1392 // clock.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001393 int clockId = CLOCK_MONOTONIC;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001394 bool usingClockIoctl = !ioctl(device->fd, EVIOCSCLOCKID, &clockId);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001395 ALOGI("wakeMechanism=%s, usingClockIoctl=%s", wakeMechanism.c_str(),
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001396 toString(usingClockIoctl));
1397}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001398
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001399bool EventHub::isDeviceEnabled(int32_t deviceId) {
1400 AutoMutex _l(mLock);
1401 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001402 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001403 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1404 return false;
1405 }
1406 return device->enabled;
1407}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001408
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001409status_t EventHub::enableDevice(int32_t deviceId) {
1410 AutoMutex _l(mLock);
1411 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001412 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001413 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1414 return BAD_VALUE;
1415 }
1416 if (device->enabled) {
1417 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
1418 return OK;
1419 }
1420 status_t result = device->enable();
1421 if (result != OK) {
1422 ALOGE("Failed to enable device %" PRId32, deviceId);
1423 return result;
1424 }
1425
1426 configureFd(device);
1427
1428 return registerDeviceForEpollLocked(device);
1429}
1430
1431status_t EventHub::disableDevice(int32_t deviceId) {
1432 AutoMutex _l(mLock);
1433 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001434 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001435 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1436 return BAD_VALUE;
1437 }
1438 if (!device->enabled) {
1439 ALOGW("Duplicate call to %s, input device already disabled", __func__);
1440 return OK;
1441 }
1442 unregisterDeviceFromEpollLocked(device);
1443 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001444}
1445
1446void EventHub::createVirtualKeyboardLocked() {
1447 InputDeviceIdentifier identifier;
1448 identifier.name = "Virtual";
1449 identifier.uniqueId = "<virtual>";
1450 assignDescriptorLocked(identifier);
1451
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001452 Device* device = new Device(-1, VIRTUAL_KEYBOARD_ID, "<virtual>", identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001453 device->classes = INPUT_DEVICE_CLASS_KEYBOARD
1454 | INPUT_DEVICE_CLASS_ALPHAKEY
1455 | INPUT_DEVICE_CLASS_DPAD
1456 | INPUT_DEVICE_CLASS_VIRTUAL;
1457 loadKeyMapLocked(device);
1458 addDeviceLocked(device);
1459}
1460
1461void EventHub::addDeviceLocked(Device* device) {
1462 mDevices.add(device->id, device);
1463 device->next = mOpeningDevices;
1464 mOpeningDevices = device;
1465}
1466
1467void EventHub::loadConfigurationLocked(Device* device) {
1468 device->configurationFile = getInputDeviceConfigurationFilePathByDeviceIdentifier(
1469 device->identifier, INPUT_DEVICE_CONFIGURATION_FILE_TYPE_CONFIGURATION);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001470 if (device->configurationFile.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001471 ALOGD("No input device configuration file found for device '%s'.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001472 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001473 } else {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001474 status_t status = PropertyMap::load(String8(device->configurationFile.c_str()),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001475 &device->configuration);
1476 if (status) {
1477 ALOGE("Error loading input device configuration file for device '%s'. "
1478 "Using default configuration.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001479 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480 }
1481 }
1482}
1483
1484status_t EventHub::loadVirtualKeyMapLocked(Device* device) {
1485 // The virtual key map is supplied by the kernel as a system board property file.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001486 std::string path;
1487 path += "/sys/board_properties/virtualkeys.";
1488 path += device->identifier.name;
1489 if (access(path.c_str(), R_OK)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001490 return NAME_NOT_FOUND;
1491 }
1492 return VirtualKeyMap::load(path, &device->virtualKeyMap);
1493}
1494
1495status_t EventHub::loadKeyMapLocked(Device* device) {
1496 return device->keyMap.load(device->identifier, device->configuration);
1497}
1498
1499bool EventHub::isExternalDeviceLocked(Device* device) {
1500 if (device->configuration) {
1501 bool value;
1502 if (device->configuration->tryGetProperty(String8("device.internal"), value)) {
1503 return !value;
1504 }
1505 }
1506 return device->identifier.bus == BUS_USB || device->identifier.bus == BUS_BLUETOOTH;
1507}
1508
Tim Kilbourn063ff532015-04-08 10:26:18 -07001509bool EventHub::deviceHasMicLocked(Device* device) {
1510 if (device->configuration) {
1511 bool value;
1512 if (device->configuration->tryGetProperty(String8("audio.mic"), value)) {
1513 return value;
1514 }
1515 }
1516 return false;
1517}
1518
Michael Wrightd02c5b62014-02-10 15:10:22 -08001519int32_t EventHub::getNextControllerNumberLocked(Device* device) {
1520 if (mControllerNumbers.isFull()) {
1521 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001522 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001523 return 0;
1524 }
1525 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
1526 // one
1527 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
1528}
1529
1530void EventHub::releaseControllerNumberLocked(Device* device) {
1531 int32_t num = device->controllerNumber;
1532 device->controllerNumber= 0;
1533 if (num == 0) {
1534 return;
1535 }
1536 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
1537}
1538
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001539void EventHub::setLedForControllerLocked(Device* device) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001540 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
1541 setLedStateLocked(device, ALED_CONTROLLER_1 + i, device->controllerNumber == i + 1);
1542 }
1543}
1544
1545bool EventHub::hasKeycodeLocked(Device* device, int keycode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001546 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001547 return false;
1548 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001549
Michael Wrightd02c5b62014-02-10 15:10:22 -08001550 Vector<int32_t> scanCodes;
1551 device->keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes);
1552 const size_t N = scanCodes.size();
1553 for (size_t i=0; i<N && i<=KEY_MAX; i++) {
1554 int32_t sc = scanCodes.itemAt(i);
1555 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, device->keyBitmask)) {
1556 return true;
1557 }
1558 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001559
Michael Wrightd02c5b62014-02-10 15:10:22 -08001560 return false;
1561}
1562
1563status_t EventHub::mapLed(Device* device, int32_t led, int32_t* outScanCode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001564 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001565 return NAME_NOT_FOUND;
1566 }
1567
1568 int32_t scanCode;
1569 if(device->keyMap.keyLayoutMap->findScanCodeForLed(led, &scanCode) != NAME_NOT_FOUND) {
1570 if(scanCode >= 0 && scanCode <= LED_MAX && test_bit(scanCode, device->ledBitmask)) {
1571 *outScanCode = scanCode;
1572 return NO_ERROR;
1573 }
1574 }
1575 return NAME_NOT_FOUND;
1576}
1577
1578status_t EventHub::closeDeviceByPathLocked(const char *devicePath) {
1579 Device* device = getDeviceByPathLocked(devicePath);
1580 if (device) {
1581 closeDeviceLocked(device);
1582 return 0;
1583 }
1584 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath);
1585 return -1;
1586}
1587
1588void EventHub::closeAllDevicesLocked() {
1589 while (mDevices.size() > 0) {
1590 closeDeviceLocked(mDevices.valueAt(mDevices.size() - 1));
1591 }
1592}
1593
1594void EventHub::closeDeviceLocked(Device* device) {
1595 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=0x%x\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001596 device->path.c_str(), device->identifier.name.c_str(), device->id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001597 device->fd, device->classes);
1598
1599 if (device->id == mBuiltInKeyboardId) {
1600 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001601 device->path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001602 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
1603 }
1604
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001605 unregisterDeviceFromEpollLocked(device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001606
1607 releaseControllerNumberLocked(device);
1608
1609 mDevices.removeItem(device->id);
1610 device->close();
1611
1612 // Unlink for opening devices list if it is present.
Yi Kong9b14ac62018-07-17 13:48:38 -07001613 Device* pred = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001614 bool found = false;
Yi Kong9b14ac62018-07-17 13:48:38 -07001615 for (Device* entry = mOpeningDevices; entry != nullptr; ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001616 if (entry == device) {
1617 found = true;
1618 break;
1619 }
1620 pred = entry;
1621 entry = entry->next;
1622 }
1623 if (found) {
1624 // Unlink the device from the opening devices list then delete it.
1625 // We don't need to tell the client that the device was closed because
1626 // it does not even know it was opened in the first place.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001627 ALOGI("Device %s was immediately closed after opening.", device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001628 if (pred) {
1629 pred->next = device->next;
1630 } else {
1631 mOpeningDevices = device->next;
1632 }
1633 delete device;
1634 } else {
1635 // Link into closing devices list.
1636 // The device will be deleted later after we have informed the client.
1637 device->next = mClosingDevices;
1638 mClosingDevices = device;
1639 }
1640}
1641
1642status_t EventHub::readNotifyLocked() {
1643 int res;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001644 char event_buf[512];
1645 int event_size;
1646 int event_pos = 0;
1647 struct inotify_event *event;
1648
1649 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
1650 res = read(mINotifyFd, event_buf, sizeof(event_buf));
1651 if(res < (int)sizeof(*event)) {
1652 if(errno == EINTR)
1653 return 0;
1654 ALOGW("could not get event, %s\n", strerror(errno));
1655 return -1;
1656 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001657
1658 while(res >= (int)sizeof(*event)) {
1659 event = (struct inotify_event *)(event_buf + event_pos);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001660 if(event->len) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001661 if (event->wd == mInputWd) {
1662 std::string filename = StringPrintf("%s/%s", DEVICE_PATH, event->name);
1663 if(event->mask & IN_CREATE) {
1664 openDeviceLocked(filename.c_str());
1665 } else {
1666 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
1667 closeDeviceByPathLocked(filename.c_str());
1668 }
1669 }
1670 else if (event->wd == mVideoWd) {
1671 if (isV4lTouchNode(event->name)) {
1672 std::string filename = StringPrintf("%s/%s", VIDEO_DEVICE_PATH, event->name);
1673 ALOGV("Received an inotify event for a video device %s", filename.c_str());
1674 }
1675 }
1676 else {
1677 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event->wd);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001678 }
1679 }
1680 event_size = sizeof(*event) + event->len;
1681 res -= event_size;
1682 event_pos += event_size;
1683 }
1684 return 0;
1685}
1686
1687status_t EventHub::scanDirLocked(const char *dirname)
1688{
1689 char devname[PATH_MAX];
1690 char *filename;
1691 DIR *dir;
1692 struct dirent *de;
1693 dir = opendir(dirname);
Yi Kong9b14ac62018-07-17 13:48:38 -07001694 if(dir == nullptr)
Michael Wrightd02c5b62014-02-10 15:10:22 -08001695 return -1;
1696 strcpy(devname, dirname);
1697 filename = devname + strlen(devname);
1698 *filename++ = '/';
1699 while((de = readdir(dir))) {
1700 if(de->d_name[0] == '.' &&
1701 (de->d_name[1] == '\0' ||
1702 (de->d_name[1] == '.' && de->d_name[2] == '\0')))
1703 continue;
1704 strcpy(filename, de->d_name);
1705 openDeviceLocked(devname);
1706 }
1707 closedir(dir);
1708 return 0;
1709}
1710
1711void EventHub::requestReopenDevices() {
1712 ALOGV("requestReopenDevices() called");
1713
1714 AutoMutex _l(mLock);
1715 mNeedToReopenDevices = true;
1716}
1717
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001718void EventHub::dump(std::string& dump) {
1719 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001720
1721 { // acquire lock
1722 AutoMutex _l(mLock);
1723
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001724 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001725
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001726 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001727
1728 for (size_t i = 0; i < mDevices.size(); i++) {
1729 const Device* device = mDevices.valueAt(i);
1730 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001731 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001732 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001733 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001734 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001735 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001736 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001737 dump += StringPrintf(INDENT3 "Classes: 0x%08x\n", device->classes);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001738 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001739 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001740 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
1741 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001742 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001743 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001744 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08001745 "product=0x%04x, version=0x%04x\n",
1746 device->identifier.bus, device->identifier.vendor,
1747 device->identifier.product, device->identifier.version);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001748 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001749 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001750 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001751 device->keyMap.keyCharacterMapFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001752 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001753 device->configurationFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001754 dump += StringPrintf(INDENT3 "HaveKeyboardLayoutOverlay: %s\n",
Yi Kong9b14ac62018-07-17 13:48:38 -07001755 toString(device->overlayKeyMap != nullptr));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001756 }
1757 } // release lock
1758}
1759
1760void EventHub::monitor() {
1761 // Acquire and release the lock to ensure that the event hub has not deadlocked.
1762 mLock.lock();
1763 mLock.unlock();
1764}
1765
1766
1767}; // namespace android