blob: efe3809f1d693666173564878730d7a5324aeb40 [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>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070028#include <sys/inotify.h>
29#include <sys/ioctl.h>
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070030#include <sys/limits.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070031#include <unistd.h>
32
Michael Wrightd02c5b62014-02-10 15:10:22 -080033#define LOG_TAG "EventHub"
34
35// #define LOG_NDEBUG 0
36
37#include "EventHub.h"
38
39#include <hardware_legacy/power.h>
40
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080041#include <android-base/stringprintf.h>
Philip Quinn39b81682019-01-09 22:20:39 -080042#include <cutils/properties.h>
Dan Albert677d87e2014-06-16 17:31:28 -070043#include <openssl/sha.h>
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070044#include <utils/Errors.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080045#include <utils/Log.h>
46#include <utils/Timers.h>
47#include <utils/threads.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080048
Michael Wrightd02c5b62014-02-10 15:10:22 -080049#include <input/KeyCharacterMap.h>
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070050#include <input/KeyLayoutMap.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080051#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 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -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 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -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
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070073static 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
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070076static 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
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080096/**
97 * Return true if name matches "v4l-touch*"
98 */
99static bool isV4lTouchNode(const char* name) {
100 return strstr(name, "v4l-touch") == name;
101}
102
Philip Quinn39b81682019-01-09 22:20:39 -0800103/**
104 * Returns true if V4L devices should be scanned.
105 *
106 * The system property ro.input.video_enabled can be used to control whether
107 * EventHub scans and opens V4L devices. As V4L does not support multiple
108 * clients, EventHub effectively blocks access to these devices when it opens
Siarhei Vishniakou29f88492019-04-05 14:11:43 -0700109 * them.
110 *
111 * Setting this to "false" would prevent any video devices from being discovered and
112 * associated with input devices.
113 *
114 * This property can be used as follows:
115 * 1. To turn off features that are dependent on video device presence.
116 * 2. During testing and development, to allow other clients to read video devices
117 * directly from /dev.
Philip Quinn39b81682019-01-09 22:20:39 -0800118 */
119static bool isV4lScanningEnabled() {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700120 return property_get_bool("ro.input.video_enabled", true /* default_value */);
Philip Quinn39b81682019-01-09 22:20:39 -0800121}
122
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800123static nsecs_t processEventTimestamp(const struct input_event& event) {
124 // Use the time specified in the event instead of the current time
125 // so that downstream code can get more accurate estimates of
126 // event dispatch latency from the time the event is enqueued onto
127 // the evdev client buffer.
128 //
129 // The event's timestamp fortuitously uses the same monotonic clock
130 // time base as the rest of Android. The kernel event device driver
131 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
132 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
133 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
134 // system call that also queries ktime_get_ts().
135
136 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.time.tv_sec) +
137 microseconds_to_nanoseconds(event.time.tv_usec);
138 return inputEventTime;
139}
140
Michael Wrightd02c5b62014-02-10 15:10:22 -0800141// --- Global Functions ---
142
143uint32_t getAbsAxisUsage(int32_t axis, uint32_t deviceClasses) {
144 // Touch devices get dibs on touch-related axes.
145 if (deviceClasses & INPUT_DEVICE_CLASS_TOUCH) {
146 switch (axis) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700147 case ABS_X:
148 case ABS_Y:
149 case ABS_PRESSURE:
150 case ABS_TOOL_WIDTH:
151 case ABS_DISTANCE:
152 case ABS_TILT_X:
153 case ABS_TILT_Y:
154 case ABS_MT_SLOT:
155 case ABS_MT_TOUCH_MAJOR:
156 case ABS_MT_TOUCH_MINOR:
157 case ABS_MT_WIDTH_MAJOR:
158 case ABS_MT_WIDTH_MINOR:
159 case ABS_MT_ORIENTATION:
160 case ABS_MT_POSITION_X:
161 case ABS_MT_POSITION_Y:
162 case ABS_MT_TOOL_TYPE:
163 case ABS_MT_BLOB_ID:
164 case ABS_MT_TRACKING_ID:
165 case ABS_MT_PRESSURE:
166 case ABS_MT_DISTANCE:
167 return INPUT_DEVICE_CLASS_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800168 }
169 }
170
Michael Wright842500e2015-03-13 17:32:02 -0700171 // External stylus gets the pressure axis
172 if (deviceClasses & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
173 if (axis == ABS_PRESSURE) {
174 return INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
175 }
176 }
177
Michael Wrightd02c5b62014-02-10 15:10:22 -0800178 // Joystick devices get the rest.
179 return deviceClasses & INPUT_DEVICE_CLASS_JOYSTICK;
180}
181
182// --- EventHub::Device ---
183
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100184EventHub::Device::Device(int fd, int32_t id, const std::string& path,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700185 const InputDeviceIdentifier& identifier)
186 : next(nullptr),
187 fd(fd),
188 id(id),
189 path(path),
190 identifier(identifier),
191 classes(0),
192 configuration(nullptr),
193 virtualKeyMap(nullptr),
194 ffEffectPlaying(false),
195 ffEffectId(-1),
196 controllerNumber(0),
197 enabled(true),
198 isVirtual(fd < 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800199 memset(keyBitmask, 0, sizeof(keyBitmask));
200 memset(absBitmask, 0, sizeof(absBitmask));
201 memset(relBitmask, 0, sizeof(relBitmask));
202 memset(swBitmask, 0, sizeof(swBitmask));
203 memset(ledBitmask, 0, sizeof(ledBitmask));
204 memset(ffBitmask, 0, sizeof(ffBitmask));
205 memset(propBitmask, 0, sizeof(propBitmask));
206}
207
208EventHub::Device::~Device() {
209 close();
210 delete configuration;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800211}
212
213void EventHub::Device::close() {
214 if (fd >= 0) {
215 ::close(fd);
216 fd = -1;
217 }
218}
219
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700220status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100221 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700222 if (fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100223 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700224 return -errno;
225 }
226 enabled = true;
227 return OK;
228}
229
230status_t EventHub::Device::disable() {
231 close();
232 enabled = false;
233 return OK;
234}
235
236bool EventHub::Device::hasValidFd() {
237 return !isVirtual && enabled;
238}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800239
240// --- EventHub ---
241
Michael Wrightd02c5b62014-02-10 15:10:22 -0800242const int EventHub::EPOLL_MAX_EVENTS;
243
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700244EventHub::EventHub(void)
245 : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
246 mNextDeviceId(1),
247 mControllerNumbers(),
248 mOpeningDevices(nullptr),
249 mClosingDevices(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800250 mNeedToSendFinishedDeviceScan(false),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700251 mNeedToReopenDevices(false),
252 mNeedToScanDevices(true),
253 mPendingEventCount(0),
254 mPendingEventIndex(0),
255 mPendingINotify(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800256 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
257
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800258 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800259 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800260
261 mINotifyFd = inotify_init();
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800262 mInputWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700263 LOG_ALWAYS_FATAL_IF(mInputWd < 0, "Could not register INotify for %s: %s", DEVICE_PATH,
264 strerror(errno));
Philip Quinn39b81682019-01-09 22:20:39 -0800265 if (isV4lScanningEnabled()) {
266 mVideoWd = inotify_add_watch(mINotifyFd, VIDEO_DEVICE_PATH, IN_DELETE | IN_CREATE);
267 LOG_ALWAYS_FATAL_IF(mVideoWd < 0, "Could not register INotify for %s: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700268 VIDEO_DEVICE_PATH, strerror(errno));
Philip Quinn39b81682019-01-09 22:20:39 -0800269 } else {
270 mVideoWd = -1;
271 ALOGI("Video device scanning disabled");
272 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800273
Siarhei Vishniakou2d0e9482019-09-24 12:52:47 +0100274 struct epoll_event eventItem = {};
275 eventItem.events = EPOLLIN | EPOLLWAKEUP;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700276 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800277 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800278 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
279
280 int wakeFds[2];
281 result = pipe(wakeFds);
282 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
283
284 mWakeReadPipeFd = wakeFds[0];
285 mWakeWritePipeFd = wakeFds[1];
286
287 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
288 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700289 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800290
291 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
292 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700293 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800294
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700295 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800296 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
297 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700298 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800299}
300
301EventHub::~EventHub(void) {
302 closeAllDevicesLocked();
303
304 while (mClosingDevices) {
305 Device* device = mClosingDevices;
306 mClosingDevices = device->next;
307 delete device;
308 }
309
310 ::close(mEpollFd);
311 ::close(mINotifyFd);
312 ::close(mWakeReadPipeFd);
313 ::close(mWakeWritePipeFd);
314
315 release_wake_lock(WAKE_LOCK_ID);
316}
317
318InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
319 AutoMutex _l(mLock);
320 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700321 if (device == nullptr) return InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800322 return device->identifier;
323}
324
325uint32_t EventHub::getDeviceClasses(int32_t deviceId) const {
326 AutoMutex _l(mLock);
327 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700328 if (device == nullptr) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800329 return device->classes;
330}
331
332int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
333 AutoMutex _l(mLock);
334 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700335 if (device == nullptr) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800336 return device->controllerNumber;
337}
338
339void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
340 AutoMutex _l(mLock);
341 Device* device = getDeviceLocked(deviceId);
342 if (device && device->configuration) {
343 *outConfiguration = *device->configuration;
344 } else {
345 outConfiguration->clear();
346 }
347}
348
349status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700350 RawAbsoluteAxisInfo* outAxisInfo) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800351 outAxisInfo->clear();
352
353 if (axis >= 0 && axis <= ABS_MAX) {
354 AutoMutex _l(mLock);
355
356 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700357 if (device && device->hasValidFd() && test_bit(axis, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800358 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700359 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
360 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
361 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800362 return -errno;
363 }
364
365 if (info.minimum != info.maximum) {
366 outAxisInfo->valid = true;
367 outAxisInfo->minValue = info.minimum;
368 outAxisInfo->maxValue = info.maximum;
369 outAxisInfo->flat = info.flat;
370 outAxisInfo->fuzz = info.fuzz;
371 outAxisInfo->resolution = info.resolution;
372 }
373 return OK;
374 }
375 }
376 return -1;
377}
378
379bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
380 if (axis >= 0 && axis <= REL_MAX) {
381 AutoMutex _l(mLock);
382
383 Device* device = getDeviceLocked(deviceId);
384 if (device) {
385 return test_bit(axis, device->relBitmask);
386 }
387 }
388 return false;
389}
390
391bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
392 if (property >= 0 && property <= INPUT_PROP_MAX) {
393 AutoMutex _l(mLock);
394
395 Device* device = getDeviceLocked(deviceId);
396 if (device) {
397 return test_bit(property, device->propBitmask);
398 }
399 }
400 return false;
401}
402
403int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
404 if (scanCode >= 0 && scanCode <= KEY_MAX) {
405 AutoMutex _l(mLock);
406
407 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700408 if (device && device->hasValidFd() && test_bit(scanCode, device->keyBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800409 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
410 memset(keyState, 0, sizeof(keyState));
411 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
412 return test_bit(scanCode, keyState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
413 }
414 }
415 }
416 return AKEY_STATE_UNKNOWN;
417}
418
419int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
420 AutoMutex _l(mLock);
421
422 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700423 if (device && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800424 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800425 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode, &scanCodes);
426 if (scanCodes.size() != 0) {
427 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
428 memset(keyState, 0, sizeof(keyState));
429 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
430 for (size_t i = 0; i < scanCodes.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800431 int32_t sc = scanCodes[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -0800432 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, keyState)) {
433 return AKEY_STATE_DOWN;
434 }
435 }
436 return AKEY_STATE_UP;
437 }
438 }
439 }
440 return AKEY_STATE_UNKNOWN;
441}
442
443int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
444 if (sw >= 0 && sw <= SW_MAX) {
445 AutoMutex _l(mLock);
446
447 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700448 if (device && device->hasValidFd() && test_bit(sw, device->swBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800449 uint8_t swState[sizeof_bit_array(SW_MAX + 1)];
450 memset(swState, 0, sizeof(swState));
451 if (ioctl(device->fd, EVIOCGSW(sizeof(swState)), swState) >= 0) {
452 return test_bit(sw, swState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
453 }
454 }
455 }
456 return AKEY_STATE_UNKNOWN;
457}
458
459status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
460 *outValue = 0;
461
462 if (axis >= 0 && axis <= ABS_MAX) {
463 AutoMutex _l(mLock);
464
465 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700466 if (device && device->hasValidFd() && test_bit(axis, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800467 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700468 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
469 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
470 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800471 return -errno;
472 }
473
474 *outValue = info.value;
475 return OK;
476 }
477 }
478 return -1;
479}
480
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700481bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes, const int32_t* keyCodes,
482 uint8_t* outFlags) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800483 AutoMutex _l(mLock);
484
485 Device* device = getDeviceLocked(deviceId);
486 if (device && device->keyMap.haveKeyLayout()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800487 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800488 for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) {
489 scanCodes.clear();
490
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700491 status_t err = device->keyMap.keyLayoutMap->findScanCodesForKey(keyCodes[codeIndex],
492 &scanCodes);
493 if (!err) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800494 // check the possible scan codes identified by the layout map against the
495 // map of codes actually emitted by the driver
496 for (size_t sc = 0; sc < scanCodes.size(); sc++) {
497 if (test_bit(scanCodes[sc], device->keyBitmask)) {
498 outFlags[codeIndex] = 1;
499 break;
500 }
501 }
502 }
503 }
504 return true;
505 }
506 return false;
507}
508
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700509status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
510 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800511 AutoMutex _l(mLock);
512 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700513 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800514
515 if (device) {
516 // Check the key character map first.
517 sp<KeyCharacterMap> kcm = device->getKeyCharacterMap();
Yi Kong9b14ac62018-07-17 13:48:38 -0700518 if (kcm != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800519 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
520 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700521 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800522 }
523 }
524
525 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700526 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800527 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700528 status = NO_ERROR;
529 }
530 }
531
532 if (status == NO_ERROR) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700533 if (kcm != nullptr) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700534 kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState);
535 } else {
536 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800537 }
538 }
539 }
540
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700541 if (status != NO_ERROR) {
542 *outKeycode = 0;
543 *outFlags = 0;
544 *outMetaState = metaState;
545 }
546
547 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800548}
549
550status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
551 AutoMutex _l(mLock);
552 Device* device = getDeviceLocked(deviceId);
553
554 if (device && device->keyMap.haveKeyLayout()) {
555 status_t err = device->keyMap.keyLayoutMap->mapAxis(scanCode, outAxisInfo);
556 if (err == NO_ERROR) {
557 return NO_ERROR;
558 }
559 }
560
561 return NAME_NOT_FOUND;
562}
563
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100564void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800565 AutoMutex _l(mLock);
566
567 mExcludedDevices = devices;
568}
569
570bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
571 AutoMutex _l(mLock);
572 Device* device = getDeviceLocked(deviceId);
573 if (device && scanCode >= 0 && scanCode <= KEY_MAX) {
574 if (test_bit(scanCode, device->keyBitmask)) {
575 return true;
576 }
577 }
578 return false;
579}
580
581bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
582 AutoMutex _l(mLock);
583 Device* device = getDeviceLocked(deviceId);
584 int32_t sc;
585 if (device && mapLed(device, led, &sc) == NO_ERROR) {
586 if (test_bit(sc, device->ledBitmask)) {
587 return true;
588 }
589 }
590 return false;
591}
592
593void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
594 AutoMutex _l(mLock);
595 Device* device = getDeviceLocked(deviceId);
596 setLedStateLocked(device, led, on);
597}
598
599void EventHub::setLedStateLocked(Device* device, int32_t led, bool on) {
600 int32_t sc;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700601 if (device && device->hasValidFd() && mapLed(device, led, &sc) != NAME_NOT_FOUND) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800602 struct input_event ev;
603 ev.time.tv_sec = 0;
604 ev.time.tv_usec = 0;
605 ev.type = EV_LED;
606 ev.code = sc;
607 ev.value = on ? 1 : 0;
608
609 ssize_t nWrite;
610 do {
611 nWrite = write(device->fd, &ev, sizeof(struct input_event));
612 } while (nWrite == -1 && errno == EINTR);
613 }
614}
615
616void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700617 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800618 outVirtualKeys.clear();
619
620 AutoMutex _l(mLock);
621 Device* device = getDeviceLocked(deviceId);
622 if (device && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800623 const std::vector<VirtualKeyDefinition> virtualKeys =
624 device->virtualKeyMap->getVirtualKeys();
625 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800626 }
627}
628
629sp<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
630 AutoMutex _l(mLock);
631 Device* device = getDeviceLocked(deviceId);
632 if (device) {
633 return device->getKeyCharacterMap();
634 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700635 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800636}
637
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700638bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, const sp<KeyCharacterMap>& map) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800639 AutoMutex _l(mLock);
640 Device* device = getDeviceLocked(deviceId);
641 if (device) {
642 if (map != device->overlayKeyMap) {
643 device->overlayKeyMap = map;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700644 device->combinedKeyMap = KeyCharacterMap::combine(device->keyMap.keyCharacterMap, map);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800645 return true;
646 }
647 }
648 return false;
649}
650
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100651static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
652 std::string rawDescriptor;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700653 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800654 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100655 if (!identifier.uniqueId.empty()) {
656 rawDescriptor += "uniqueId:";
657 rawDescriptor += identifier.uniqueId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800658 } else if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100659 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800660 }
661
662 if (identifier.vendor == 0 && identifier.product == 0) {
663 // If we don't know the vendor and product id, then the device is probably
664 // built-in so we need to rely on other information to uniquely identify
665 // the input device. Usually we try to avoid relying on the device name or
666 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100667 if (!identifier.name.empty()) {
668 rawDescriptor += "name:";
669 rawDescriptor += identifier.name;
670 } else if (!identifier.location.empty()) {
671 rawDescriptor += "location:";
672 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800673 }
674 }
675 identifier.descriptor = sha1(rawDescriptor);
676 return rawDescriptor;
677}
678
679void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
680 // Compute a device descriptor that uniquely identifies the device.
681 // The descriptor is assumed to be a stable identifier. Its value should not
682 // change between reboots, reconnections, firmware updates or new releases
683 // of Android. In practice we sometimes get devices that cannot be uniquely
684 // identified. In this case we enforce uniqueness between connected devices.
685 // Ideally, we also want the descriptor to be short and relatively opaque.
686
687 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100688 std::string rawDescriptor = generateDescriptor(identifier);
689 if (identifier.uniqueId.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800690 // If it didn't have a unique id check for conflicts and enforce
691 // uniqueness if necessary.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700692 while (getDeviceByDescriptorLocked(identifier.descriptor) != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800693 identifier.nonce++;
694 rawDescriptor = generateDescriptor(identifier);
695 }
696 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100697 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700698 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800699}
700
701void EventHub::vibrate(int32_t deviceId, nsecs_t duration) {
702 AutoMutex _l(mLock);
703 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700704 if (device && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800705 ff_effect effect;
706 memset(&effect, 0, sizeof(effect));
707 effect.type = FF_RUMBLE;
708 effect.id = device->ffEffectId;
709 effect.u.rumble.strong_magnitude = 0xc000;
710 effect.u.rumble.weak_magnitude = 0xc000;
711 effect.replay.length = (duration + 999999LL) / 1000000LL;
712 effect.replay.delay = 0;
713 if (ioctl(device->fd, EVIOCSFF, &effect)) {
714 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700715 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800716 return;
717 }
718 device->ffEffectId = effect.id;
719
720 struct input_event ev;
721 ev.time.tv_sec = 0;
722 ev.time.tv_usec = 0;
723 ev.type = EV_FF;
724 ev.code = device->ffEffectId;
725 ev.value = 1;
726 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
727 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700728 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800729 return;
730 }
731 device->ffEffectPlaying = true;
732 }
733}
734
735void EventHub::cancelVibrate(int32_t deviceId) {
736 AutoMutex _l(mLock);
737 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700738 if (device && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800739 if (device->ffEffectPlaying) {
740 device->ffEffectPlaying = false;
741
742 struct input_event ev;
743 ev.time.tv_sec = 0;
744 ev.time.tv_usec = 0;
745 ev.type = EV_FF;
746 ev.code = device->ffEffectId;
747 ev.value = 0;
748 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
749 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700750 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800751 return;
752 }
753 }
754 }
755}
756
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100757EventHub::Device* EventHub::getDeviceByDescriptorLocked(const std::string& descriptor) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800758 size_t size = mDevices.size();
759 for (size_t i = 0; i < size; i++) {
760 Device* device = mDevices.valueAt(i);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100761 if (descriptor == device->identifier.descriptor) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800762 return device;
763 }
764 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700765 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800766}
767
768EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -0800769 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800770 deviceId = mBuiltInKeyboardId;
771 }
772 ssize_t index = mDevices.indexOfKey(deviceId);
773 return index >= 0 ? mDevices.valueAt(index) : NULL;
774}
775
776EventHub::Device* EventHub::getDeviceByPathLocked(const char* devicePath) const {
777 for (size_t i = 0; i < mDevices.size(); i++) {
778 Device* device = mDevices.valueAt(i);
779 if (device->path == devicePath) {
780 return device;
781 }
782 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700783 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800784}
785
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700786/**
787 * The file descriptor could be either input device, or a video device (associated with a
788 * specific input device). Check both cases here, and return the device that this event
789 * belongs to. Caller can compare the fd's once more to determine event type.
790 * Looks through all input devices, and only attached video devices. Unattached video
791 * devices are ignored.
792 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700793EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
794 for (size_t i = 0; i < mDevices.size(); i++) {
795 Device* device = mDevices.valueAt(i);
796 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700797 // This is an input device event
798 return device;
799 }
800 if (device->videoDevice && device->videoDevice->getFd() == fd) {
801 // This is a video device event
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700802 return device;
803 }
804 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700805 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
806 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700807 return nullptr;
808}
809
Michael Wrightd02c5b62014-02-10 15:10:22 -0800810size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
811 ALOG_ASSERT(bufferSize >= 1);
812
813 AutoMutex _l(mLock);
814
815 struct input_event readBuffer[bufferSize];
816
817 RawEvent* event = buffer;
818 size_t capacity = bufferSize;
819 bool awoken = false;
820 for (;;) {
821 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
822
823 // Reopen input devices if needed.
824 if (mNeedToReopenDevices) {
825 mNeedToReopenDevices = false;
826
827 ALOGI("Reopening all input devices due to a configuration change.");
828
829 closeAllDevicesLocked();
830 mNeedToScanDevices = true;
831 break; // return to the caller before we actually rescan
832 }
833
834 // Report any devices that had last been added/removed.
835 while (mClosingDevices) {
836 Device* device = mClosingDevices;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700837 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800838 mClosingDevices = device->next;
839 event->when = now;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700840 event->deviceId = (device->id == mBuiltInKeyboardId)
841 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
842 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800843 event->type = DEVICE_REMOVED;
844 event += 1;
845 delete device;
846 mNeedToSendFinishedDeviceScan = true;
847 if (--capacity == 0) {
848 break;
849 }
850 }
851
852 if (mNeedToScanDevices) {
853 mNeedToScanDevices = false;
854 scanDevicesLocked();
855 mNeedToSendFinishedDeviceScan = true;
856 }
857
Yi Kong9b14ac62018-07-17 13:48:38 -0700858 while (mOpeningDevices != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800859 Device* device = mOpeningDevices;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700860 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800861 mOpeningDevices = device->next;
862 event->when = now;
863 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
864 event->type = DEVICE_ADDED;
865 event += 1;
866 mNeedToSendFinishedDeviceScan = true;
867 if (--capacity == 0) {
868 break;
869 }
870 }
871
872 if (mNeedToSendFinishedDeviceScan) {
873 mNeedToSendFinishedDeviceScan = false;
874 event->when = now;
875 event->type = FINISHED_DEVICE_SCAN;
876 event += 1;
877 if (--capacity == 0) {
878 break;
879 }
880 }
881
882 // Grab the next input event.
883 bool deviceChanged = false;
884 while (mPendingEventIndex < mPendingEventCount) {
885 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700886 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800887 if (eventItem.events & EPOLLIN) {
888 mPendingINotify = true;
889 } else {
890 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
891 }
892 continue;
893 }
894
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700895 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800896 if (eventItem.events & EPOLLIN) {
897 ALOGV("awoken after wake()");
898 awoken = true;
899 char buffer[16];
900 ssize_t nRead;
901 do {
902 nRead = read(mWakeReadPipeFd, buffer, sizeof(buffer));
903 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(buffer));
904 } else {
905 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700906 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800907 }
908 continue;
909 }
910
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700911 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700912 if (!device) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700913 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
914 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700915 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800916 continue;
917 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700918 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
919 if (eventItem.events & EPOLLIN) {
920 size_t numFrames = device->videoDevice->readAndQueueFrames();
921 if (numFrames == 0) {
922 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700923 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700924 }
925 } else if (eventItem.events & EPOLLHUP) {
926 // TODO(b/121395353) - consider adding EPOLLRDHUP
927 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700928 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700929 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
930 device->videoDevice = nullptr;
931 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700932 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
933 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700934 ALOG_ASSERT(!DEBUG);
935 }
936 continue;
937 }
938 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -0800939 if (eventItem.events & EPOLLIN) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700940 int32_t readSize =
941 read(device->fd, readBuffer, sizeof(struct input_event) * capacity);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800942 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
943 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -0700944 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700945 " bufferSize: %zu capacity: %zu errno: %d)\n",
946 device->fd, readSize, bufferSize, capacity, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800947 deviceChanged = true;
948 closeDeviceLocked(device);
949 } else if (readSize < 0) {
950 if (errno != EAGAIN && errno != EINTR) {
951 ALOGW("could not get event (errno=%d)", errno);
952 }
953 } else if ((readSize % sizeof(struct input_event)) != 0) {
954 ALOGE("could not get event (wrong size: %d)", readSize);
955 } else {
956 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
957
958 size_t count = size_t(readSize) / sizeof(struct input_event);
959 for (size_t i = 0; i < count; i++) {
960 struct input_event& iev = readBuffer[i];
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800961 event->when = processEventTimestamp(iev);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800962 event->deviceId = deviceId;
963 event->type = iev.type;
964 event->code = iev.code;
965 event->value = iev.value;
966 event += 1;
967 capacity -= 1;
968 }
969 if (capacity == 0) {
970 // The result buffer is full. Reset the pending event index
971 // so we will try to read the device again on the next iteration.
972 mPendingEventIndex -= 1;
973 break;
974 }
975 }
976 } else if (eventItem.events & EPOLLHUP) {
977 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700978 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800979 deviceChanged = true;
980 closeDeviceLocked(device);
981 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700982 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
983 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800984 }
985 }
986
987 // readNotify() will modify the list of devices so this must be done after
988 // processing all other events to ensure that we read all remaining events
989 // before closing the devices.
990 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
991 mPendingINotify = false;
992 readNotifyLocked();
993 deviceChanged = true;
994 }
995
996 // Report added or removed devices immediately.
997 if (deviceChanged) {
998 continue;
999 }
1000
1001 // Return now if we have collected any events or if we were explicitly awoken.
1002 if (event != buffer || awoken) {
1003 break;
1004 }
1005
1006 // Poll for events. Mind the wake lock dance!
1007 // We hold a wake lock at all times except during epoll_wait(). This works due to some
1008 // subtle choreography. When a device driver has pending (unread) events, it acquires
1009 // a kernel wake lock. However, once the last pending event has been read, the device
1010 // driver will release the kernel wake lock. To prevent the system from going to sleep
1011 // when this happens, the EventHub holds onto its own user wake lock while the client
1012 // is processing events. Thus the system can only sleep if there are no events
1013 // pending or currently being processed.
1014 //
1015 // The timeout is advisory only. If the device is asleep, it will not wake just to
1016 // service the timeout.
1017 mPendingEventIndex = 0;
1018
1019 mLock.unlock(); // release lock before poll, must be before release_wake_lock
1020 release_wake_lock(WAKE_LOCK_ID);
1021
1022 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1023
1024 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
1025 mLock.lock(); // reacquire lock after poll, must be after acquire_wake_lock
1026
1027 if (pollResult == 0) {
1028 // Timed out.
1029 mPendingEventCount = 0;
1030 break;
1031 }
1032
1033 if (pollResult < 0) {
1034 // An error occurred.
1035 mPendingEventCount = 0;
1036
1037 // Sleep after errors to avoid locking up the system.
1038 // Hopefully the error is transient.
1039 if (errno != EINTR) {
1040 ALOGW("poll failed (errno=%d)\n", errno);
1041 usleep(100000);
1042 }
1043 } else {
1044 // Some events occurred.
1045 mPendingEventCount = size_t(pollResult);
1046 }
1047 }
1048
1049 // All done, return the number of events we read.
1050 return event - buffer;
1051}
1052
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001053std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
1054 AutoMutex _l(mLock);
1055
1056 Device* device = getDeviceLocked(deviceId);
1057 if (!device || !device->videoDevice) {
1058 return {};
1059 }
1060 return device->videoDevice->consumeFrames();
1061}
1062
Michael Wrightd02c5b62014-02-10 15:10:22 -08001063void EventHub::wake() {
1064 ALOGV("wake() called");
1065
1066 ssize_t nWrite;
1067 do {
1068 nWrite = write(mWakeWritePipeFd, "W", 1);
1069 } while (nWrite == -1 && errno == EINTR);
1070
1071 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001072 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001073 }
1074}
1075
1076void EventHub::scanDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001077 status_t result = scanDirLocked(DEVICE_PATH);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001078 if (result < 0) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001079 ALOGE("scan dir failed for %s", DEVICE_PATH);
1080 }
Philip Quinn39b81682019-01-09 22:20:39 -08001081 if (isV4lScanningEnabled()) {
1082 result = scanVideoDirLocked(VIDEO_DEVICE_PATH);
1083 if (result != OK) {
1084 ALOGE("scan video dir failed for %s", VIDEO_DEVICE_PATH);
1085 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001086 }
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001087 if (mDevices.indexOfKey(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) < 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001088 createVirtualKeyboardLocked();
1089 }
1090}
1091
1092// ----------------------------------------------------------------------------
1093
1094static bool containsNonZeroByte(const uint8_t* array, uint32_t startIndex, uint32_t endIndex) {
1095 const uint8_t* end = array + endIndex;
1096 array += startIndex;
1097 while (array != end) {
1098 if (*(array++) != 0) {
1099 return true;
1100 }
1101 }
1102 return false;
1103}
1104
1105static const int32_t GAMEPAD_KEYCODES[] = {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001106 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C, //
1107 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z, //
1108 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1, //
1109 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2, //
1110 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR, //
1111 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE, //
Michael Wrightd02c5b62014-02-10 15:10:22 -08001112};
1113
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001114status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001115 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001116 struct epoll_event eventItem = {};
1117 eventItem.events = EPOLLIN | EPOLLWAKEUP;
1118 eventItem.data.fd = fd;
1119 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1120 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001121 return -errno;
1122 }
1123 return OK;
1124}
1125
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001126status_t EventHub::unregisterFdFromEpoll(int fd) {
1127 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
1128 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
1129 return -errno;
1130 }
1131 return OK;
1132}
1133
1134status_t EventHub::registerDeviceForEpollLocked(Device* device) {
1135 if (device == nullptr) {
1136 if (DEBUG) {
1137 LOG_ALWAYS_FATAL("Cannot call registerDeviceForEpollLocked with null Device");
1138 }
1139 return BAD_VALUE;
1140 }
1141 status_t result = registerFdForEpoll(device->fd);
1142 if (result != OK) {
1143 ALOGE("Could not add input device fd to epoll for device %" PRId32, device->id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001144 return result;
1145 }
1146 if (device->videoDevice) {
1147 registerVideoDeviceForEpollLocked(*device->videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001148 }
1149 return result;
1150}
1151
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001152void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
1153 status_t result = registerFdForEpoll(videoDevice.getFd());
1154 if (result != OK) {
1155 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
1156 }
1157}
1158
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001159status_t EventHub::unregisterDeviceFromEpollLocked(Device* device) {
1160 if (device->hasValidFd()) {
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001161 status_t result = unregisterFdFromEpoll(device->fd);
1162 if (result != OK) {
1163 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device->id);
1164 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001165 }
1166 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001167 if (device->videoDevice) {
1168 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1169 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001170 return OK;
1171}
1172
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001173void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
1174 if (videoDevice.hasValidFd()) {
1175 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
1176 if (result != OK) {
1177 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001178 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001179 }
1180 }
1181}
1182
1183status_t EventHub::openDeviceLocked(const char* devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001184 char buffer[80];
1185
1186 ALOGV("Opening device: %s", devicePath);
1187
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001188 int fd = open(devicePath, O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001189 if (fd < 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001190 ALOGE("could not open %s, %s\n", devicePath, strerror(errno));
1191 return -1;
1192 }
1193
1194 InputDeviceIdentifier identifier;
1195
1196 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001197 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001198 ALOGE("Could not get device name for %s: %s", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001199 } else {
1200 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001201 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001202 }
1203
1204 // Check to see if the device is on our excluded list
1205 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001206 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001207 if (identifier.name == item) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001208 ALOGI("ignoring event id %s driver %s\n", devicePath, item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001209 close(fd);
1210 return -1;
1211 }
1212 }
1213
1214 // Get device driver version.
1215 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001216 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001217 ALOGE("could not get driver version for %s, %s\n", devicePath, strerror(errno));
1218 close(fd);
1219 return -1;
1220 }
1221
1222 // Get device identifier.
1223 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001224 if (ioctl(fd, EVIOCGID, &inputId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001225 ALOGE("could not get device input id for %s, %s\n", devicePath, strerror(errno));
1226 close(fd);
1227 return -1;
1228 }
1229 identifier.bus = inputId.bustype;
1230 identifier.product = inputId.product;
1231 identifier.vendor = inputId.vendor;
1232 identifier.version = inputId.version;
1233
1234 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001235 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
1236 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237 } else {
1238 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001239 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001240 }
1241
1242 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001243 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
1244 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001245 } else {
1246 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001247 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001248 }
1249
1250 // Fill in the descriptor.
1251 assignDescriptorLocked(identifier);
1252
Michael Wrightd02c5b62014-02-10 15:10:22 -08001253 // Allocate device. (The device object takes ownership of the fd at this point.)
1254 int32_t deviceId = mNextDeviceId++;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001255 Device* device = new Device(fd, deviceId, devicePath, identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001256
1257 ALOGV("add device %d: %s\n", deviceId, devicePath);
1258 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001259 " vendor %04x\n"
1260 " product %04x\n"
1261 " version %04x\n",
1262 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001263 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
1264 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
1265 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
1266 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001267 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
1268 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001269
1270 // Load the configuration file for the device.
1271 loadConfigurationLocked(device);
1272
1273 // Figure out the kinds of events the device reports.
1274 ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(device->keyBitmask)), device->keyBitmask);
1275 ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(device->absBitmask)), device->absBitmask);
1276 ioctl(fd, EVIOCGBIT(EV_REL, sizeof(device->relBitmask)), device->relBitmask);
1277 ioctl(fd, EVIOCGBIT(EV_SW, sizeof(device->swBitmask)), device->swBitmask);
1278 ioctl(fd, EVIOCGBIT(EV_LED, sizeof(device->ledBitmask)), device->ledBitmask);
1279 ioctl(fd, EVIOCGBIT(EV_FF, sizeof(device->ffBitmask)), device->ffBitmask);
1280 ioctl(fd, EVIOCGPROP(sizeof(device->propBitmask)), device->propBitmask);
1281
1282 // See if this is a keyboard. Ignore everything in the button range except for
1283 // joystick and gamepad buttons which are handled like keyboards for the most part.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001284 bool haveKeyboardKeys =
1285 containsNonZeroByte(device->keyBitmask, 0, sizeof_bit_array(BTN_MISC)) ||
1286 containsNonZeroByte(device->keyBitmask, sizeof_bit_array(KEY_OK),
1287 sizeof_bit_array(KEY_MAX + 1));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001288 bool haveGamepadButtons = containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_MISC),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001289 sizeof_bit_array(BTN_MOUSE)) ||
1290 containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_JOYSTICK),
1291 sizeof_bit_array(BTN_DIGI));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001292 if (haveKeyboardKeys || haveGamepadButtons) {
1293 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1294 }
1295
1296 // See if this is a cursor device such as a trackball or mouse.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001297 if (test_bit(BTN_MOUSE, device->keyBitmask) && test_bit(REL_X, device->relBitmask) &&
1298 test_bit(REL_Y, device->relBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001299 device->classes |= INPUT_DEVICE_CLASS_CURSOR;
1300 }
1301
Prashant Malani1941ff52015-08-11 18:29:28 -07001302 // See if this is a rotary encoder type device.
1303 String8 deviceType = String8();
1304 if (device->configuration &&
1305 device->configuration->tryGetProperty(String8("device.type"), deviceType)) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001306 if (!deviceType.compare(String8("rotaryEncoder"))) {
1307 device->classes |= INPUT_DEVICE_CLASS_ROTARY_ENCODER;
1308 }
Prashant Malani1941ff52015-08-11 18:29:28 -07001309 }
1310
Michael Wrightd02c5b62014-02-10 15:10:22 -08001311 // See if this is a touch pad.
1312 // Is this a new modern multi-touch driver?
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001313 if (test_bit(ABS_MT_POSITION_X, device->absBitmask) &&
1314 test_bit(ABS_MT_POSITION_Y, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001315 // Some joysticks such as the PS3 controller report axes that conflict
1316 // with the ABS_MT range. Try to confirm that the device really is
1317 // a touch screen.
1318 if (test_bit(BTN_TOUCH, device->keyBitmask) || !haveGamepadButtons) {
1319 device->classes |= INPUT_DEVICE_CLASS_TOUCH | INPUT_DEVICE_CLASS_TOUCH_MT;
1320 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001321 // Is this an old style single-touch driver?
1322 } else if (test_bit(BTN_TOUCH, device->keyBitmask) && test_bit(ABS_X, device->absBitmask) &&
1323 test_bit(ABS_Y, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001324 device->classes |= INPUT_DEVICE_CLASS_TOUCH;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001325 // Is this a BT stylus?
Michael Wright842500e2015-03-13 17:32:02 -07001326 } else if ((test_bit(ABS_PRESSURE, device->absBitmask) ||
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001327 test_bit(BTN_TOUCH, device->keyBitmask)) &&
1328 !test_bit(ABS_X, device->absBitmask) && !test_bit(ABS_Y, device->absBitmask)) {
Michael Wright842500e2015-03-13 17:32:02 -07001329 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
1330 // Keyboard will try to claim some of the buttons but we really want to reserve those so we
1331 // can fuse it with the touch screen data, so just take them back. Note this means an
1332 // external stylus cannot also be a keyboard device.
1333 device->classes &= ~INPUT_DEVICE_CLASS_KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001334 }
1335
1336 // See if this device is a joystick.
1337 // Assumes that joysticks always have gamepad buttons in order to distinguish them
1338 // from other devices such as accelerometers that also have absolute axes.
1339 if (haveGamepadButtons) {
1340 uint32_t assumedClasses = device->classes | INPUT_DEVICE_CLASS_JOYSTICK;
1341 for (int i = 0; i <= ABS_MAX; i++) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001342 if (test_bit(i, device->absBitmask) &&
1343 (getAbsAxisUsage(i, assumedClasses) & INPUT_DEVICE_CLASS_JOYSTICK)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001344 device->classes = assumedClasses;
1345 break;
1346 }
1347 }
1348 }
1349
1350 // Check whether this device has switches.
1351 for (int i = 0; i <= SW_MAX; i++) {
1352 if (test_bit(i, device->swBitmask)) {
1353 device->classes |= INPUT_DEVICE_CLASS_SWITCH;
1354 break;
1355 }
1356 }
1357
1358 // Check whether this device supports the vibrator.
1359 if (test_bit(FF_RUMBLE, device->ffBitmask)) {
1360 device->classes |= INPUT_DEVICE_CLASS_VIBRATOR;
1361 }
1362
1363 // Configure virtual keys.
1364 if ((device->classes & INPUT_DEVICE_CLASS_TOUCH)) {
1365 // Load the virtual keys for the touch screen, if any.
1366 // We do this now so that we can make sure to load the keymap if necessary.
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001367 bool success = loadVirtualKeyMapLocked(device);
1368 if (success) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001369 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1370 }
1371 }
1372
1373 // Load the key map.
1374 // We need to do this for joysticks too because the key layout may specify axes.
1375 status_t keyMapStatus = NAME_NOT_FOUND;
1376 if (device->classes & (INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_JOYSTICK)) {
1377 // Load the keymap for the device.
1378 keyMapStatus = loadKeyMapLocked(device);
1379 }
1380
1381 // Configure the keyboard, gamepad or virtual keyboard.
1382 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1383 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001384 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
1385 isEligibleBuiltInKeyboard(device->identifier, device->configuration, &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001386 mBuiltInKeyboardId = device->id;
1387 }
1388
1389 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
1390 if (hasKeycodeLocked(device, AKEYCODE_Q)) {
1391 device->classes |= INPUT_DEVICE_CLASS_ALPHAKEY;
1392 }
1393
1394 // See if this device has a DPAD.
1395 if (hasKeycodeLocked(device, AKEYCODE_DPAD_UP) &&
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001396 hasKeycodeLocked(device, AKEYCODE_DPAD_DOWN) &&
1397 hasKeycodeLocked(device, AKEYCODE_DPAD_LEFT) &&
1398 hasKeycodeLocked(device, AKEYCODE_DPAD_RIGHT) &&
1399 hasKeycodeLocked(device, AKEYCODE_DPAD_CENTER)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001400 device->classes |= INPUT_DEVICE_CLASS_DPAD;
1401 }
1402
1403 // See if this device has a gamepad.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001404 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES) / sizeof(GAMEPAD_KEYCODES[0]); i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001405 if (hasKeycodeLocked(device, GAMEPAD_KEYCODES[i])) {
1406 device->classes |= INPUT_DEVICE_CLASS_GAMEPAD;
1407 break;
1408 }
1409 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001410 }
1411
1412 // If the device isn't recognized as something we handle, don't monitor it.
1413 if (device->classes == 0) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001414 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath,
1415 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001416 delete device;
1417 return -1;
1418 }
1419
Tim Kilbourn063ff532015-04-08 10:26:18 -07001420 // Determine whether the device has a mic.
1421 if (deviceHasMicLocked(device)) {
1422 device->classes |= INPUT_DEVICE_CLASS_MIC;
1423 }
1424
Michael Wrightd02c5b62014-02-10 15:10:22 -08001425 // Determine whether the device is external or internal.
1426 if (isExternalDeviceLocked(device)) {
1427 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL;
1428 }
1429
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001430 if (device->classes & (INPUT_DEVICE_CLASS_JOYSTICK | INPUT_DEVICE_CLASS_DPAD) &&
1431 device->classes & INPUT_DEVICE_CLASS_GAMEPAD) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001432 device->controllerNumber = getNextControllerNumberLocked(device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001433 setLedForControllerLocked(device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001434 }
1435
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001436 // Find a matching video device by comparing device names
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001437 // This should be done before registerDeviceForEpollLocked, so that both fds are added to epoll
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001438 for (std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
1439 if (device->identifier.name == videoDevice->getName()) {
1440 device->videoDevice = std::move(videoDevice);
1441 break;
1442 }
1443 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001444 mUnattachedVideoDevices
1445 .erase(std::remove_if(mUnattachedVideoDevices.begin(), mUnattachedVideoDevices.end(),
1446 [](const std::unique_ptr<TouchVideoDevice>& videoDevice) {
1447 return videoDevice == nullptr;
1448 }),
1449 mUnattachedVideoDevices.end());
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001450
1451 if (registerDeviceForEpollLocked(device) != OK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001452 delete device;
1453 return -1;
1454 }
1455
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001456 configureFd(device);
1457
1458 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=0x%x, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001459 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
1460 deviceId, fd, devicePath, device->identifier.name.c_str(), device->classes,
1461 device->configurationFile.c_str(), device->keyMap.keyLayoutFile.c_str(),
1462 device->keyMap.keyCharacterMapFile.c_str(), toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001463
1464 addDeviceLocked(device);
1465 return OK;
1466}
1467
1468void EventHub::configureFd(Device* device) {
1469 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
1470 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1471 // Disable kernel key repeat since we handle it ourselves
1472 unsigned int repeatRate[] = {0, 0};
1473 if (ioctl(device->fd, EVIOCSREP, repeatRate)) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001474 ALOGW("Unable to disable kernel key repeat for %s: %s", device->path.c_str(),
1475 strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001476 }
1477 }
1478
Michael Wrightd02c5b62014-02-10 15:10:22 -08001479 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
1480 // associated with input events. This is important because the input system
1481 // uses the timestamps extensively and assumes they were recorded using the monotonic
1482 // clock.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001483 int clockId = CLOCK_MONOTONIC;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001484 bool usingClockIoctl = !ioctl(device->fd, EVIOCSCLOCKID, &clockId);
Atif Niyaz4180aa42019-05-10 16:27:48 -07001485 ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001486}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001487
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001488void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
1489 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
1490 if (!videoDevice) {
1491 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
1492 return;
1493 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001494 // Transfer ownership of this video device to a matching input device
1495 for (size_t i = 0; i < mDevices.size(); i++) {
1496 Device* device = mDevices.valueAt(i);
1497 if (videoDevice->getName() == device->identifier.name) {
1498 device->videoDevice = std::move(videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001499 if (device->enabled) {
1500 registerVideoDeviceForEpollLocked(*device->videoDevice);
1501 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001502 return;
1503 }
1504 }
1505
1506 // Couldn't find a matching input device, so just add it to a temporary holding queue.
1507 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001508 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001509 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001510 mUnattachedVideoDevices.push_back(std::move(videoDevice));
1511}
1512
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001513bool EventHub::isDeviceEnabled(int32_t deviceId) {
1514 AutoMutex _l(mLock);
1515 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001516 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001517 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1518 return false;
1519 }
1520 return device->enabled;
1521}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001522
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001523status_t EventHub::enableDevice(int32_t deviceId) {
1524 AutoMutex _l(mLock);
1525 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001526 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001527 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1528 return BAD_VALUE;
1529 }
1530 if (device->enabled) {
1531 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
1532 return OK;
1533 }
1534 status_t result = device->enable();
1535 if (result != OK) {
1536 ALOGE("Failed to enable device %" PRId32, deviceId);
1537 return result;
1538 }
1539
1540 configureFd(device);
1541
1542 return registerDeviceForEpollLocked(device);
1543}
1544
1545status_t EventHub::disableDevice(int32_t deviceId) {
1546 AutoMutex _l(mLock);
1547 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001548 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001549 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1550 return BAD_VALUE;
1551 }
1552 if (!device->enabled) {
1553 ALOGW("Duplicate call to %s, input device already disabled", __func__);
1554 return OK;
1555 }
1556 unregisterDeviceFromEpollLocked(device);
1557 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001558}
1559
1560void EventHub::createVirtualKeyboardLocked() {
1561 InputDeviceIdentifier identifier;
1562 identifier.name = "Virtual";
1563 identifier.uniqueId = "<virtual>";
1564 assignDescriptorLocked(identifier);
1565
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001566 Device* device =
1567 new Device(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>", identifier);
1568 device->classes = INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_ALPHAKEY |
1569 INPUT_DEVICE_CLASS_DPAD | INPUT_DEVICE_CLASS_VIRTUAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001570 loadKeyMapLocked(device);
1571 addDeviceLocked(device);
1572}
1573
1574void EventHub::addDeviceLocked(Device* device) {
1575 mDevices.add(device->id, device);
1576 device->next = mOpeningDevices;
1577 mOpeningDevices = device;
1578}
1579
1580void EventHub::loadConfigurationLocked(Device* device) {
1581 device->configurationFile = getInputDeviceConfigurationFilePathByDeviceIdentifier(
1582 device->identifier, INPUT_DEVICE_CONFIGURATION_FILE_TYPE_CONFIGURATION);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001583 if (device->configurationFile.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001584 ALOGD("No input device configuration file found for device '%s'.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001585 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001586 } else {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001587 status_t status = PropertyMap::load(String8(device->configurationFile.c_str()),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001588 &device->configuration);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001589 if (status) {
1590 ALOGE("Error loading input device configuration file for device '%s'. "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001591 "Using default configuration.",
1592 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001593 }
1594 }
1595}
1596
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001597bool EventHub::loadVirtualKeyMapLocked(Device* device) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001598 // The virtual key map is supplied by the kernel as a system board property file.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001599 std::string path;
1600 path += "/sys/board_properties/virtualkeys.";
Siarhei Vishniakoub45635c2019-02-20 19:22:09 -06001601 path += device->identifier.getCanonicalName();
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001602 if (access(path.c_str(), R_OK)) {
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001603 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001604 }
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001605 device->virtualKeyMap = VirtualKeyMap::load(path);
1606 return device->virtualKeyMap != nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001607}
1608
1609status_t EventHub::loadKeyMapLocked(Device* device) {
1610 return device->keyMap.load(device->identifier, device->configuration);
1611}
1612
1613bool EventHub::isExternalDeviceLocked(Device* device) {
1614 if (device->configuration) {
1615 bool value;
1616 if (device->configuration->tryGetProperty(String8("device.internal"), value)) {
1617 return !value;
1618 }
1619 }
1620 return device->identifier.bus == BUS_USB || device->identifier.bus == BUS_BLUETOOTH;
1621}
1622
Tim Kilbourn063ff532015-04-08 10:26:18 -07001623bool EventHub::deviceHasMicLocked(Device* device) {
1624 if (device->configuration) {
1625 bool value;
1626 if (device->configuration->tryGetProperty(String8("audio.mic"), value)) {
1627 return value;
1628 }
1629 }
1630 return false;
1631}
1632
Michael Wrightd02c5b62014-02-10 15:10:22 -08001633int32_t EventHub::getNextControllerNumberLocked(Device* device) {
1634 if (mControllerNumbers.isFull()) {
1635 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001636 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001637 return 0;
1638 }
1639 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
1640 // one
1641 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
1642}
1643
1644void EventHub::releaseControllerNumberLocked(Device* device) {
1645 int32_t num = device->controllerNumber;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001646 device->controllerNumber = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001647 if (num == 0) {
1648 return;
1649 }
1650 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
1651}
1652
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001653void EventHub::setLedForControllerLocked(Device* device) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001654 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
1655 setLedStateLocked(device, ALED_CONTROLLER_1 + i, device->controllerNumber == i + 1);
1656 }
1657}
1658
1659bool EventHub::hasKeycodeLocked(Device* device, int keycode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001660 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001661 return false;
1662 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001663
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001664 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001665 device->keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes);
1666 const size_t N = scanCodes.size();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001667 for (size_t i = 0; i < N && i <= KEY_MAX; i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001668 int32_t sc = scanCodes[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001669 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, device->keyBitmask)) {
1670 return true;
1671 }
1672 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001673
Michael Wrightd02c5b62014-02-10 15:10:22 -08001674 return false;
1675}
1676
1677status_t EventHub::mapLed(Device* device, int32_t led, int32_t* outScanCode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001678 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001679 return NAME_NOT_FOUND;
1680 }
1681
1682 int32_t scanCode;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001683 if (device->keyMap.keyLayoutMap->findScanCodeForLed(led, &scanCode) != NAME_NOT_FOUND) {
1684 if (scanCode >= 0 && scanCode <= LED_MAX && test_bit(scanCode, device->ledBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001685 *outScanCode = scanCode;
1686 return NO_ERROR;
1687 }
1688 }
1689 return NAME_NOT_FOUND;
1690}
1691
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001692void EventHub::closeDeviceByPathLocked(const char* devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001693 Device* device = getDeviceByPathLocked(devicePath);
1694 if (device) {
1695 closeDeviceLocked(device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001696 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001697 }
1698 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001699}
1700
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001701/**
1702 * Find the video device by filename, and close it.
1703 * The video device is closed by path during an inotify event, where we don't have the
1704 * additional context about the video device fd, or the associated input device.
1705 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001706void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001707 // A video device may be owned by an existing input device, or it may be stored in
1708 // the mUnattachedVideoDevices queue. Check both locations.
1709 for (size_t i = 0; i < mDevices.size(); i++) {
1710 Device* device = mDevices.valueAt(i);
1711 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001712 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001713 device->videoDevice = nullptr;
1714 return;
1715 }
1716 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001717 mUnattachedVideoDevices
1718 .erase(std::remove_if(mUnattachedVideoDevices.begin(), mUnattachedVideoDevices.end(),
1719 [&devicePath](
1720 const std::unique_ptr<TouchVideoDevice>& videoDevice) {
1721 return videoDevice->getPath() == devicePath;
1722 }),
1723 mUnattachedVideoDevices.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001724}
1725
1726void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001727 mUnattachedVideoDevices.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001728 while (mDevices.size() > 0) {
1729 closeDeviceLocked(mDevices.valueAt(mDevices.size() - 1));
1730 }
1731}
1732
1733void EventHub::closeDeviceLocked(Device* device) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001734 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=0x%x", device->path.c_str(),
1735 device->identifier.name.c_str(), device->id, device->fd, device->classes);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001736
1737 if (device->id == mBuiltInKeyboardId) {
1738 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001739 device->path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001740 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
1741 }
1742
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001743 unregisterDeviceFromEpollLocked(device);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001744 if (device->videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001745 // This must be done after the video device is removed from epoll
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001746 mUnattachedVideoDevices.push_back(std::move(device->videoDevice));
1747 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001748
1749 releaseControllerNumberLocked(device);
1750
1751 mDevices.removeItem(device->id);
1752 device->close();
1753
1754 // Unlink for opening devices list if it is present.
Yi Kong9b14ac62018-07-17 13:48:38 -07001755 Device* pred = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001756 bool found = false;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001757 for (Device* entry = mOpeningDevices; entry != nullptr;) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001758 if (entry == device) {
1759 found = true;
1760 break;
1761 }
1762 pred = entry;
1763 entry = entry->next;
1764 }
1765 if (found) {
1766 // Unlink the device from the opening devices list then delete it.
1767 // We don't need to tell the client that the device was closed because
1768 // it does not even know it was opened in the first place.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001769 ALOGI("Device %s was immediately closed after opening.", device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001770 if (pred) {
1771 pred->next = device->next;
1772 } else {
1773 mOpeningDevices = device->next;
1774 }
1775 delete device;
1776 } else {
1777 // Link into closing devices list.
1778 // The device will be deleted later after we have informed the client.
1779 device->next = mClosingDevices;
1780 mClosingDevices = device;
1781 }
1782}
1783
1784status_t EventHub::readNotifyLocked() {
1785 int res;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001786 char event_buf[512];
1787 int event_size;
1788 int event_pos = 0;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001789 struct inotify_event* event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001790
1791 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
1792 res = read(mINotifyFd, event_buf, sizeof(event_buf));
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001793 if (res < (int)sizeof(*event)) {
1794 if (errno == EINTR) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001795 ALOGW("could not get event, %s\n", strerror(errno));
1796 return -1;
1797 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001798
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001799 while (res >= (int)sizeof(*event)) {
1800 event = (struct inotify_event*)(event_buf + event_pos);
1801 if (event->len) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001802 if (event->wd == mInputWd) {
1803 std::string filename = StringPrintf("%s/%s", DEVICE_PATH, event->name);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001804 if (event->mask & IN_CREATE) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001805 openDeviceLocked(filename.c_str());
1806 } else {
1807 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
1808 closeDeviceByPathLocked(filename.c_str());
1809 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001810 } else if (event->wd == mVideoWd) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001811 if (isV4lTouchNode(event->name)) {
1812 std::string filename = StringPrintf("%s/%s", VIDEO_DEVICE_PATH, event->name);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001813 if (event->mask & IN_CREATE) {
1814 openVideoDeviceLocked(filename);
1815 } else {
1816 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
1817 closeVideoDeviceByPathLocked(filename);
1818 }
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001819 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001820 } else {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001821 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event->wd);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001822 }
1823 }
1824 event_size = sizeof(*event) + event->len;
1825 res -= event_size;
1826 event_pos += event_size;
1827 }
1828 return 0;
1829}
1830
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001831status_t EventHub::scanDirLocked(const char* dirname) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001832 char devname[PATH_MAX];
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001833 char* filename;
1834 DIR* dir;
1835 struct dirent* de;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001836 dir = opendir(dirname);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001837 if (dir == nullptr) return -1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001838 strcpy(devname, dirname);
1839 filename = devname + strlen(devname);
1840 *filename++ = '/';
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001841 while ((de = readdir(dir))) {
1842 if (de->d_name[0] == '.' &&
1843 (de->d_name[1] == '\0' || (de->d_name[1] == '.' && de->d_name[2] == '\0')))
Michael Wrightd02c5b62014-02-10 15:10:22 -08001844 continue;
1845 strcpy(filename, de->d_name);
1846 openDeviceLocked(devname);
1847 }
1848 closedir(dir);
1849 return 0;
1850}
1851
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001852/**
1853 * Look for all dirname/v4l-touch* devices, and open them.
1854 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001855status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001856 DIR* dir;
1857 struct dirent* de;
1858 dir = opendir(dirname.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001859 if (!dir) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001860 ALOGE("Could not open video directory %s", dirname.c_str());
1861 return BAD_VALUE;
1862 }
1863
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001864 while ((de = readdir(dir))) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001865 const char* name = de->d_name;
1866 if (isV4lTouchNode(name)) {
1867 ALOGI("Found touch video device %s", name);
1868 openVideoDeviceLocked(dirname + "/" + name);
1869 }
1870 }
1871 closedir(dir);
1872 return OK;
1873}
1874
Michael Wrightd02c5b62014-02-10 15:10:22 -08001875void EventHub::requestReopenDevices() {
1876 ALOGV("requestReopenDevices() called");
1877
1878 AutoMutex _l(mLock);
1879 mNeedToReopenDevices = true;
1880}
1881
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001882void EventHub::dump(std::string& dump) {
1883 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001884
1885 { // acquire lock
1886 AutoMutex _l(mLock);
1887
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001888 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001889
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001890 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001891
1892 for (size_t i = 0; i < mDevices.size(); i++) {
1893 const Device* device = mDevices.valueAt(i);
1894 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001895 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001896 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001897 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001898 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001899 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001900 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001901 dump += StringPrintf(INDENT3 "Classes: 0x%08x\n", device->classes);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001902 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001903 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001904 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
1905 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001906 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001907 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001908 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001909 "product=0x%04x, version=0x%04x\n",
1910 device->identifier.bus, device->identifier.vendor,
1911 device->identifier.product, device->identifier.version);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001912 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001913 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001914 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001915 device->keyMap.keyCharacterMapFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001916 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001917 device->configurationFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001918 dump += StringPrintf(INDENT3 "HaveKeyboardLayoutOverlay: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001919 toString(device->overlayKeyMap != nullptr));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001920 dump += INDENT3 "VideoDevice: ";
1921 if (device->videoDevice) {
1922 dump += device->videoDevice->dump() + "\n";
1923 } else {
1924 dump += "<none>\n";
1925 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001926 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001927
1928 dump += INDENT "Unattached video devices:\n";
1929 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
1930 dump += INDENT2 + videoDevice->dump() + "\n";
1931 }
1932 if (mUnattachedVideoDevices.empty()) {
1933 dump += INDENT2 "<none>\n";
1934 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001935 } // release lock
1936}
1937
1938void EventHub::monitor() {
1939 // Acquire and release the lock to ensure that the event hub has not deadlocked.
1940 mLock.lock();
1941 mLock.unlock();
1942}
1943
Michael Wrightd02c5b62014-02-10 15:10:22 -08001944}; // namespace android