blob: ce5627271a6d1e26ec41622656f1a1478b9746f5 [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>
Philip Quinn39b81682019-01-09 22:20:39 -080043#include <cutils/properties.h>
Dan Albert677d87e2014-06-16 17:31:28 -070044#include <openssl/sha.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080045#include <utils/Log.h>
46#include <utils/Timers.h>
47#include <utils/threads.h>
48#include <utils/Errors.h>
49
Michael Wrightd02c5b62014-02-10 15:10:22 -080050#include <input/KeyLayoutMap.h>
51#include <input/KeyCharacterMap.h>
52#include <input/VirtualKeyMap.h>
53
Michael Wrightd02c5b62014-02-10 15:10:22 -080054/* this macro is used to tell if "bit" is set in "array"
55 * it selects a byte from the array, and does a boolean AND
56 * operation with a byte that only has the relevant bit set.
57 * eg. to check for the 12th bit, we do (array[1] & 1<<4)
58 */
Chih-Hung Hsieh4a186d42016-05-20 11:33:26 -070059#define test_bit(bit, array) ((array)[(bit)/8] & (1<<((bit)%8)))
Michael Wrightd02c5b62014-02-10 15:10:22 -080060
61/* this macro computes the number of bytes needed to represent a bit array of the specified size */
Chih-Hung Hsieh4a186d42016-05-20 11:33:26 -070062#define sizeof_bit_array(bits) (((bits) + 7) / 8)
Michael Wrightd02c5b62014-02-10 15:10:22 -080063
64#define INDENT " "
65#define INDENT2 " "
66#define INDENT3 " "
67
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080068using android::base::StringPrintf;
69
Michael Wrightd02c5b62014-02-10 15:10:22 -080070namespace android {
71
Siarhei Vishniakou25920312018-12-12 15:24:44 -080072static constexpr bool DEBUG = false;
73
Michael Wrightd02c5b62014-02-10 15:10:22 -080074static const char *WAKE_LOCK_ID = "KeyEvents";
75static const char *DEVICE_PATH = "/dev/input";
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080076// v4l2 devices go directly into /dev
77static const char *VIDEO_DEVICE_PATH = "/dev";
Michael Wrightd02c5b62014-02-10 15:10:22 -080078
Michael Wrightd02c5b62014-02-10 15:10:22 -080079static inline const char* toString(bool value) {
80 return value ? "true" : "false";
81}
82
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010083static std::string sha1(const std::string& in) {
Dan Albert677d87e2014-06-16 17:31:28 -070084 SHA_CTX ctx;
85 SHA1_Init(&ctx);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010086 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
Dan Albert677d87e2014-06-16 17:31:28 -070087 u_char digest[SHA_DIGEST_LENGTH];
88 SHA1_Final(digest, &ctx);
Michael Wrightd02c5b62014-02-10 15:10:22 -080089
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010090 std::string out;
Dan Albert677d87e2014-06-16 17:31:28 -070091 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010092 out += StringPrintf("%02x", digest[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -080093 }
94 return out;
95}
96
97static void getLinuxRelease(int* major, int* minor) {
98 struct utsname info;
99 if (uname(&info) || sscanf(info.release, "%d.%d", major, minor) <= 0) {
100 *major = 0, *minor = 0;
101 ALOGE("Could not get linux version: %s", strerror(errno));
102 }
103}
104
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800105/**
106 * Return true if name matches "v4l-touch*"
107 */
108static bool isV4lTouchNode(const char* name) {
109 return strstr(name, "v4l-touch") == name;
110}
111
Philip Quinn39b81682019-01-09 22:20:39 -0800112/**
113 * Returns true if V4L devices should be scanned.
114 *
115 * The system property ro.input.video_enabled can be used to control whether
116 * EventHub scans and opens V4L devices. As V4L does not support multiple
117 * clients, EventHub effectively blocks access to these devices when it opens
Siarhei Vishniakou29f88492019-04-05 14:11:43 -0700118 * them.
119 *
120 * Setting this to "false" would prevent any video devices from being discovered and
121 * associated with input devices.
122 *
123 * This property can be used as follows:
124 * 1. To turn off features that are dependent on video device presence.
125 * 2. During testing and development, to allow other clients to read video devices
126 * directly from /dev.
Philip Quinn39b81682019-01-09 22:20:39 -0800127 */
128static bool isV4lScanningEnabled() {
129 return property_get_bool("ro.input.video_enabled", true /* default_value */);
130}
131
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800132static nsecs_t processEventTimestamp(const struct input_event& event) {
133 // Use the time specified in the event instead of the current time
134 // so that downstream code can get more accurate estimates of
135 // event dispatch latency from the time the event is enqueued onto
136 // the evdev client buffer.
137 //
138 // The event's timestamp fortuitously uses the same monotonic clock
139 // time base as the rest of Android. The kernel event device driver
140 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
141 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
142 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
143 // system call that also queries ktime_get_ts().
144
145 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.time.tv_sec) +
146 microseconds_to_nanoseconds(event.time.tv_usec);
147 return inputEventTime;
148}
149
Michael Wrightd02c5b62014-02-10 15:10:22 -0800150// --- Global Functions ---
151
152uint32_t getAbsAxisUsage(int32_t axis, uint32_t deviceClasses) {
153 // Touch devices get dibs on touch-related axes.
154 if (deviceClasses & INPUT_DEVICE_CLASS_TOUCH) {
155 switch (axis) {
156 case ABS_X:
157 case ABS_Y:
158 case ABS_PRESSURE:
159 case ABS_TOOL_WIDTH:
160 case ABS_DISTANCE:
161 case ABS_TILT_X:
162 case ABS_TILT_Y:
163 case ABS_MT_SLOT:
164 case ABS_MT_TOUCH_MAJOR:
165 case ABS_MT_TOUCH_MINOR:
166 case ABS_MT_WIDTH_MAJOR:
167 case ABS_MT_WIDTH_MINOR:
168 case ABS_MT_ORIENTATION:
169 case ABS_MT_POSITION_X:
170 case ABS_MT_POSITION_Y:
171 case ABS_MT_TOOL_TYPE:
172 case ABS_MT_BLOB_ID:
173 case ABS_MT_TRACKING_ID:
174 case ABS_MT_PRESSURE:
175 case ABS_MT_DISTANCE:
176 return INPUT_DEVICE_CLASS_TOUCH;
177 }
178 }
179
Michael Wright842500e2015-03-13 17:32:02 -0700180 // External stylus gets the pressure axis
181 if (deviceClasses & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
182 if (axis == ABS_PRESSURE) {
183 return INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
184 }
185 }
186
Michael Wrightd02c5b62014-02-10 15:10:22 -0800187 // Joystick devices get the rest.
188 return deviceClasses & INPUT_DEVICE_CLASS_JOYSTICK;
189}
190
191// --- EventHub::Device ---
192
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100193EventHub::Device::Device(int fd, int32_t id, const std::string& path,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800194 const InputDeviceIdentifier& identifier) :
Yi Kong9b14ac62018-07-17 13:48:38 -0700195 next(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800196 fd(fd), id(id), path(path), identifier(identifier),
Yi Kong9b14ac62018-07-17 13:48:38 -0700197 classes(0), configuration(nullptr), virtualKeyMap(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800198 ffEffectPlaying(false), ffEffectId(-1), controllerNumber(0),
Siarhei Vishniakou88786812018-11-09 15:36:21 -0800199 enabled(true), isVirtual(fd < 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800200 memset(keyBitmask, 0, sizeof(keyBitmask));
201 memset(absBitmask, 0, sizeof(absBitmask));
202 memset(relBitmask, 0, sizeof(relBitmask));
203 memset(swBitmask, 0, sizeof(swBitmask));
204 memset(ledBitmask, 0, sizeof(ledBitmask));
205 memset(ffBitmask, 0, sizeof(ffBitmask));
206 memset(propBitmask, 0, sizeof(propBitmask));
207}
208
209EventHub::Device::~Device() {
210 close();
211 delete configuration;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800212}
213
214void EventHub::Device::close() {
215 if (fd >= 0) {
216 ::close(fd);
217 fd = -1;
218 }
219}
220
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700221status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100222 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700223 if(fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100224 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700225 return -errno;
226 }
227 enabled = true;
228 return OK;
229}
230
231status_t EventHub::Device::disable() {
232 close();
233 enabled = false;
234 return OK;
235}
236
237bool EventHub::Device::hasValidFd() {
238 return !isVirtual && enabled;
239}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800240
241// --- EventHub ---
242
Michael Wrightd02c5b62014-02-10 15:10:22 -0800243const int EventHub::EPOLL_MAX_EVENTS;
244
245EventHub::EventHub(void) :
246 mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD), mNextDeviceId(1), mControllerNumbers(),
Yi Kong9b14ac62018-07-17 13:48:38 -0700247 mOpeningDevices(nullptr), mClosingDevices(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800248 mNeedToSendFinishedDeviceScan(false),
249 mNeedToReopenDevices(false), mNeedToScanDevices(true),
250 mPendingEventCount(0), mPendingEventIndex(0), mPendingINotify(false) {
251 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
252
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800253 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800254 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800255
256 mINotifyFd = inotify_init();
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800257 mInputWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
258 LOG_ALWAYS_FATAL_IF(mInputWd < 0, "Could not register INotify for %s: %s",
259 DEVICE_PATH, strerror(errno));
Philip Quinn39b81682019-01-09 22:20:39 -0800260 if (isV4lScanningEnabled()) {
261 mVideoWd = inotify_add_watch(mINotifyFd, VIDEO_DEVICE_PATH, IN_DELETE | IN_CREATE);
262 LOG_ALWAYS_FATAL_IF(mVideoWd < 0, "Could not register INotify for %s: %s",
263 VIDEO_DEVICE_PATH, strerror(errno));
264 } else {
265 mVideoWd = -1;
266 ALOGI("Video device scanning disabled");
267 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800268
269 struct epoll_event eventItem;
270 memset(&eventItem, 0, sizeof(eventItem));
271 eventItem.events = EPOLLIN;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700272 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800273 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800274 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
275
276 int wakeFds[2];
277 result = pipe(wakeFds);
278 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
279
280 mWakeReadPipeFd = wakeFds[0];
281 mWakeWritePipeFd = wakeFds[1];
282
283 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
284 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
285 errno);
286
287 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
288 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
289 errno);
290
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700291 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800292 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
293 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
294 errno);
295
296 int major, minor;
297 getLinuxRelease(&major, &minor);
298 // EPOLLWAKEUP was introduced in kernel 3.5
299 mUsingEpollWakeup = major > 3 || (major == 3 && minor >= 5);
300}
301
302EventHub::~EventHub(void) {
303 closeAllDevicesLocked();
304
305 while (mClosingDevices) {
306 Device* device = mClosingDevices;
307 mClosingDevices = device->next;
308 delete device;
309 }
310
311 ::close(mEpollFd);
312 ::close(mINotifyFd);
313 ::close(mWakeReadPipeFd);
314 ::close(mWakeWritePipeFd);
315
316 release_wake_lock(WAKE_LOCK_ID);
317}
318
319InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
320 AutoMutex _l(mLock);
321 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700322 if (device == nullptr) return InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800323 return device->identifier;
324}
325
326uint32_t EventHub::getDeviceClasses(int32_t deviceId) const {
327 AutoMutex _l(mLock);
328 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700329 if (device == nullptr) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800330 return device->classes;
331}
332
333int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
334 AutoMutex _l(mLock);
335 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700336 if (device == nullptr) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800337 return device->controllerNumber;
338}
339
340void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
341 AutoMutex _l(mLock);
342 Device* device = getDeviceLocked(deviceId);
343 if (device && device->configuration) {
344 *outConfiguration = *device->configuration;
345 } else {
346 outConfiguration->clear();
347 }
348}
349
350status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
351 RawAbsoluteAxisInfo* outAxisInfo) const {
352 outAxisInfo->clear();
353
354 if (axis >= 0 && axis <= ABS_MAX) {
355 AutoMutex _l(mLock);
356
357 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700358 if (device && device->hasValidFd() && test_bit(axis, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800359 struct input_absinfo info;
360 if(ioctl(device->fd, EVIOCGABS(axis), &info)) {
361 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100362 axis, device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800363 return -errno;
364 }
365
366 if (info.minimum != info.maximum) {
367 outAxisInfo->valid = true;
368 outAxisInfo->minValue = info.minimum;
369 outAxisInfo->maxValue = info.maximum;
370 outAxisInfo->flat = info.flat;
371 outAxisInfo->fuzz = info.fuzz;
372 outAxisInfo->resolution = info.resolution;
373 }
374 return OK;
375 }
376 }
377 return -1;
378}
379
380bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
381 if (axis >= 0 && axis <= REL_MAX) {
382 AutoMutex _l(mLock);
383
384 Device* device = getDeviceLocked(deviceId);
385 if (device) {
386 return test_bit(axis, device->relBitmask);
387 }
388 }
389 return false;
390}
391
392bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
393 if (property >= 0 && property <= INPUT_PROP_MAX) {
394 AutoMutex _l(mLock);
395
396 Device* device = getDeviceLocked(deviceId);
397 if (device) {
398 return test_bit(property, device->propBitmask);
399 }
400 }
401 return false;
402}
403
404int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
405 if (scanCode >= 0 && scanCode <= KEY_MAX) {
406 AutoMutex _l(mLock);
407
408 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700409 if (device && device->hasValidFd() && test_bit(scanCode, device->keyBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800410 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
411 memset(keyState, 0, sizeof(keyState));
412 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
413 return test_bit(scanCode, keyState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
414 }
415 }
416 }
417 return AKEY_STATE_UNKNOWN;
418}
419
420int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
421 AutoMutex _l(mLock);
422
423 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700424 if (device && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800425 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800426 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode, &scanCodes);
427 if (scanCodes.size() != 0) {
428 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
429 memset(keyState, 0, sizeof(keyState));
430 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
431 for (size_t i = 0; i < scanCodes.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800432 int32_t sc = scanCodes[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -0800433 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, keyState)) {
434 return AKEY_STATE_DOWN;
435 }
436 }
437 return AKEY_STATE_UP;
438 }
439 }
440 }
441 return AKEY_STATE_UNKNOWN;
442}
443
444int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
445 if (sw >= 0 && sw <= SW_MAX) {
446 AutoMutex _l(mLock);
447
448 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700449 if (device && device->hasValidFd() && test_bit(sw, device->swBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800450 uint8_t swState[sizeof_bit_array(SW_MAX + 1)];
451 memset(swState, 0, sizeof(swState));
452 if (ioctl(device->fd, EVIOCGSW(sizeof(swState)), swState) >= 0) {
453 return test_bit(sw, swState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
454 }
455 }
456 }
457 return AKEY_STATE_UNKNOWN;
458}
459
460status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
461 *outValue = 0;
462
463 if (axis >= 0 && axis <= ABS_MAX) {
464 AutoMutex _l(mLock);
465
466 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700467 if (device && device->hasValidFd() && test_bit(axis, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800468 struct input_absinfo info;
469 if(ioctl(device->fd, EVIOCGABS(axis), &info)) {
470 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100471 axis, device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800472 return -errno;
473 }
474
475 *outValue = info.value;
476 return OK;
477 }
478 }
479 return -1;
480}
481
482bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes,
483 const int32_t* keyCodes, uint8_t* outFlags) const {
484 AutoMutex _l(mLock);
485
486 Device* device = getDeviceLocked(deviceId);
487 if (device && device->keyMap.haveKeyLayout()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800488 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800489 for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) {
490 scanCodes.clear();
491
492 status_t err = device->keyMap.keyLayoutMap->findScanCodesForKey(
493 keyCodes[codeIndex], &scanCodes);
494 if (! err) {
495 // check the possible scan codes identified by the layout map against the
496 // map of codes actually emitted by the driver
497 for (size_t sc = 0; sc < scanCodes.size(); sc++) {
498 if (test_bit(scanCodes[sc], device->keyBitmask)) {
499 outFlags[codeIndex] = 1;
500 break;
501 }
502 }
503 }
504 }
505 return true;
506 }
507 return false;
508}
509
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700510status_t EventHub::mapKey(int32_t deviceId,
511 int32_t scanCode, int32_t usageCode, int32_t metaState,
512 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800513 AutoMutex _l(mLock);
514 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700515 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800516
517 if (device) {
518 // Check the key character map first.
519 sp<KeyCharacterMap> kcm = device->getKeyCharacterMap();
Yi Kong9b14ac62018-07-17 13:48:38 -0700520 if (kcm != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800521 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
522 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700523 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800524 }
525 }
526
527 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700528 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800529 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700530 status = NO_ERROR;
531 }
532 }
533
534 if (status == NO_ERROR) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700535 if (kcm != nullptr) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700536 kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState);
537 } else {
538 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800539 }
540 }
541 }
542
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700543 if (status != NO_ERROR) {
544 *outKeycode = 0;
545 *outFlags = 0;
546 *outMetaState = metaState;
547 }
548
549 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800550}
551
552status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
553 AutoMutex _l(mLock);
554 Device* device = getDeviceLocked(deviceId);
555
556 if (device && device->keyMap.haveKeyLayout()) {
557 status_t err = device->keyMap.keyLayoutMap->mapAxis(scanCode, outAxisInfo);
558 if (err == NO_ERROR) {
559 return NO_ERROR;
560 }
561 }
562
563 return NAME_NOT_FOUND;
564}
565
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100566void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800567 AutoMutex _l(mLock);
568
569 mExcludedDevices = devices;
570}
571
572bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
573 AutoMutex _l(mLock);
574 Device* device = getDeviceLocked(deviceId);
575 if (device && scanCode >= 0 && scanCode <= KEY_MAX) {
576 if (test_bit(scanCode, device->keyBitmask)) {
577 return true;
578 }
579 }
580 return false;
581}
582
583bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
584 AutoMutex _l(mLock);
585 Device* device = getDeviceLocked(deviceId);
586 int32_t sc;
587 if (device && mapLed(device, led, &sc) == NO_ERROR) {
588 if (test_bit(sc, device->ledBitmask)) {
589 return true;
590 }
591 }
592 return false;
593}
594
595void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
596 AutoMutex _l(mLock);
597 Device* device = getDeviceLocked(deviceId);
598 setLedStateLocked(device, led, on);
599}
600
601void EventHub::setLedStateLocked(Device* device, int32_t led, bool on) {
602 int32_t sc;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700603 if (device && device->hasValidFd() && mapLed(device, led, &sc) != NAME_NOT_FOUND) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800604 struct input_event ev;
605 ev.time.tv_sec = 0;
606 ev.time.tv_usec = 0;
607 ev.type = EV_LED;
608 ev.code = sc;
609 ev.value = on ? 1 : 0;
610
611 ssize_t nWrite;
612 do {
613 nWrite = write(device->fd, &ev, sizeof(struct input_event));
614 } while (nWrite == -1 && errno == EINTR);
615 }
616}
617
618void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800619 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800620 outVirtualKeys.clear();
621
622 AutoMutex _l(mLock);
623 Device* device = getDeviceLocked(deviceId);
624 if (device && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800625 const std::vector<VirtualKeyDefinition> virtualKeys =
626 device->virtualKeyMap->getVirtualKeys();
627 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800628 }
629}
630
631sp<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
632 AutoMutex _l(mLock);
633 Device* device = getDeviceLocked(deviceId);
634 if (device) {
635 return device->getKeyCharacterMap();
636 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700637 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800638}
639
640bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId,
641 const sp<KeyCharacterMap>& map) {
642 AutoMutex _l(mLock);
643 Device* device = getDeviceLocked(deviceId);
644 if (device) {
645 if (map != device->overlayKeyMap) {
646 device->overlayKeyMap = map;
647 device->combinedKeyMap = KeyCharacterMap::combine(
648 device->keyMap.keyCharacterMap, map);
649 return true;
650 }
651 }
652 return false;
653}
654
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100655static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
656 std::string rawDescriptor;
657 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800658 identifier.product);
659 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100660 if (!identifier.uniqueId.empty()) {
661 rawDescriptor += "uniqueId:";
662 rawDescriptor += identifier.uniqueId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800663 } else if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100664 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800665 }
666
667 if (identifier.vendor == 0 && identifier.product == 0) {
668 // If we don't know the vendor and product id, then the device is probably
669 // built-in so we need to rely on other information to uniquely identify
670 // the input device. Usually we try to avoid relying on the device name or
671 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100672 if (!identifier.name.empty()) {
673 rawDescriptor += "name:";
674 rawDescriptor += identifier.name;
675 } else if (!identifier.location.empty()) {
676 rawDescriptor += "location:";
677 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800678 }
679 }
680 identifier.descriptor = sha1(rawDescriptor);
681 return rawDescriptor;
682}
683
684void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
685 // Compute a device descriptor that uniquely identifies the device.
686 // The descriptor is assumed to be a stable identifier. Its value should not
687 // change between reboots, reconnections, firmware updates or new releases
688 // of Android. In practice we sometimes get devices that cannot be uniquely
689 // identified. In this case we enforce uniqueness between connected devices.
690 // Ideally, we also want the descriptor to be short and relatively opaque.
691
692 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100693 std::string rawDescriptor = generateDescriptor(identifier);
694 if (identifier.uniqueId.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800695 // If it didn't have a unique id check for conflicts and enforce
696 // uniqueness if necessary.
Yi Kong9b14ac62018-07-17 13:48:38 -0700697 while(getDeviceByDescriptorLocked(identifier.descriptor) != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800698 identifier.nonce++;
699 rawDescriptor = generateDescriptor(identifier);
700 }
701 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100702 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
703 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800704}
705
706void EventHub::vibrate(int32_t deviceId, nsecs_t duration) {
707 AutoMutex _l(mLock);
708 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700709 if (device && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800710 ff_effect effect;
711 memset(&effect, 0, sizeof(effect));
712 effect.type = FF_RUMBLE;
713 effect.id = device->ffEffectId;
714 effect.u.rumble.strong_magnitude = 0xc000;
715 effect.u.rumble.weak_magnitude = 0xc000;
716 effect.replay.length = (duration + 999999LL) / 1000000LL;
717 effect.replay.delay = 0;
718 if (ioctl(device->fd, EVIOCSFF, &effect)) {
719 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100720 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800721 return;
722 }
723 device->ffEffectId = effect.id;
724
725 struct input_event ev;
726 ev.time.tv_sec = 0;
727 ev.time.tv_usec = 0;
728 ev.type = EV_FF;
729 ev.code = device->ffEffectId;
730 ev.value = 1;
731 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
732 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100733 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800734 return;
735 }
736 device->ffEffectPlaying = true;
737 }
738}
739
740void EventHub::cancelVibrate(int32_t deviceId) {
741 AutoMutex _l(mLock);
742 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700743 if (device && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800744 if (device->ffEffectPlaying) {
745 device->ffEffectPlaying = false;
746
747 struct input_event ev;
748 ev.time.tv_sec = 0;
749 ev.time.tv_usec = 0;
750 ev.type = EV_FF;
751 ev.code = device->ffEffectId;
752 ev.value = 0;
753 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
754 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100755 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800756 return;
757 }
758 }
759 }
760}
761
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100762EventHub::Device* EventHub::getDeviceByDescriptorLocked(const std::string& descriptor) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800763 size_t size = mDevices.size();
764 for (size_t i = 0; i < size; i++) {
765 Device* device = mDevices.valueAt(i);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100766 if (descriptor == device->identifier.descriptor) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800767 return device;
768 }
769 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700770 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800771}
772
773EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -0800774 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800775 deviceId = mBuiltInKeyboardId;
776 }
777 ssize_t index = mDevices.indexOfKey(deviceId);
778 return index >= 0 ? mDevices.valueAt(index) : NULL;
779}
780
781EventHub::Device* EventHub::getDeviceByPathLocked(const char* devicePath) const {
782 for (size_t i = 0; i < mDevices.size(); i++) {
783 Device* device = mDevices.valueAt(i);
784 if (device->path == devicePath) {
785 return device;
786 }
787 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700788 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800789}
790
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700791/**
792 * The file descriptor could be either input device, or a video device (associated with a
793 * specific input device). Check both cases here, and return the device that this event
794 * belongs to. Caller can compare the fd's once more to determine event type.
795 * Looks through all input devices, and only attached video devices. Unattached video
796 * devices are ignored.
797 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700798EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
799 for (size_t i = 0; i < mDevices.size(); i++) {
800 Device* device = mDevices.valueAt(i);
801 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700802 // This is an input device event
803 return device;
804 }
805 if (device->videoDevice && device->videoDevice->getFd() == fd) {
806 // This is a video device event
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700807 return device;
808 }
809 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700810 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
811 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700812 return nullptr;
813}
814
Michael Wrightd02c5b62014-02-10 15:10:22 -0800815size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
816 ALOG_ASSERT(bufferSize >= 1);
817
818 AutoMutex _l(mLock);
819
820 struct input_event readBuffer[bufferSize];
821
822 RawEvent* event = buffer;
823 size_t capacity = bufferSize;
824 bool awoken = false;
825 for (;;) {
826 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
827
828 // Reopen input devices if needed.
829 if (mNeedToReopenDevices) {
830 mNeedToReopenDevices = false;
831
832 ALOGI("Reopening all input devices due to a configuration change.");
833
834 closeAllDevicesLocked();
835 mNeedToScanDevices = true;
836 break; // return to the caller before we actually rescan
837 }
838
839 // Report any devices that had last been added/removed.
840 while (mClosingDevices) {
841 Device* device = mClosingDevices;
842 ALOGV("Reporting device closed: id=%d, name=%s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100843 device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800844 mClosingDevices = device->next;
845 event->when = now;
Prabir Pradhancae4b3a2019-02-05 18:51:32 -0800846 event->deviceId = (device->id == mBuiltInKeyboardId) ?
847 ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800848 event->type = DEVICE_REMOVED;
849 event += 1;
850 delete device;
851 mNeedToSendFinishedDeviceScan = true;
852 if (--capacity == 0) {
853 break;
854 }
855 }
856
857 if (mNeedToScanDevices) {
858 mNeedToScanDevices = false;
859 scanDevicesLocked();
860 mNeedToSendFinishedDeviceScan = true;
861 }
862
Yi Kong9b14ac62018-07-17 13:48:38 -0700863 while (mOpeningDevices != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800864 Device* device = mOpeningDevices;
865 ALOGV("Reporting device opened: id=%d, name=%s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100866 device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800867 mOpeningDevices = device->next;
868 event->when = now;
869 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
870 event->type = DEVICE_ADDED;
871 event += 1;
872 mNeedToSendFinishedDeviceScan = true;
873 if (--capacity == 0) {
874 break;
875 }
876 }
877
878 if (mNeedToSendFinishedDeviceScan) {
879 mNeedToSendFinishedDeviceScan = false;
880 event->when = now;
881 event->type = FINISHED_DEVICE_SCAN;
882 event += 1;
883 if (--capacity == 0) {
884 break;
885 }
886 }
887
888 // Grab the next input event.
889 bool deviceChanged = false;
890 while (mPendingEventIndex < mPendingEventCount) {
891 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700892 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800893 if (eventItem.events & EPOLLIN) {
894 mPendingINotify = true;
895 } else {
896 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
897 }
898 continue;
899 }
900
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700901 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800902 if (eventItem.events & EPOLLIN) {
903 ALOGV("awoken after wake()");
904 awoken = true;
905 char buffer[16];
906 ssize_t nRead;
907 do {
908 nRead = read(mWakeReadPipeFd, buffer, sizeof(buffer));
909 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(buffer));
910 } else {
911 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
912 eventItem.events);
913 }
914 continue;
915 }
916
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700917 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700918 if (!device) {
919 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.",
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700920 eventItem.events, eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700921 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800922 continue;
923 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700924 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
925 if (eventItem.events & EPOLLIN) {
926 size_t numFrames = device->videoDevice->readAndQueueFrames();
927 if (numFrames == 0) {
928 ALOGE("Received epoll event for video device %s, but could not read frame",
929 device->videoDevice->getName().c_str());
930 }
931 } else if (eventItem.events & EPOLLHUP) {
932 // TODO(b/121395353) - consider adding EPOLLRDHUP
933 ALOGI("Removing video device %s due to epoll hang-up event.",
934 device->videoDevice->getName().c_str());
935 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
936 device->videoDevice = nullptr;
937 } else {
938 ALOGW("Received unexpected epoll event 0x%08x for device %s.",
939 eventItem.events, device->videoDevice->getName().c_str());
940 ALOG_ASSERT(!DEBUG);
941 }
942 continue;
943 }
944 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -0800945 if (eventItem.events & EPOLLIN) {
946 int32_t readSize = read(device->fd, readBuffer,
947 sizeof(struct input_event) * capacity);
948 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
949 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -0700950 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
951 " bufferSize: %zu capacity: %zu errno: %d)\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800952 device->fd, readSize, bufferSize, capacity, errno);
953 deviceChanged = true;
954 closeDeviceLocked(device);
955 } else if (readSize < 0) {
956 if (errno != EAGAIN && errno != EINTR) {
957 ALOGW("could not get event (errno=%d)", errno);
958 }
959 } else if ((readSize % sizeof(struct input_event)) != 0) {
960 ALOGE("could not get event (wrong size: %d)", readSize);
961 } else {
962 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
963
964 size_t count = size_t(readSize) / sizeof(struct input_event);
965 for (size_t i = 0; i < count; i++) {
966 struct input_event& iev = readBuffer[i];
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800967 event->when = processEventTimestamp(iev);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800968 event->deviceId = deviceId;
969 event->type = iev.type;
970 event->code = iev.code;
971 event->value = iev.value;
972 event += 1;
973 capacity -= 1;
974 }
975 if (capacity == 0) {
976 // The result buffer is full. Reset the pending event index
977 // so we will try to read the device again on the next iteration.
978 mPendingEventIndex -= 1;
979 break;
980 }
981 }
982 } else if (eventItem.events & EPOLLHUP) {
983 ALOGI("Removing device %s due to epoll hang-up event.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100984 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800985 deviceChanged = true;
986 closeDeviceLocked(device);
987 } else {
988 ALOGW("Received unexpected epoll event 0x%08x for device %s.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100989 eventItem.events, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800990 }
991 }
992
993 // readNotify() will modify the list of devices so this must be done after
994 // processing all other events to ensure that we read all remaining events
995 // before closing the devices.
996 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
997 mPendingINotify = false;
998 readNotifyLocked();
999 deviceChanged = true;
1000 }
1001
1002 // Report added or removed devices immediately.
1003 if (deviceChanged) {
1004 continue;
1005 }
1006
1007 // Return now if we have collected any events or if we were explicitly awoken.
1008 if (event != buffer || awoken) {
1009 break;
1010 }
1011
1012 // Poll for events. Mind the wake lock dance!
1013 // We hold a wake lock at all times except during epoll_wait(). This works due to some
1014 // subtle choreography. When a device driver has pending (unread) events, it acquires
1015 // a kernel wake lock. However, once the last pending event has been read, the device
1016 // driver will release the kernel wake lock. To prevent the system from going to sleep
1017 // when this happens, the EventHub holds onto its own user wake lock while the client
1018 // is processing events. Thus the system can only sleep if there are no events
1019 // pending or currently being processed.
1020 //
1021 // The timeout is advisory only. If the device is asleep, it will not wake just to
1022 // service the timeout.
1023 mPendingEventIndex = 0;
1024
1025 mLock.unlock(); // release lock before poll, must be before release_wake_lock
1026 release_wake_lock(WAKE_LOCK_ID);
1027
1028 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1029
1030 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
1031 mLock.lock(); // reacquire lock after poll, must be after acquire_wake_lock
1032
1033 if (pollResult == 0) {
1034 // Timed out.
1035 mPendingEventCount = 0;
1036 break;
1037 }
1038
1039 if (pollResult < 0) {
1040 // An error occurred.
1041 mPendingEventCount = 0;
1042
1043 // Sleep after errors to avoid locking up the system.
1044 // Hopefully the error is transient.
1045 if (errno != EINTR) {
1046 ALOGW("poll failed (errno=%d)\n", errno);
1047 usleep(100000);
1048 }
1049 } else {
1050 // Some events occurred.
1051 mPendingEventCount = size_t(pollResult);
1052 }
1053 }
1054
1055 // All done, return the number of events we read.
1056 return event - buffer;
1057}
1058
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001059std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
1060 AutoMutex _l(mLock);
1061
1062 Device* device = getDeviceLocked(deviceId);
1063 if (!device || !device->videoDevice) {
1064 return {};
1065 }
1066 return device->videoDevice->consumeFrames();
1067}
1068
Michael Wrightd02c5b62014-02-10 15:10:22 -08001069void EventHub::wake() {
1070 ALOGV("wake() called");
1071
1072 ssize_t nWrite;
1073 do {
1074 nWrite = write(mWakeWritePipeFd, "W", 1);
1075 } while (nWrite == -1 && errno == EINTR);
1076
1077 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001078 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001079 }
1080}
1081
1082void EventHub::scanDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001083 status_t result = scanDirLocked(DEVICE_PATH);
1084 if(result < 0) {
1085 ALOGE("scan dir failed for %s", DEVICE_PATH);
1086 }
Philip Quinn39b81682019-01-09 22:20:39 -08001087 if (isV4lScanningEnabled()) {
1088 result = scanVideoDirLocked(VIDEO_DEVICE_PATH);
1089 if (result != OK) {
1090 ALOGE("scan video dir failed for %s", VIDEO_DEVICE_PATH);
1091 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001092 }
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001093 if (mDevices.indexOfKey(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) < 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001094 createVirtualKeyboardLocked();
1095 }
1096}
1097
1098// ----------------------------------------------------------------------------
1099
1100static bool containsNonZeroByte(const uint8_t* array, uint32_t startIndex, uint32_t endIndex) {
1101 const uint8_t* end = array + endIndex;
1102 array += startIndex;
1103 while (array != end) {
1104 if (*(array++) != 0) {
1105 return true;
1106 }
1107 }
1108 return false;
1109}
1110
1111static const int32_t GAMEPAD_KEYCODES[] = {
1112 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C,
1113 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z,
1114 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1,
1115 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2,
1116 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR,
1117 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001118};
1119
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001120status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001121 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001122 struct epoll_event eventItem = {};
1123 eventItem.events = EPOLLIN | EPOLLWAKEUP;
1124 eventItem.data.fd = fd;
1125 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1126 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001127 return -errno;
1128 }
1129 return OK;
1130}
1131
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001132status_t EventHub::unregisterFdFromEpoll(int fd) {
1133 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
1134 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
1135 return -errno;
1136 }
1137 return OK;
1138}
1139
1140status_t EventHub::registerDeviceForEpollLocked(Device* device) {
1141 if (device == nullptr) {
1142 if (DEBUG) {
1143 LOG_ALWAYS_FATAL("Cannot call registerDeviceForEpollLocked with null Device");
1144 }
1145 return BAD_VALUE;
1146 }
1147 status_t result = registerFdForEpoll(device->fd);
1148 if (result != OK) {
1149 ALOGE("Could not add input device fd to epoll for device %" PRId32, device->id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001150 return result;
1151 }
1152 if (device->videoDevice) {
1153 registerVideoDeviceForEpollLocked(*device->videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001154 }
1155 return result;
1156}
1157
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001158void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
1159 status_t result = registerFdForEpoll(videoDevice.getFd());
1160 if (result != OK) {
1161 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
1162 }
1163}
1164
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001165status_t EventHub::unregisterDeviceFromEpollLocked(Device* device) {
1166 if (device->hasValidFd()) {
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001167 status_t result = unregisterFdFromEpoll(device->fd);
1168 if (result != OK) {
1169 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device->id);
1170 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001171 }
1172 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001173 if (device->videoDevice) {
1174 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1175 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001176 return OK;
1177}
1178
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001179void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
1180 if (videoDevice.hasValidFd()) {
1181 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
1182 if (result != OK) {
1183 ALOGW("Could not remove video device fd from epoll for device: %s",
1184 videoDevice.getName().c_str());
1185 }
1186 }
1187}
1188
1189status_t EventHub::openDeviceLocked(const char* devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001190 char buffer[80];
1191
1192 ALOGV("Opening device: %s", devicePath);
1193
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001194 int fd = open(devicePath, O_RDWR | O_CLOEXEC | O_NONBLOCK);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001195 if(fd < 0) {
1196 ALOGE("could not open %s, %s\n", devicePath, strerror(errno));
1197 return -1;
1198 }
1199
1200 InputDeviceIdentifier identifier;
1201
1202 // Get device name.
1203 if(ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001204 ALOGE("Could not get device name for %s: %s", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001205 } else {
1206 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001207 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001208 }
1209
1210 // Check to see if the device is on our excluded list
1211 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001212 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001213 if (identifier.name == item) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001214 ALOGI("ignoring event id %s driver %s\n", devicePath, item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001215 close(fd);
1216 return -1;
1217 }
1218 }
1219
1220 // Get device driver version.
1221 int driverVersion;
1222 if(ioctl(fd, EVIOCGVERSION, &driverVersion)) {
1223 ALOGE("could not get driver version for %s, %s\n", devicePath, strerror(errno));
1224 close(fd);
1225 return -1;
1226 }
1227
1228 // Get device identifier.
1229 struct input_id inputId;
1230 if(ioctl(fd, EVIOCGID, &inputId)) {
1231 ALOGE("could not get device input id for %s, %s\n", devicePath, strerror(errno));
1232 close(fd);
1233 return -1;
1234 }
1235 identifier.bus = inputId.bustype;
1236 identifier.product = inputId.product;
1237 identifier.vendor = inputId.vendor;
1238 identifier.version = inputId.version;
1239
1240 // Get device physical location.
1241 if(ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
1242 //fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
1243 } else {
1244 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001245 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001246 }
1247
1248 // Get device unique id.
1249 if(ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
1250 //fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
1251 } else {
1252 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001253 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001254 }
1255
1256 // Fill in the descriptor.
1257 assignDescriptorLocked(identifier);
1258
Michael Wrightd02c5b62014-02-10 15:10:22 -08001259 // Allocate device. (The device object takes ownership of the fd at this point.)
1260 int32_t deviceId = mNextDeviceId++;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001261 Device* device = new Device(fd, deviceId, devicePath, identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001262
1263 ALOGV("add device %d: %s\n", deviceId, devicePath);
1264 ALOGV(" bus: %04x\n"
1265 " vendor %04x\n"
1266 " product %04x\n"
1267 " version %04x\n",
1268 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001269 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
1270 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
1271 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
1272 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001273 ALOGV(" driver: v%d.%d.%d\n",
1274 driverVersion >> 16, (driverVersion >> 8) & 0xff, driverVersion & 0xff);
1275
1276 // Load the configuration file for the device.
1277 loadConfigurationLocked(device);
1278
1279 // Figure out the kinds of events the device reports.
1280 ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(device->keyBitmask)), device->keyBitmask);
1281 ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(device->absBitmask)), device->absBitmask);
1282 ioctl(fd, EVIOCGBIT(EV_REL, sizeof(device->relBitmask)), device->relBitmask);
1283 ioctl(fd, EVIOCGBIT(EV_SW, sizeof(device->swBitmask)), device->swBitmask);
1284 ioctl(fd, EVIOCGBIT(EV_LED, sizeof(device->ledBitmask)), device->ledBitmask);
1285 ioctl(fd, EVIOCGBIT(EV_FF, sizeof(device->ffBitmask)), device->ffBitmask);
1286 ioctl(fd, EVIOCGPROP(sizeof(device->propBitmask)), device->propBitmask);
1287
1288 // See if this is a keyboard. Ignore everything in the button range except for
1289 // joystick and gamepad buttons which are handled like keyboards for the most part.
1290 bool haveKeyboardKeys = containsNonZeroByte(device->keyBitmask, 0, sizeof_bit_array(BTN_MISC))
1291 || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(KEY_OK),
1292 sizeof_bit_array(KEY_MAX + 1));
1293 bool haveGamepadButtons = containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_MISC),
1294 sizeof_bit_array(BTN_MOUSE))
1295 || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_JOYSTICK),
1296 sizeof_bit_array(BTN_DIGI));
1297 if (haveKeyboardKeys || haveGamepadButtons) {
1298 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1299 }
1300
1301 // See if this is a cursor device such as a trackball or mouse.
1302 if (test_bit(BTN_MOUSE, device->keyBitmask)
1303 && test_bit(REL_X, device->relBitmask)
1304 && test_bit(REL_Y, device->relBitmask)) {
1305 device->classes |= INPUT_DEVICE_CLASS_CURSOR;
1306 }
1307
Prashant Malani1941ff52015-08-11 18:29:28 -07001308 // See if this is a rotary encoder type device.
1309 String8 deviceType = String8();
1310 if (device->configuration &&
1311 device->configuration->tryGetProperty(String8("device.type"), deviceType)) {
1312 if (!deviceType.compare(String8("rotaryEncoder"))) {
1313 device->classes |= INPUT_DEVICE_CLASS_ROTARY_ENCODER;
1314 }
1315 }
1316
Michael Wrightd02c5b62014-02-10 15:10:22 -08001317 // See if this is a touch pad.
1318 // Is this a new modern multi-touch driver?
1319 if (test_bit(ABS_MT_POSITION_X, device->absBitmask)
1320 && test_bit(ABS_MT_POSITION_Y, device->absBitmask)) {
1321 // Some joysticks such as the PS3 controller report axes that conflict
1322 // with the ABS_MT range. Try to confirm that the device really is
1323 // a touch screen.
1324 if (test_bit(BTN_TOUCH, device->keyBitmask) || !haveGamepadButtons) {
1325 device->classes |= INPUT_DEVICE_CLASS_TOUCH | INPUT_DEVICE_CLASS_TOUCH_MT;
1326 }
1327 // Is this an old style single-touch driver?
1328 } else if (test_bit(BTN_TOUCH, device->keyBitmask)
1329 && test_bit(ABS_X, device->absBitmask)
1330 && test_bit(ABS_Y, device->absBitmask)) {
1331 device->classes |= INPUT_DEVICE_CLASS_TOUCH;
Michael Wright842500e2015-03-13 17:32:02 -07001332 // Is this a BT stylus?
1333 } else if ((test_bit(ABS_PRESSURE, device->absBitmask) ||
1334 test_bit(BTN_TOUCH, device->keyBitmask))
1335 && !test_bit(ABS_X, device->absBitmask)
1336 && !test_bit(ABS_Y, device->absBitmask)) {
1337 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
1338 // Keyboard will try to claim some of the buttons but we really want to reserve those so we
1339 // can fuse it with the touch screen data, so just take them back. Note this means an
1340 // external stylus cannot also be a keyboard device.
1341 device->classes &= ~INPUT_DEVICE_CLASS_KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001342 }
1343
1344 // See if this device is a joystick.
1345 // Assumes that joysticks always have gamepad buttons in order to distinguish them
1346 // from other devices such as accelerometers that also have absolute axes.
1347 if (haveGamepadButtons) {
1348 uint32_t assumedClasses = device->classes | INPUT_DEVICE_CLASS_JOYSTICK;
1349 for (int i = 0; i <= ABS_MAX; i++) {
1350 if (test_bit(i, device->absBitmask)
1351 && (getAbsAxisUsage(i, assumedClasses) & INPUT_DEVICE_CLASS_JOYSTICK)) {
1352 device->classes = assumedClasses;
1353 break;
1354 }
1355 }
1356 }
1357
1358 // Check whether this device has switches.
1359 for (int i = 0; i <= SW_MAX; i++) {
1360 if (test_bit(i, device->swBitmask)) {
1361 device->classes |= INPUT_DEVICE_CLASS_SWITCH;
1362 break;
1363 }
1364 }
1365
1366 // Check whether this device supports the vibrator.
1367 if (test_bit(FF_RUMBLE, device->ffBitmask)) {
1368 device->classes |= INPUT_DEVICE_CLASS_VIBRATOR;
1369 }
1370
1371 // Configure virtual keys.
1372 if ((device->classes & INPUT_DEVICE_CLASS_TOUCH)) {
1373 // Load the virtual keys for the touch screen, if any.
1374 // We do this now so that we can make sure to load the keymap if necessary.
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001375 bool success = loadVirtualKeyMapLocked(device);
1376 if (success) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001377 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1378 }
1379 }
1380
1381 // Load the key map.
1382 // We need to do this for joysticks too because the key layout may specify axes.
1383 status_t keyMapStatus = NAME_NOT_FOUND;
1384 if (device->classes & (INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_JOYSTICK)) {
1385 // Load the keymap for the device.
1386 keyMapStatus = loadKeyMapLocked(device);
1387 }
1388
1389 // Configure the keyboard, gamepad or virtual keyboard.
1390 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1391 // Register the keyboard as a built-in keyboard if it is eligible.
1392 if (!keyMapStatus
1393 && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD
1394 && isEligibleBuiltInKeyboard(device->identifier,
1395 device->configuration, &device->keyMap)) {
1396 mBuiltInKeyboardId = device->id;
1397 }
1398
1399 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
1400 if (hasKeycodeLocked(device, AKEYCODE_Q)) {
1401 device->classes |= INPUT_DEVICE_CLASS_ALPHAKEY;
1402 }
1403
1404 // See if this device has a DPAD.
1405 if (hasKeycodeLocked(device, AKEYCODE_DPAD_UP) &&
1406 hasKeycodeLocked(device, AKEYCODE_DPAD_DOWN) &&
1407 hasKeycodeLocked(device, AKEYCODE_DPAD_LEFT) &&
1408 hasKeycodeLocked(device, AKEYCODE_DPAD_RIGHT) &&
1409 hasKeycodeLocked(device, AKEYCODE_DPAD_CENTER)) {
1410 device->classes |= INPUT_DEVICE_CLASS_DPAD;
1411 }
1412
1413 // See if this device has a gamepad.
1414 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES)/sizeof(GAMEPAD_KEYCODES[0]); i++) {
1415 if (hasKeycodeLocked(device, GAMEPAD_KEYCODES[i])) {
1416 device->classes |= INPUT_DEVICE_CLASS_GAMEPAD;
1417 break;
1418 }
1419 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001420 }
1421
1422 // If the device isn't recognized as something we handle, don't monitor it.
1423 if (device->classes == 0) {
1424 ALOGV("Dropping device: id=%d, path='%s', name='%s'",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001425 deviceId, devicePath, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001426 delete device;
1427 return -1;
1428 }
1429
Tim Kilbourn063ff532015-04-08 10:26:18 -07001430 // Determine whether the device has a mic.
1431 if (deviceHasMicLocked(device)) {
1432 device->classes |= INPUT_DEVICE_CLASS_MIC;
1433 }
1434
Michael Wrightd02c5b62014-02-10 15:10:22 -08001435 // Determine whether the device is external or internal.
1436 if (isExternalDeviceLocked(device)) {
1437 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL;
1438 }
1439
Michael Wright42f2c6a2014-03-12 10:33:03 -07001440 if (device->classes & (INPUT_DEVICE_CLASS_JOYSTICK | INPUT_DEVICE_CLASS_DPAD)
1441 && device->classes & INPUT_DEVICE_CLASS_GAMEPAD) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001442 device->controllerNumber = getNextControllerNumberLocked(device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001443 setLedForControllerLocked(device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001444 }
1445
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001446 // Find a matching video device by comparing device names
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001447 // This should be done before registerDeviceForEpollLocked, so that both fds are added to epoll
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001448 for (std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
1449 if (device->identifier.name == videoDevice->getName()) {
1450 device->videoDevice = std::move(videoDevice);
1451 break;
1452 }
1453 }
1454 mUnattachedVideoDevices.erase(std::remove_if(mUnattachedVideoDevices.begin(),
1455 mUnattachedVideoDevices.end(),
1456 [](const std::unique_ptr<TouchVideoDevice>& videoDevice){
1457 return videoDevice == nullptr; }), mUnattachedVideoDevices.end());
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001458
1459 if (registerDeviceForEpollLocked(device) != OK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001460 delete device;
1461 return -1;
1462 }
1463
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001464 configureFd(device);
1465
1466 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=0x%x, "
1467 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001468 deviceId, fd, devicePath, device->identifier.name.c_str(),
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001469 device->classes,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001470 device->configurationFile.c_str(),
1471 device->keyMap.keyLayoutFile.c_str(),
1472 device->keyMap.keyCharacterMapFile.c_str(),
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001473 toString(mBuiltInKeyboardId == deviceId));
1474
1475 addDeviceLocked(device);
1476 return OK;
1477}
1478
1479void EventHub::configureFd(Device* device) {
1480 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
1481 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1482 // Disable kernel key repeat since we handle it ourselves
1483 unsigned int repeatRate[] = {0, 0};
1484 if (ioctl(device->fd, EVIOCSREP, repeatRate)) {
1485 ALOGW("Unable to disable kernel key repeat for %s: %s",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001486 device->path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001487 }
1488 }
1489
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001490 std::string wakeMechanism = "EPOLLWAKEUP";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001491 if (!mUsingEpollWakeup) {
1492#ifndef EVIOCSSUSPENDBLOCK
1493 // uapi headers don't include EVIOCSSUSPENDBLOCK, and future kernels
1494 // will use an epoll flag instead, so as long as we want to support
1495 // this feature, we need to be prepared to define the ioctl ourselves.
1496#define EVIOCSSUSPENDBLOCK _IOW('E', 0x91, int)
1497#endif
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001498 if (ioctl(device->fd, EVIOCSSUSPENDBLOCK, 1)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001499 wakeMechanism = "<none>";
1500 } else {
1501 wakeMechanism = "EVIOCSSUSPENDBLOCK";
1502 }
1503 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001504 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
1505 // associated with input events. This is important because the input system
1506 // uses the timestamps extensively and assumes they were recorded using the monotonic
1507 // clock.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001508 int clockId = CLOCK_MONOTONIC;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001509 bool usingClockIoctl = !ioctl(device->fd, EVIOCSCLOCKID, &clockId);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001510 ALOGI("wakeMechanism=%s, usingClockIoctl=%s", wakeMechanism.c_str(),
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001511 toString(usingClockIoctl));
1512}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001513
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001514void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
1515 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
1516 if (!videoDevice) {
1517 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
1518 return;
1519 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001520 // Transfer ownership of this video device to a matching input device
1521 for (size_t i = 0; i < mDevices.size(); i++) {
1522 Device* device = mDevices.valueAt(i);
1523 if (videoDevice->getName() == device->identifier.name) {
1524 device->videoDevice = std::move(videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001525 if (device->enabled) {
1526 registerVideoDeviceForEpollLocked(*device->videoDevice);
1527 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001528 return;
1529 }
1530 }
1531
1532 // Couldn't find a matching input device, so just add it to a temporary holding queue.
1533 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001534 ALOGI("Adding video device %s to list of unattached video devices",
1535 videoDevice->getName().c_str());
1536 mUnattachedVideoDevices.push_back(std::move(videoDevice));
1537}
1538
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001539bool EventHub::isDeviceEnabled(int32_t deviceId) {
1540 AutoMutex _l(mLock);
1541 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001542 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001543 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1544 return false;
1545 }
1546 return device->enabled;
1547}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001548
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001549status_t EventHub::enableDevice(int32_t deviceId) {
1550 AutoMutex _l(mLock);
1551 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001552 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001553 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1554 return BAD_VALUE;
1555 }
1556 if (device->enabled) {
1557 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
1558 return OK;
1559 }
1560 status_t result = device->enable();
1561 if (result != OK) {
1562 ALOGE("Failed to enable device %" PRId32, deviceId);
1563 return result;
1564 }
1565
1566 configureFd(device);
1567
1568 return registerDeviceForEpollLocked(device);
1569}
1570
1571status_t EventHub::disableDevice(int32_t deviceId) {
1572 AutoMutex _l(mLock);
1573 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001574 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001575 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1576 return BAD_VALUE;
1577 }
1578 if (!device->enabled) {
1579 ALOGW("Duplicate call to %s, input device already disabled", __func__);
1580 return OK;
1581 }
1582 unregisterDeviceFromEpollLocked(device);
1583 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001584}
1585
1586void EventHub::createVirtualKeyboardLocked() {
1587 InputDeviceIdentifier identifier;
1588 identifier.name = "Virtual";
1589 identifier.uniqueId = "<virtual>";
1590 assignDescriptorLocked(identifier);
1591
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001592 Device* device = new Device(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
1593 identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001594 device->classes = INPUT_DEVICE_CLASS_KEYBOARD
1595 | INPUT_DEVICE_CLASS_ALPHAKEY
1596 | INPUT_DEVICE_CLASS_DPAD
1597 | INPUT_DEVICE_CLASS_VIRTUAL;
1598 loadKeyMapLocked(device);
1599 addDeviceLocked(device);
1600}
1601
1602void EventHub::addDeviceLocked(Device* device) {
1603 mDevices.add(device->id, device);
1604 device->next = mOpeningDevices;
1605 mOpeningDevices = device;
1606}
1607
1608void EventHub::loadConfigurationLocked(Device* device) {
1609 device->configurationFile = getInputDeviceConfigurationFilePathByDeviceIdentifier(
1610 device->identifier, INPUT_DEVICE_CONFIGURATION_FILE_TYPE_CONFIGURATION);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001611 if (device->configurationFile.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001612 ALOGD("No input device configuration file found for device '%s'.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001613 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001614 } else {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001615 status_t status = PropertyMap::load(String8(device->configurationFile.c_str()),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001616 &device->configuration);
1617 if (status) {
1618 ALOGE("Error loading input device configuration file for device '%s'. "
1619 "Using default configuration.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001620 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001621 }
1622 }
1623}
1624
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001625bool EventHub::loadVirtualKeyMapLocked(Device* device) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001626 // The virtual key map is supplied by the kernel as a system board property file.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001627 std::string path;
1628 path += "/sys/board_properties/virtualkeys.";
Siarhei Vishniakoub45635c2019-02-20 19:22:09 -06001629 path += device->identifier.getCanonicalName();
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001630 if (access(path.c_str(), R_OK)) {
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001631 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001632 }
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001633 device->virtualKeyMap = VirtualKeyMap::load(path);
1634 return device->virtualKeyMap != nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001635}
1636
1637status_t EventHub::loadKeyMapLocked(Device* device) {
1638 return device->keyMap.load(device->identifier, device->configuration);
1639}
1640
1641bool EventHub::isExternalDeviceLocked(Device* device) {
1642 if (device->configuration) {
1643 bool value;
1644 if (device->configuration->tryGetProperty(String8("device.internal"), value)) {
1645 return !value;
1646 }
1647 }
1648 return device->identifier.bus == BUS_USB || device->identifier.bus == BUS_BLUETOOTH;
1649}
1650
Tim Kilbourn063ff532015-04-08 10:26:18 -07001651bool EventHub::deviceHasMicLocked(Device* device) {
1652 if (device->configuration) {
1653 bool value;
1654 if (device->configuration->tryGetProperty(String8("audio.mic"), value)) {
1655 return value;
1656 }
1657 }
1658 return false;
1659}
1660
Michael Wrightd02c5b62014-02-10 15:10:22 -08001661int32_t EventHub::getNextControllerNumberLocked(Device* device) {
1662 if (mControllerNumbers.isFull()) {
1663 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001664 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001665 return 0;
1666 }
1667 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
1668 // one
1669 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
1670}
1671
1672void EventHub::releaseControllerNumberLocked(Device* device) {
1673 int32_t num = device->controllerNumber;
1674 device->controllerNumber= 0;
1675 if (num == 0) {
1676 return;
1677 }
1678 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
1679}
1680
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001681void EventHub::setLedForControllerLocked(Device* device) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001682 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
1683 setLedStateLocked(device, ALED_CONTROLLER_1 + i, device->controllerNumber == i + 1);
1684 }
1685}
1686
1687bool EventHub::hasKeycodeLocked(Device* device, int keycode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001688 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001689 return false;
1690 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001691
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001692 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001693 device->keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes);
1694 const size_t N = scanCodes.size();
1695 for (size_t i=0; i<N && i<=KEY_MAX; i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001696 int32_t sc = scanCodes[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001697 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, device->keyBitmask)) {
1698 return true;
1699 }
1700 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001701
Michael Wrightd02c5b62014-02-10 15:10:22 -08001702 return false;
1703}
1704
1705status_t EventHub::mapLed(Device* device, int32_t led, int32_t* outScanCode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001706 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001707 return NAME_NOT_FOUND;
1708 }
1709
1710 int32_t scanCode;
1711 if(device->keyMap.keyLayoutMap->findScanCodeForLed(led, &scanCode) != NAME_NOT_FOUND) {
1712 if(scanCode >= 0 && scanCode <= LED_MAX && test_bit(scanCode, device->ledBitmask)) {
1713 *outScanCode = scanCode;
1714 return NO_ERROR;
1715 }
1716 }
1717 return NAME_NOT_FOUND;
1718}
1719
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001720void EventHub::closeDeviceByPathLocked(const char *devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001721 Device* device = getDeviceByPathLocked(devicePath);
1722 if (device) {
1723 closeDeviceLocked(device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001724 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001725 }
1726 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001727}
1728
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001729/**
1730 * Find the video device by filename, and close it.
1731 * The video device is closed by path during an inotify event, where we don't have the
1732 * additional context about the video device fd, or the associated input device.
1733 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001734void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001735 // A video device may be owned by an existing input device, or it may be stored in
1736 // the mUnattachedVideoDevices queue. Check both locations.
1737 for (size_t i = 0; i < mDevices.size(); i++) {
1738 Device* device = mDevices.valueAt(i);
1739 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001740 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001741 device->videoDevice = nullptr;
1742 return;
1743 }
1744 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001745 mUnattachedVideoDevices.erase(std::remove_if(mUnattachedVideoDevices.begin(),
1746 mUnattachedVideoDevices.end(), [&devicePath](
1747 const std::unique_ptr<TouchVideoDevice>& videoDevice) {
1748 return videoDevice->getPath() == devicePath; }), mUnattachedVideoDevices.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001749}
1750
1751void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001752 mUnattachedVideoDevices.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001753 while (mDevices.size() > 0) {
1754 closeDeviceLocked(mDevices.valueAt(mDevices.size() - 1));
1755 }
1756}
1757
1758void EventHub::closeDeviceLocked(Device* device) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001759 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=0x%x",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001760 device->path.c_str(), device->identifier.name.c_str(), device->id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001761 device->fd, device->classes);
1762
1763 if (device->id == mBuiltInKeyboardId) {
1764 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001765 device->path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001766 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
1767 }
1768
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001769 unregisterDeviceFromEpollLocked(device);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001770 if (device->videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001771 // This must be done after the video device is removed from epoll
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001772 mUnattachedVideoDevices.push_back(std::move(device->videoDevice));
1773 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001774
1775 releaseControllerNumberLocked(device);
1776
1777 mDevices.removeItem(device->id);
1778 device->close();
1779
1780 // Unlink for opening devices list if it is present.
Yi Kong9b14ac62018-07-17 13:48:38 -07001781 Device* pred = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001782 bool found = false;
Yi Kong9b14ac62018-07-17 13:48:38 -07001783 for (Device* entry = mOpeningDevices; entry != nullptr; ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001784 if (entry == device) {
1785 found = true;
1786 break;
1787 }
1788 pred = entry;
1789 entry = entry->next;
1790 }
1791 if (found) {
1792 // Unlink the device from the opening devices list then delete it.
1793 // We don't need to tell the client that the device was closed because
1794 // it does not even know it was opened in the first place.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001795 ALOGI("Device %s was immediately closed after opening.", device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001796 if (pred) {
1797 pred->next = device->next;
1798 } else {
1799 mOpeningDevices = device->next;
1800 }
1801 delete device;
1802 } else {
1803 // Link into closing devices list.
1804 // The device will be deleted later after we have informed the client.
1805 device->next = mClosingDevices;
1806 mClosingDevices = device;
1807 }
1808}
1809
1810status_t EventHub::readNotifyLocked() {
1811 int res;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001812 char event_buf[512];
1813 int event_size;
1814 int event_pos = 0;
1815 struct inotify_event *event;
1816
1817 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
1818 res = read(mINotifyFd, event_buf, sizeof(event_buf));
1819 if(res < (int)sizeof(*event)) {
1820 if(errno == EINTR)
1821 return 0;
1822 ALOGW("could not get event, %s\n", strerror(errno));
1823 return -1;
1824 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001825
1826 while(res >= (int)sizeof(*event)) {
1827 event = (struct inotify_event *)(event_buf + event_pos);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001828 if(event->len) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001829 if (event->wd == mInputWd) {
1830 std::string filename = StringPrintf("%s/%s", DEVICE_PATH, event->name);
1831 if(event->mask & IN_CREATE) {
1832 openDeviceLocked(filename.c_str());
1833 } else {
1834 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
1835 closeDeviceByPathLocked(filename.c_str());
1836 }
1837 }
1838 else if (event->wd == mVideoWd) {
1839 if (isV4lTouchNode(event->name)) {
1840 std::string filename = StringPrintf("%s/%s", VIDEO_DEVICE_PATH, event->name);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001841 if (event->mask & IN_CREATE) {
1842 openVideoDeviceLocked(filename);
1843 } else {
1844 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
1845 closeVideoDeviceByPathLocked(filename);
1846 }
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001847 }
1848 }
1849 else {
1850 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event->wd);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001851 }
1852 }
1853 event_size = sizeof(*event) + event->len;
1854 res -= event_size;
1855 event_pos += event_size;
1856 }
1857 return 0;
1858}
1859
1860status_t EventHub::scanDirLocked(const char *dirname)
1861{
1862 char devname[PATH_MAX];
1863 char *filename;
1864 DIR *dir;
1865 struct dirent *de;
1866 dir = opendir(dirname);
Yi Kong9b14ac62018-07-17 13:48:38 -07001867 if(dir == nullptr)
Michael Wrightd02c5b62014-02-10 15:10:22 -08001868 return -1;
1869 strcpy(devname, dirname);
1870 filename = devname + strlen(devname);
1871 *filename++ = '/';
1872 while((de = readdir(dir))) {
1873 if(de->d_name[0] == '.' &&
1874 (de->d_name[1] == '\0' ||
1875 (de->d_name[1] == '.' && de->d_name[2] == '\0')))
1876 continue;
1877 strcpy(filename, de->d_name);
1878 openDeviceLocked(devname);
1879 }
1880 closedir(dir);
1881 return 0;
1882}
1883
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001884/**
1885 * Look for all dirname/v4l-touch* devices, and open them.
1886 */
1887status_t EventHub::scanVideoDirLocked(const std::string& dirname)
1888{
1889 DIR* dir;
1890 struct dirent* de;
1891 dir = opendir(dirname.c_str());
1892 if(!dir) {
1893 ALOGE("Could not open video directory %s", dirname.c_str());
1894 return BAD_VALUE;
1895 }
1896
1897 while((de = readdir(dir))) {
1898 const char* name = de->d_name;
1899 if (isV4lTouchNode(name)) {
1900 ALOGI("Found touch video device %s", name);
1901 openVideoDeviceLocked(dirname + "/" + name);
1902 }
1903 }
1904 closedir(dir);
1905 return OK;
1906}
1907
Michael Wrightd02c5b62014-02-10 15:10:22 -08001908void EventHub::requestReopenDevices() {
1909 ALOGV("requestReopenDevices() called");
1910
1911 AutoMutex _l(mLock);
1912 mNeedToReopenDevices = true;
1913}
1914
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001915void EventHub::dump(std::string& dump) {
1916 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001917
1918 { // acquire lock
1919 AutoMutex _l(mLock);
1920
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001921 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001922
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001923 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001924
1925 for (size_t i = 0; i < mDevices.size(); i++) {
1926 const Device* device = mDevices.valueAt(i);
1927 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001928 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001929 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001930 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001931 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001932 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001933 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001934 dump += StringPrintf(INDENT3 "Classes: 0x%08x\n", device->classes);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001935 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001936 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001937 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
1938 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001939 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001940 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001941 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08001942 "product=0x%04x, version=0x%04x\n",
1943 device->identifier.bus, device->identifier.vendor,
1944 device->identifier.product, device->identifier.version);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001945 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001946 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001947 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001948 device->keyMap.keyCharacterMapFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001949 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001950 device->configurationFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001951 dump += StringPrintf(INDENT3 "HaveKeyboardLayoutOverlay: %s\n",
Yi Kong9b14ac62018-07-17 13:48:38 -07001952 toString(device->overlayKeyMap != nullptr));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001953 dump += INDENT3 "VideoDevice: ";
1954 if (device->videoDevice) {
1955 dump += device->videoDevice->dump() + "\n";
1956 } else {
1957 dump += "<none>\n";
1958 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001959 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001960
1961 dump += INDENT "Unattached video devices:\n";
1962 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
1963 dump += INDENT2 + videoDevice->dump() + "\n";
1964 }
1965 if (mUnattachedVideoDevices.empty()) {
1966 dump += INDENT2 "<none>\n";
1967 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001968 } // release lock
1969}
1970
1971void EventHub::monitor() {
1972 // Acquire and release the lock to ensure that the event hub has not deadlocked.
1973 mLock.lock();
1974 mLock.unlock();
1975}
1976
1977
1978}; // namespace android