blob: 20a843fbf56b588dd4a58fd094e3ea43fcf0d81c [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>
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +010027#include <sys/capability.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070028#include <sys/epoll.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070029#include <sys/inotify.h>
30#include <sys/ioctl.h>
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070031#include <sys/limits.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070032#include <unistd.h>
33
Michael Wrightd02c5b62014-02-10 15:10:22 -080034#define LOG_TAG "EventHub"
35
36// #define LOG_NDEBUG 0
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080037#include <android-base/stringprintf.h>
Philip Quinn39b81682019-01-09 22:20:39 -080038#include <cutils/properties.h>
Chris Yedb924702020-07-14 10:34:06 -070039#include <input/KeyCharacterMap.h>
40#include <input/KeyLayoutMap.h>
41#include <input/VirtualKeyMap.h>
Dan Albert677d87e2014-06-16 17:31:28 -070042#include <openssl/sha.h>
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070043#include <utils/Errors.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080044#include <utils/Log.h>
45#include <utils/Timers.h>
46#include <utils/threads.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080047
Chris Yedb924702020-07-14 10:34:06 -070048#include <filesystem>
49
50#include "EventHub.h"
Michael Wrightd02c5b62014-02-10 15:10:22 -080051
Michael Wrightd02c5b62014-02-10 15:10:22 -080052/* this macro is used to tell if "bit" is set in "array"
53 * it selects a byte from the array, and does a boolean AND
54 * operation with a byte that only has the relevant bit set.
55 * eg. to check for the 12th bit, we do (array[1] & 1<<4)
56 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070057#define test_bit(bit, array) ((array)[(bit) / 8] & (1 << ((bit) % 8)))
Michael Wrightd02c5b62014-02-10 15:10:22 -080058
59/* this macro computes the number of bytes needed to represent a bit array of the specified size */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070060#define sizeof_bit_array(bits) (((bits) + 7) / 8)
Michael Wrightd02c5b62014-02-10 15:10:22 -080061
62#define INDENT " "
63#define INDENT2 " "
64#define INDENT3 " "
65
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080066using android::base::StringPrintf;
67
Michael Wrightd02c5b62014-02-10 15:10:22 -080068namespace android {
69
Siarhei Vishniakou25920312018-12-12 15:24:44 -080070static constexpr bool DEBUG = false;
71
Usama Arifd9a25ed2021-06-03 16:44:09 +010072static const char* DEVICE_INPUT_PATH = "/dev/input";
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080073// v4l2 devices go directly into /dev
Usama Arifd9a25ed2021-06-03 16:44:09 +010074static const char* DEVICE_PATH = "/dev";
Michael Wrightd02c5b62014-02-10 15:10:22 -080075
Michael Wrightd02c5b62014-02-10 15:10:22 -080076static inline const char* toString(bool value) {
77 return value ? "true" : "false";
78}
79
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010080static std::string sha1(const std::string& in) {
Dan Albert677d87e2014-06-16 17:31:28 -070081 SHA_CTX ctx;
82 SHA1_Init(&ctx);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010083 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
Dan Albert677d87e2014-06-16 17:31:28 -070084 u_char digest[SHA_DIGEST_LENGTH];
85 SHA1_Final(digest, &ctx);
Michael Wrightd02c5b62014-02-10 15:10:22 -080086
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010087 std::string out;
Dan Albert677d87e2014-06-16 17:31:28 -070088 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010089 out += StringPrintf("%02x", digest[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -080090 }
91 return out;
92}
93
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080094/**
95 * Return true if name matches "v4l-touch*"
96 */
Chris Yedb924702020-07-14 10:34:06 -070097static bool isV4lTouchNode(std::string name) {
98 return name.find("v4l-touch") != std::string::npos;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080099}
100
Philip Quinn39b81682019-01-09 22:20:39 -0800101/**
102 * Returns true if V4L devices should be scanned.
103 *
104 * The system property ro.input.video_enabled can be used to control whether
105 * EventHub scans and opens V4L devices. As V4L does not support multiple
106 * clients, EventHub effectively blocks access to these devices when it opens
Siarhei Vishniakou29f88492019-04-05 14:11:43 -0700107 * them.
108 *
109 * Setting this to "false" would prevent any video devices from being discovered and
110 * associated with input devices.
111 *
112 * This property can be used as follows:
113 * 1. To turn off features that are dependent on video device presence.
114 * 2. During testing and development, to allow other clients to read video devices
115 * directly from /dev.
Philip Quinn39b81682019-01-09 22:20:39 -0800116 */
117static bool isV4lScanningEnabled() {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700118 return property_get_bool("ro.input.video_enabled", true /* default_value */);
Philip Quinn39b81682019-01-09 22:20:39 -0800119}
120
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800121static nsecs_t processEventTimestamp(const struct input_event& event) {
122 // Use the time specified in the event instead of the current time
123 // so that downstream code can get more accurate estimates of
124 // event dispatch latency from the time the event is enqueued onto
125 // the evdev client buffer.
126 //
127 // The event's timestamp fortuitously uses the same monotonic clock
128 // time base as the rest of Android. The kernel event device driver
129 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
130 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
131 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
132 // system call that also queries ktime_get_ts().
133
134 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.time.tv_sec) +
135 microseconds_to_nanoseconds(event.time.tv_usec);
136 return inputEventTime;
137}
138
Michael Wrightd02c5b62014-02-10 15:10:22 -0800139// --- Global Functions ---
140
141uint32_t getAbsAxisUsage(int32_t axis, uint32_t deviceClasses) {
142 // Touch devices get dibs on touch-related axes.
143 if (deviceClasses & INPUT_DEVICE_CLASS_TOUCH) {
144 switch (axis) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700145 case ABS_X:
146 case ABS_Y:
147 case ABS_PRESSURE:
148 case ABS_TOOL_WIDTH:
149 case ABS_DISTANCE:
150 case ABS_TILT_X:
151 case ABS_TILT_Y:
152 case ABS_MT_SLOT:
153 case ABS_MT_TOUCH_MAJOR:
154 case ABS_MT_TOUCH_MINOR:
155 case ABS_MT_WIDTH_MAJOR:
156 case ABS_MT_WIDTH_MINOR:
157 case ABS_MT_ORIENTATION:
158 case ABS_MT_POSITION_X:
159 case ABS_MT_POSITION_Y:
160 case ABS_MT_TOOL_TYPE:
161 case ABS_MT_BLOB_ID:
162 case ABS_MT_TRACKING_ID:
163 case ABS_MT_PRESSURE:
164 case ABS_MT_DISTANCE:
165 return INPUT_DEVICE_CLASS_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800166 }
167 }
168
Michael Wright842500e2015-03-13 17:32:02 -0700169 // External stylus gets the pressure axis
170 if (deviceClasses & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
171 if (axis == ABS_PRESSURE) {
172 return INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
173 }
174 }
175
Michael Wrightd02c5b62014-02-10 15:10:22 -0800176 // Joystick devices get the rest.
177 return deviceClasses & INPUT_DEVICE_CLASS_JOYSTICK;
178}
179
180// --- EventHub::Device ---
181
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100182EventHub::Device::Device(int fd, int32_t id, const std::string& path,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700183 const InputDeviceIdentifier& identifier)
184 : next(nullptr),
185 fd(fd),
186 id(id),
187 path(path),
188 identifier(identifier),
189 classes(0),
190 configuration(nullptr),
191 virtualKeyMap(nullptr),
192 ffEffectPlaying(false),
193 ffEffectId(-1),
194 controllerNumber(0),
195 enabled(true),
196 isVirtual(fd < 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800197 memset(keyBitmask, 0, sizeof(keyBitmask));
198 memset(absBitmask, 0, sizeof(absBitmask));
199 memset(relBitmask, 0, sizeof(relBitmask));
200 memset(swBitmask, 0, sizeof(swBitmask));
201 memset(ledBitmask, 0, sizeof(ledBitmask));
202 memset(ffBitmask, 0, sizeof(ffBitmask));
203 memset(propBitmask, 0, sizeof(propBitmask));
204}
205
206EventHub::Device::~Device() {
207 close();
208 delete configuration;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800209}
210
211void EventHub::Device::close() {
212 if (fd >= 0) {
213 ::close(fd);
214 fd = -1;
215 }
216}
217
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700218status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100219 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700220 if (fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100221 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700222 return -errno;
223 }
224 enabled = true;
225 return OK;
226}
227
228status_t EventHub::Device::disable() {
229 close();
230 enabled = false;
231 return OK;
232}
233
234bool EventHub::Device::hasValidFd() {
235 return !isVirtual && enabled;
236}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800237
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100238/**
239 * Get the capabilities for the current process.
240 * Crashes the system if unable to create / check / destroy the capabilities object.
241 */
242class Capabilities final {
243public:
244 explicit Capabilities() {
245 mCaps = cap_get_proc();
246 LOG_ALWAYS_FATAL_IF(mCaps == nullptr, "Could not get capabilities of the current process");
247 }
248
249 /**
250 * Check whether the current process has a specific capability
251 * in the set of effective capabilities.
252 * Return CAP_SET if the process has the requested capability
253 * Return CAP_CLEAR otherwise.
254 */
255 cap_flag_value_t checkEffectiveCapability(cap_value_t capability) {
256 cap_flag_value_t value;
257 const int result = cap_get_flag(mCaps, capability, CAP_EFFECTIVE, &value);
258 LOG_ALWAYS_FATAL_IF(result == -1, "Could not obtain the requested capability");
259 return value;
260 }
261
262 ~Capabilities() {
263 const int result = cap_free(mCaps);
264 LOG_ALWAYS_FATAL_IF(result == -1, "Could not release the capabilities structure");
265 }
266
267private:
268 cap_t mCaps;
269};
270
271static void ensureProcessCanBlockSuspend() {
272 Capabilities capabilities;
273 const bool canBlockSuspend =
274 capabilities.checkEffectiveCapability(CAP_BLOCK_SUSPEND) == CAP_SET;
275 LOG_ALWAYS_FATAL_IF(!canBlockSuspend,
276 "Input must be able to block suspend to properly process events");
277}
278
Michael Wrightd02c5b62014-02-10 15:10:22 -0800279// --- EventHub ---
280
Michael Wrightd02c5b62014-02-10 15:10:22 -0800281const int EventHub::EPOLL_MAX_EVENTS;
282
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700283EventHub::EventHub(void)
284 : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
285 mNextDeviceId(1),
286 mControllerNumbers(),
287 mOpeningDevices(nullptr),
288 mClosingDevices(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800289 mNeedToSendFinishedDeviceScan(false),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700290 mNeedToReopenDevices(false),
291 mNeedToScanDevices(true),
292 mPendingEventCount(0),
293 mPendingEventIndex(0),
294 mPendingINotify(false) {
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100295 ensureProcessCanBlockSuspend();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800296
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800297 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800298 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800299
300 mINotifyFd = inotify_init();
Usama Arifd9a25ed2021-06-03 16:44:09 +0100301
302 std::error_code errorCode;
303 bool isDeviceInotifyAdded = false;
304 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
305 addDeviceInputInotify();
Philip Quinn39b81682019-01-09 22:20:39 -0800306 } else {
Usama Arifd9a25ed2021-06-03 16:44:09 +0100307 addDeviceInotify();
308 isDeviceInotifyAdded = true;
309 if (errorCode) {
310 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
311 errorCode.message().c_str());
312 }
313 }
314
315 if (isV4lScanningEnabled() && !isDeviceInotifyAdded) {
316 addDeviceInotify();
317 } else {
Philip Quinn39b81682019-01-09 22:20:39 -0800318 ALOGI("Video device scanning disabled");
319 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800320
Siarhei Vishniakou2d0e9482019-09-24 12:52:47 +0100321 struct epoll_event eventItem = {};
322 eventItem.events = EPOLLIN | EPOLLWAKEUP;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700323 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800324 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800325 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
326
327 int wakeFds[2];
328 result = pipe(wakeFds);
329 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
330
331 mWakeReadPipeFd = wakeFds[0];
332 mWakeWritePipeFd = wakeFds[1];
333
334 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
335 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700336 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800337
338 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
339 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700340 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800341
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700342 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800343 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
344 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700345 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800346}
347
348EventHub::~EventHub(void) {
349 closeAllDevicesLocked();
350
351 while (mClosingDevices) {
352 Device* device = mClosingDevices;
353 mClosingDevices = device->next;
354 delete device;
355 }
356
357 ::close(mEpollFd);
358 ::close(mINotifyFd);
359 ::close(mWakeReadPipeFd);
360 ::close(mWakeWritePipeFd);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800361}
362
Usama Arifd9a25ed2021-06-03 16:44:09 +0100363/**
364 * On devices that don't have any input devices (like some development boards), the /dev/input
365 * directory will be absent. However, the user may still plug in an input device at a later time.
366 * Add watch for contents of /dev/input only when /dev/input appears.
367 */
368void EventHub::addDeviceInputInotify() {
369 mDeviceInputWd = inotify_add_watch(mINotifyFd, DEVICE_INPUT_PATH, IN_DELETE | IN_CREATE);
370 LOG_ALWAYS_FATAL_IF(mDeviceInputWd < 0, "Could not register INotify for %s: %s",
371 DEVICE_INPUT_PATH, strerror(errno));
372}
373
374void EventHub::addDeviceInotify() {
375 mDeviceWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
376 LOG_ALWAYS_FATAL_IF(mDeviceWd < 0, "Could not register INotify for %s: %s",
377 DEVICE_PATH, strerror(errno));
378}
379
Michael Wrightd02c5b62014-02-10 15:10:22 -0800380InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
381 AutoMutex _l(mLock);
382 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700383 if (device == nullptr) return InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800384 return device->identifier;
385}
386
387uint32_t EventHub::getDeviceClasses(int32_t deviceId) const {
388 AutoMutex _l(mLock);
389 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700390 if (device == nullptr) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800391 return device->classes;
392}
393
394int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
395 AutoMutex _l(mLock);
396 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700397 if (device == nullptr) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800398 return device->controllerNumber;
399}
400
401void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
402 AutoMutex _l(mLock);
403 Device* device = getDeviceLocked(deviceId);
404 if (device && device->configuration) {
405 *outConfiguration = *device->configuration;
406 } else {
407 outConfiguration->clear();
408 }
409}
410
411status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700412 RawAbsoluteAxisInfo* outAxisInfo) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800413 outAxisInfo->clear();
414
415 if (axis >= 0 && axis <= ABS_MAX) {
416 AutoMutex _l(mLock);
417
418 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700419 if (device && device->hasValidFd() && test_bit(axis, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800420 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700421 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
422 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
423 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800424 return -errno;
425 }
426
427 if (info.minimum != info.maximum) {
428 outAxisInfo->valid = true;
429 outAxisInfo->minValue = info.minimum;
430 outAxisInfo->maxValue = info.maximum;
431 outAxisInfo->flat = info.flat;
432 outAxisInfo->fuzz = info.fuzz;
433 outAxisInfo->resolution = info.resolution;
434 }
435 return OK;
436 }
437 }
438 return -1;
439}
440
441bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
442 if (axis >= 0 && axis <= REL_MAX) {
443 AutoMutex _l(mLock);
444
445 Device* device = getDeviceLocked(deviceId);
446 if (device) {
447 return test_bit(axis, device->relBitmask);
448 }
449 }
450 return false;
451}
452
453bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
454 if (property >= 0 && property <= INPUT_PROP_MAX) {
455 AutoMutex _l(mLock);
456
457 Device* device = getDeviceLocked(deviceId);
458 if (device) {
459 return test_bit(property, device->propBitmask);
460 }
461 }
462 return false;
463}
464
465int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
466 if (scanCode >= 0 && scanCode <= KEY_MAX) {
467 AutoMutex _l(mLock);
468
469 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700470 if (device && device->hasValidFd() && test_bit(scanCode, device->keyBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800471 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
472 memset(keyState, 0, sizeof(keyState));
473 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
474 return test_bit(scanCode, keyState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
475 }
476 }
477 }
478 return AKEY_STATE_UNKNOWN;
479}
480
481int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
482 AutoMutex _l(mLock);
483
484 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700485 if (device && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800486 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800487 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode, &scanCodes);
488 if (scanCodes.size() != 0) {
489 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
490 memset(keyState, 0, sizeof(keyState));
491 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
492 for (size_t i = 0; i < scanCodes.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800493 int32_t sc = scanCodes[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -0800494 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, keyState)) {
495 return AKEY_STATE_DOWN;
496 }
497 }
498 return AKEY_STATE_UP;
499 }
500 }
501 }
502 return AKEY_STATE_UNKNOWN;
503}
504
505int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
506 if (sw >= 0 && sw <= SW_MAX) {
507 AutoMutex _l(mLock);
508
509 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700510 if (device && device->hasValidFd() && test_bit(sw, device->swBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800511 uint8_t swState[sizeof_bit_array(SW_MAX + 1)];
512 memset(swState, 0, sizeof(swState));
513 if (ioctl(device->fd, EVIOCGSW(sizeof(swState)), swState) >= 0) {
514 return test_bit(sw, swState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
515 }
516 }
517 }
518 return AKEY_STATE_UNKNOWN;
519}
520
521status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
522 *outValue = 0;
523
524 if (axis >= 0 && axis <= ABS_MAX) {
525 AutoMutex _l(mLock);
526
527 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700528 if (device && device->hasValidFd() && test_bit(axis, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800529 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700530 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
531 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
532 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800533 return -errno;
534 }
535
536 *outValue = info.value;
537 return OK;
538 }
539 }
540 return -1;
541}
542
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700543bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes, const int32_t* keyCodes,
544 uint8_t* outFlags) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800545 AutoMutex _l(mLock);
546
547 Device* device = getDeviceLocked(deviceId);
548 if (device && device->keyMap.haveKeyLayout()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800549 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800550 for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) {
551 scanCodes.clear();
552
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700553 status_t err = device->keyMap.keyLayoutMap->findScanCodesForKey(keyCodes[codeIndex],
554 &scanCodes);
555 if (!err) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800556 // check the possible scan codes identified by the layout map against the
557 // map of codes actually emitted by the driver
558 for (size_t sc = 0; sc < scanCodes.size(); sc++) {
559 if (test_bit(scanCodes[sc], device->keyBitmask)) {
560 outFlags[codeIndex] = 1;
561 break;
562 }
563 }
564 }
565 }
566 return true;
567 }
568 return false;
569}
570
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700571status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
572 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800573 AutoMutex _l(mLock);
574 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700575 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800576
577 if (device) {
578 // Check the key character map first.
579 sp<KeyCharacterMap> kcm = device->getKeyCharacterMap();
Yi Kong9b14ac62018-07-17 13:48:38 -0700580 if (kcm != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800581 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
582 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700583 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800584 }
585 }
586
587 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700588 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800589 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700590 status = NO_ERROR;
591 }
592 }
593
594 if (status == NO_ERROR) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700595 if (kcm != nullptr) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700596 kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState);
597 } else {
598 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800599 }
600 }
601 }
602
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700603 if (status != NO_ERROR) {
604 *outKeycode = 0;
605 *outFlags = 0;
606 *outMetaState = metaState;
607 }
608
609 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800610}
611
612status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
613 AutoMutex _l(mLock);
614 Device* device = getDeviceLocked(deviceId);
615
616 if (device && device->keyMap.haveKeyLayout()) {
617 status_t err = device->keyMap.keyLayoutMap->mapAxis(scanCode, outAxisInfo);
618 if (err == NO_ERROR) {
619 return NO_ERROR;
620 }
621 }
622
623 return NAME_NOT_FOUND;
624}
625
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100626void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800627 AutoMutex _l(mLock);
628
629 mExcludedDevices = devices;
630}
631
632bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
633 AutoMutex _l(mLock);
634 Device* device = getDeviceLocked(deviceId);
635 if (device && scanCode >= 0 && scanCode <= KEY_MAX) {
636 if (test_bit(scanCode, device->keyBitmask)) {
637 return true;
638 }
639 }
640 return false;
641}
642
643bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
644 AutoMutex _l(mLock);
645 Device* device = getDeviceLocked(deviceId);
646 int32_t sc;
647 if (device && mapLed(device, led, &sc) == NO_ERROR) {
648 if (test_bit(sc, device->ledBitmask)) {
649 return true;
650 }
651 }
652 return false;
653}
654
655void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
656 AutoMutex _l(mLock);
657 Device* device = getDeviceLocked(deviceId);
658 setLedStateLocked(device, led, on);
659}
660
661void EventHub::setLedStateLocked(Device* device, int32_t led, bool on) {
662 int32_t sc;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700663 if (device && device->hasValidFd() && mapLed(device, led, &sc) != NAME_NOT_FOUND) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800664 struct input_event ev;
665 ev.time.tv_sec = 0;
666 ev.time.tv_usec = 0;
667 ev.type = EV_LED;
668 ev.code = sc;
669 ev.value = on ? 1 : 0;
670
671 ssize_t nWrite;
672 do {
673 nWrite = write(device->fd, &ev, sizeof(struct input_event));
674 } while (nWrite == -1 && errno == EINTR);
675 }
676}
677
678void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700679 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800680 outVirtualKeys.clear();
681
682 AutoMutex _l(mLock);
683 Device* device = getDeviceLocked(deviceId);
684 if (device && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800685 const std::vector<VirtualKeyDefinition> virtualKeys =
686 device->virtualKeyMap->getVirtualKeys();
687 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800688 }
689}
690
691sp<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
692 AutoMutex _l(mLock);
693 Device* device = getDeviceLocked(deviceId);
694 if (device) {
695 return device->getKeyCharacterMap();
696 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700697 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800698}
699
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700700bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, const sp<KeyCharacterMap>& map) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800701 AutoMutex _l(mLock);
702 Device* device = getDeviceLocked(deviceId);
703 if (device) {
704 if (map != device->overlayKeyMap) {
705 device->overlayKeyMap = map;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700706 device->combinedKeyMap = KeyCharacterMap::combine(device->keyMap.keyCharacterMap, map);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800707 return true;
708 }
709 }
710 return false;
711}
712
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100713static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
714 std::string rawDescriptor;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700715 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800716 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100717 if (!identifier.uniqueId.empty()) {
718 rawDescriptor += "uniqueId:";
719 rawDescriptor += identifier.uniqueId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800720 } else if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100721 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800722 }
723
724 if (identifier.vendor == 0 && identifier.product == 0) {
725 // If we don't know the vendor and product id, then the device is probably
726 // built-in so we need to rely on other information to uniquely identify
727 // the input device. Usually we try to avoid relying on the device name or
728 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100729 if (!identifier.name.empty()) {
730 rawDescriptor += "name:";
731 rawDescriptor += identifier.name;
732 } else if (!identifier.location.empty()) {
733 rawDescriptor += "location:";
734 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800735 }
736 }
737 identifier.descriptor = sha1(rawDescriptor);
738 return rawDescriptor;
739}
740
741void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
742 // Compute a device descriptor that uniquely identifies the device.
743 // The descriptor is assumed to be a stable identifier. Its value should not
744 // change between reboots, reconnections, firmware updates or new releases
745 // of Android. In practice we sometimes get devices that cannot be uniquely
746 // identified. In this case we enforce uniqueness between connected devices.
747 // Ideally, we also want the descriptor to be short and relatively opaque.
748
749 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100750 std::string rawDescriptor = generateDescriptor(identifier);
751 if (identifier.uniqueId.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800752 // If it didn't have a unique id check for conflicts and enforce
753 // uniqueness if necessary.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700754 while (getDeviceByDescriptorLocked(identifier.descriptor) != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800755 identifier.nonce++;
756 rawDescriptor = generateDescriptor(identifier);
757 }
758 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100759 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700760 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800761}
762
763void EventHub::vibrate(int32_t deviceId, nsecs_t duration) {
764 AutoMutex _l(mLock);
765 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700766 if (device && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800767 ff_effect effect;
768 memset(&effect, 0, sizeof(effect));
769 effect.type = FF_RUMBLE;
770 effect.id = device->ffEffectId;
771 effect.u.rumble.strong_magnitude = 0xc000;
772 effect.u.rumble.weak_magnitude = 0xc000;
773 effect.replay.length = (duration + 999999LL) / 1000000LL;
774 effect.replay.delay = 0;
775 if (ioctl(device->fd, EVIOCSFF, &effect)) {
776 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700777 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800778 return;
779 }
780 device->ffEffectId = effect.id;
781
782 struct input_event ev;
783 ev.time.tv_sec = 0;
784 ev.time.tv_usec = 0;
785 ev.type = EV_FF;
786 ev.code = device->ffEffectId;
787 ev.value = 1;
788 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
789 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700790 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800791 return;
792 }
793 device->ffEffectPlaying = true;
794 }
795}
796
797void EventHub::cancelVibrate(int32_t deviceId) {
798 AutoMutex _l(mLock);
799 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700800 if (device && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800801 if (device->ffEffectPlaying) {
802 device->ffEffectPlaying = false;
803
804 struct input_event ev;
805 ev.time.tv_sec = 0;
806 ev.time.tv_usec = 0;
807 ev.type = EV_FF;
808 ev.code = device->ffEffectId;
809 ev.value = 0;
810 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
811 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700812 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800813 return;
814 }
815 }
816 }
817}
818
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100819EventHub::Device* EventHub::getDeviceByDescriptorLocked(const std::string& descriptor) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800820 size_t size = mDevices.size();
821 for (size_t i = 0; i < size; i++) {
822 Device* device = mDevices.valueAt(i);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100823 if (descriptor == device->identifier.descriptor) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800824 return device;
825 }
826 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700827 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800828}
829
830EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -0800831 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800832 deviceId = mBuiltInKeyboardId;
833 }
834 ssize_t index = mDevices.indexOfKey(deviceId);
835 return index >= 0 ? mDevices.valueAt(index) : NULL;
836}
837
Chris Yedb924702020-07-14 10:34:06 -0700838EventHub::Device* EventHub::getDeviceByPathLocked(const std::string& devicePath) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800839 for (size_t i = 0; i < mDevices.size(); i++) {
840 Device* device = mDevices.valueAt(i);
841 if (device->path == devicePath) {
842 return device;
843 }
844 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700845 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800846}
847
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700848/**
849 * The file descriptor could be either input device, or a video device (associated with a
850 * specific input device). Check both cases here, and return the device that this event
851 * belongs to. Caller can compare the fd's once more to determine event type.
852 * Looks through all input devices, and only attached video devices. Unattached video
853 * devices are ignored.
854 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700855EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
856 for (size_t i = 0; i < mDevices.size(); i++) {
857 Device* device = mDevices.valueAt(i);
858 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700859 // This is an input device event
860 return device;
861 }
862 if (device->videoDevice && device->videoDevice->getFd() == fd) {
863 // This is a video device event
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700864 return device;
865 }
866 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700867 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
868 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700869 return nullptr;
870}
871
Michael Wrightd02c5b62014-02-10 15:10:22 -0800872size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
873 ALOG_ASSERT(bufferSize >= 1);
874
875 AutoMutex _l(mLock);
876
877 struct input_event readBuffer[bufferSize];
878
879 RawEvent* event = buffer;
880 size_t capacity = bufferSize;
881 bool awoken = false;
882 for (;;) {
883 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
884
885 // Reopen input devices if needed.
886 if (mNeedToReopenDevices) {
887 mNeedToReopenDevices = false;
888
889 ALOGI("Reopening all input devices due to a configuration change.");
890
891 closeAllDevicesLocked();
892 mNeedToScanDevices = true;
893 break; // return to the caller before we actually rescan
894 }
895
896 // Report any devices that had last been added/removed.
897 while (mClosingDevices) {
898 Device* device = mClosingDevices;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700899 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800900 mClosingDevices = device->next;
901 event->when = now;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700902 event->deviceId = (device->id == mBuiltInKeyboardId)
903 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
904 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800905 event->type = DEVICE_REMOVED;
906 event += 1;
907 delete device;
908 mNeedToSendFinishedDeviceScan = true;
909 if (--capacity == 0) {
910 break;
911 }
912 }
913
914 if (mNeedToScanDevices) {
915 mNeedToScanDevices = false;
916 scanDevicesLocked();
917 mNeedToSendFinishedDeviceScan = true;
918 }
919
Yi Kong9b14ac62018-07-17 13:48:38 -0700920 while (mOpeningDevices != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800921 Device* device = mOpeningDevices;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700922 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800923 mOpeningDevices = device->next;
924 event->when = now;
925 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
926 event->type = DEVICE_ADDED;
927 event += 1;
928 mNeedToSendFinishedDeviceScan = true;
929 if (--capacity == 0) {
930 break;
931 }
932 }
933
934 if (mNeedToSendFinishedDeviceScan) {
935 mNeedToSendFinishedDeviceScan = false;
936 event->when = now;
937 event->type = FINISHED_DEVICE_SCAN;
938 event += 1;
939 if (--capacity == 0) {
940 break;
941 }
942 }
943
944 // Grab the next input event.
945 bool deviceChanged = false;
946 while (mPendingEventIndex < mPendingEventCount) {
947 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700948 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800949 if (eventItem.events & EPOLLIN) {
950 mPendingINotify = true;
951 } else {
952 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
953 }
954 continue;
955 }
956
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700957 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800958 if (eventItem.events & EPOLLIN) {
959 ALOGV("awoken after wake()");
960 awoken = true;
961 char buffer[16];
962 ssize_t nRead;
963 do {
964 nRead = read(mWakeReadPipeFd, buffer, sizeof(buffer));
965 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(buffer));
966 } else {
967 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700968 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800969 }
970 continue;
971 }
972
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700973 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700974 if (!device) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700975 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
976 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700977 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800978 continue;
979 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700980 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
981 if (eventItem.events & EPOLLIN) {
982 size_t numFrames = device->videoDevice->readAndQueueFrames();
983 if (numFrames == 0) {
984 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700985 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700986 }
987 } else if (eventItem.events & EPOLLHUP) {
988 // TODO(b/121395353) - consider adding EPOLLRDHUP
989 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700990 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700991 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
992 device->videoDevice = nullptr;
993 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700994 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
995 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700996 ALOG_ASSERT(!DEBUG);
997 }
998 continue;
999 }
1000 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -08001001 if (eventItem.events & EPOLLIN) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001002 int32_t readSize =
1003 read(device->fd, readBuffer, sizeof(struct input_event) * capacity);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001004 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
1005 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -07001006 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001007 " bufferSize: %zu capacity: %zu errno: %d)\n",
1008 device->fd, readSize, bufferSize, capacity, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001009 deviceChanged = true;
1010 closeDeviceLocked(device);
1011 } else if (readSize < 0) {
1012 if (errno != EAGAIN && errno != EINTR) {
1013 ALOGW("could not get event (errno=%d)", errno);
1014 }
1015 } else if ((readSize % sizeof(struct input_event)) != 0) {
1016 ALOGE("could not get event (wrong size: %d)", readSize);
1017 } else {
1018 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1019
1020 size_t count = size_t(readSize) / sizeof(struct input_event);
1021 for (size_t i = 0; i < count; i++) {
1022 struct input_event& iev = readBuffer[i];
Siarhei Vishniakou592bac22018-11-08 19:42:38 -08001023 event->when = processEventTimestamp(iev);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001024 event->deviceId = deviceId;
1025 event->type = iev.type;
1026 event->code = iev.code;
1027 event->value = iev.value;
1028 event += 1;
1029 capacity -= 1;
1030 }
1031 if (capacity == 0) {
1032 // The result buffer is full. Reset the pending event index
1033 // so we will try to read the device again on the next iteration.
1034 mPendingEventIndex -= 1;
1035 break;
1036 }
1037 }
1038 } else if (eventItem.events & EPOLLHUP) {
1039 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001040 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001041 deviceChanged = true;
1042 closeDeviceLocked(device);
1043 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001044 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1045 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001046 }
1047 }
1048
1049 // readNotify() will modify the list of devices so this must be done after
1050 // processing all other events to ensure that we read all remaining events
1051 // before closing the devices.
1052 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
1053 mPendingINotify = false;
1054 readNotifyLocked();
1055 deviceChanged = true;
1056 }
1057
1058 // Report added or removed devices immediately.
1059 if (deviceChanged) {
1060 continue;
1061 }
1062
1063 // Return now if we have collected any events or if we were explicitly awoken.
1064 if (event != buffer || awoken) {
1065 break;
1066 }
1067
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001068 // Poll for events.
1069 // When a device driver has pending (unread) events, it acquires
1070 // a kernel wake lock. Once the last pending event has been read, the device
1071 // driver will release the kernel wake lock, but the epoll will hold the wakelock,
1072 // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
1073 // is called again for the same fd that produced the event.
1074 // Thus the system can only sleep if there are no events pending or
1075 // currently being processed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001076 //
1077 // The timeout is advisory only. If the device is asleep, it will not wake just to
1078 // service the timeout.
1079 mPendingEventIndex = 0;
1080
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001081 mLock.unlock(); // release lock before poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001082
1083 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1084
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001085 mLock.lock(); // reacquire lock after poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001086
1087 if (pollResult == 0) {
1088 // Timed out.
1089 mPendingEventCount = 0;
1090 break;
1091 }
1092
1093 if (pollResult < 0) {
1094 // An error occurred.
1095 mPendingEventCount = 0;
1096
1097 // Sleep after errors to avoid locking up the system.
1098 // Hopefully the error is transient.
1099 if (errno != EINTR) {
1100 ALOGW("poll failed (errno=%d)\n", errno);
1101 usleep(100000);
1102 }
1103 } else {
1104 // Some events occurred.
1105 mPendingEventCount = size_t(pollResult);
1106 }
1107 }
1108
1109 // All done, return the number of events we read.
1110 return event - buffer;
1111}
1112
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001113std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
1114 AutoMutex _l(mLock);
1115
1116 Device* device = getDeviceLocked(deviceId);
1117 if (!device || !device->videoDevice) {
1118 return {};
1119 }
1120 return device->videoDevice->consumeFrames();
1121}
1122
Michael Wrightd02c5b62014-02-10 15:10:22 -08001123void EventHub::wake() {
1124 ALOGV("wake() called");
1125
1126 ssize_t nWrite;
1127 do {
1128 nWrite = write(mWakeWritePipeFd, "W", 1);
1129 } while (nWrite == -1 && errno == EINTR);
1130
1131 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001132 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001133 }
1134}
1135
1136void EventHub::scanDevicesLocked() {
Usama Arifd9a25ed2021-06-03 16:44:09 +01001137 status_t result;
1138 std::error_code errorCode;
1139
1140 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
1141 result = scanDirLocked(DEVICE_INPUT_PATH);
1142 if (result < 0) {
1143 ALOGE("scan dir failed for %s", DEVICE_INPUT_PATH);
1144 }
1145 } else {
1146 if (errorCode) {
1147 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
1148 errorCode.message().c_str());
1149 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001150 }
Philip Quinn39b81682019-01-09 22:20:39 -08001151 if (isV4lScanningEnabled()) {
Usama Arifd9a25ed2021-06-03 16:44:09 +01001152 result = scanVideoDirLocked(DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08001153 if (result != OK) {
Usama Arifd9a25ed2021-06-03 16:44:09 +01001154 ALOGE("scan video dir failed for %s", DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08001155 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001156 }
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001157 if (mDevices.indexOfKey(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) < 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001158 createVirtualKeyboardLocked();
1159 }
1160}
1161
1162// ----------------------------------------------------------------------------
1163
1164static bool containsNonZeroByte(const uint8_t* array, uint32_t startIndex, uint32_t endIndex) {
1165 const uint8_t* end = array + endIndex;
1166 array += startIndex;
1167 while (array != end) {
1168 if (*(array++) != 0) {
1169 return true;
1170 }
1171 }
1172 return false;
1173}
1174
1175static const int32_t GAMEPAD_KEYCODES[] = {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001176 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C, //
1177 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z, //
1178 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1, //
1179 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2, //
1180 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR, //
1181 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE, //
Michael Wrightd02c5b62014-02-10 15:10:22 -08001182};
1183
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001184status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001185 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001186 struct epoll_event eventItem = {};
1187 eventItem.events = EPOLLIN | EPOLLWAKEUP;
1188 eventItem.data.fd = fd;
1189 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1190 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001191 return -errno;
1192 }
1193 return OK;
1194}
1195
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001196status_t EventHub::unregisterFdFromEpoll(int fd) {
1197 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
1198 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
1199 return -errno;
1200 }
1201 return OK;
1202}
1203
1204status_t EventHub::registerDeviceForEpollLocked(Device* device) {
1205 if (device == nullptr) {
1206 if (DEBUG) {
1207 LOG_ALWAYS_FATAL("Cannot call registerDeviceForEpollLocked with null Device");
1208 }
1209 return BAD_VALUE;
1210 }
1211 status_t result = registerFdForEpoll(device->fd);
1212 if (result != OK) {
1213 ALOGE("Could not add input device fd to epoll for device %" PRId32, device->id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001214 return result;
1215 }
1216 if (device->videoDevice) {
1217 registerVideoDeviceForEpollLocked(*device->videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001218 }
1219 return result;
1220}
1221
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001222void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
1223 status_t result = registerFdForEpoll(videoDevice.getFd());
1224 if (result != OK) {
1225 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
1226 }
1227}
1228
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001229status_t EventHub::unregisterDeviceFromEpollLocked(Device* device) {
1230 if (device->hasValidFd()) {
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001231 status_t result = unregisterFdFromEpoll(device->fd);
1232 if (result != OK) {
1233 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device->id);
1234 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001235 }
1236 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001237 if (device->videoDevice) {
1238 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1239 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001240 return OK;
1241}
1242
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001243void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
1244 if (videoDevice.hasValidFd()) {
1245 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
1246 if (result != OK) {
1247 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001248 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001249 }
1250 }
1251}
1252
Chris Yedb924702020-07-14 10:34:06 -07001253status_t EventHub::openDeviceLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001254 char buffer[80];
1255
Chris Yedb924702020-07-14 10:34:06 -07001256 ALOGV("Opening device: %s", devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001257
Chris Yedb924702020-07-14 10:34:06 -07001258 int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001259 if (fd < 0) {
Chris Yedb924702020-07-14 10:34:06 -07001260 ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001261 return -1;
1262 }
1263
1264 InputDeviceIdentifier identifier;
1265
1266 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001267 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Chris Yedb924702020-07-14 10:34:06 -07001268 ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001269 } else {
1270 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001271 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001272 }
1273
1274 // Check to see if the device is on our excluded list
1275 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001276 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001277 if (identifier.name == item) {
Chris Yedb924702020-07-14 10:34:06 -07001278 ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001279 close(fd);
1280 return -1;
1281 }
1282 }
1283
1284 // Get device driver version.
1285 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001286 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Chris Yedb924702020-07-14 10:34:06 -07001287 ALOGE("could not get driver version for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001288 close(fd);
1289 return -1;
1290 }
1291
1292 // Get device identifier.
1293 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001294 if (ioctl(fd, EVIOCGID, &inputId)) {
Chris Yedb924702020-07-14 10:34:06 -07001295 ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001296 close(fd);
1297 return -1;
1298 }
1299 identifier.bus = inputId.bustype;
1300 identifier.product = inputId.product;
1301 identifier.vendor = inputId.vendor;
1302 identifier.version = inputId.version;
1303
1304 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001305 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
1306 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001307 } else {
1308 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001309 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001310 }
1311
1312 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001313 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
1314 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001315 } else {
1316 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001317 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001318 }
1319
1320 // Fill in the descriptor.
1321 assignDescriptorLocked(identifier);
1322
Michael Wrightd02c5b62014-02-10 15:10:22 -08001323 // Allocate device. (The device object takes ownership of the fd at this point.)
1324 int32_t deviceId = mNextDeviceId++;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001325 Device* device = new Device(fd, deviceId, devicePath, identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001326
Chris Yedb924702020-07-14 10:34:06 -07001327 ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001328 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001329 " vendor %04x\n"
1330 " product %04x\n"
1331 " version %04x\n",
1332 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001333 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
1334 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
1335 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
1336 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001337 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
1338 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001339
1340 // Load the configuration file for the device.
1341 loadConfigurationLocked(device);
1342
1343 // Figure out the kinds of events the device reports.
1344 ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(device->keyBitmask)), device->keyBitmask);
1345 ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(device->absBitmask)), device->absBitmask);
1346 ioctl(fd, EVIOCGBIT(EV_REL, sizeof(device->relBitmask)), device->relBitmask);
1347 ioctl(fd, EVIOCGBIT(EV_SW, sizeof(device->swBitmask)), device->swBitmask);
1348 ioctl(fd, EVIOCGBIT(EV_LED, sizeof(device->ledBitmask)), device->ledBitmask);
1349 ioctl(fd, EVIOCGBIT(EV_FF, sizeof(device->ffBitmask)), device->ffBitmask);
1350 ioctl(fd, EVIOCGPROP(sizeof(device->propBitmask)), device->propBitmask);
1351
1352 // See if this is a keyboard. Ignore everything in the button range except for
1353 // joystick and gamepad buttons which are handled like keyboards for the most part.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001354 bool haveKeyboardKeys =
1355 containsNonZeroByte(device->keyBitmask, 0, sizeof_bit_array(BTN_MISC)) ||
Siarhei Vishniakoua0d2b802020-05-13 14:00:31 -07001356 containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_WHEEL),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001357 sizeof_bit_array(KEY_MAX + 1));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001358 bool haveGamepadButtons = containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_MISC),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001359 sizeof_bit_array(BTN_MOUSE)) ||
1360 containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_JOYSTICK),
1361 sizeof_bit_array(BTN_DIGI));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001362 if (haveKeyboardKeys || haveGamepadButtons) {
1363 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1364 }
1365
1366 // See if this is a cursor device such as a trackball or mouse.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001367 if (test_bit(BTN_MOUSE, device->keyBitmask) && test_bit(REL_X, device->relBitmask) &&
1368 test_bit(REL_Y, device->relBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001369 device->classes |= INPUT_DEVICE_CLASS_CURSOR;
1370 }
1371
Prashant Malani1941ff52015-08-11 18:29:28 -07001372 // See if this is a rotary encoder type device.
1373 String8 deviceType = String8();
1374 if (device->configuration &&
1375 device->configuration->tryGetProperty(String8("device.type"), deviceType)) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001376 if (!deviceType.compare(String8("rotaryEncoder"))) {
1377 device->classes |= INPUT_DEVICE_CLASS_ROTARY_ENCODER;
1378 }
Prashant Malani1941ff52015-08-11 18:29:28 -07001379 }
1380
Michael Wrightd02c5b62014-02-10 15:10:22 -08001381 // See if this is a touch pad.
1382 // Is this a new modern multi-touch driver?
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001383 if (test_bit(ABS_MT_POSITION_X, device->absBitmask) &&
1384 test_bit(ABS_MT_POSITION_Y, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001385 // Some joysticks such as the PS3 controller report axes that conflict
1386 // with the ABS_MT range. Try to confirm that the device really is
1387 // a touch screen.
1388 if (test_bit(BTN_TOUCH, device->keyBitmask) || !haveGamepadButtons) {
1389 device->classes |= INPUT_DEVICE_CLASS_TOUCH | INPUT_DEVICE_CLASS_TOUCH_MT;
1390 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001391 // Is this an old style single-touch driver?
1392 } else if (test_bit(BTN_TOUCH, device->keyBitmask) && test_bit(ABS_X, device->absBitmask) &&
1393 test_bit(ABS_Y, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001394 device->classes |= INPUT_DEVICE_CLASS_TOUCH;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001395 // Is this a BT stylus?
Michael Wright842500e2015-03-13 17:32:02 -07001396 } else if ((test_bit(ABS_PRESSURE, device->absBitmask) ||
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001397 test_bit(BTN_TOUCH, device->keyBitmask)) &&
1398 !test_bit(ABS_X, device->absBitmask) && !test_bit(ABS_Y, device->absBitmask)) {
Michael Wright842500e2015-03-13 17:32:02 -07001399 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
1400 // Keyboard will try to claim some of the buttons but we really want to reserve those so we
1401 // can fuse it with the touch screen data, so just take them back. Note this means an
1402 // external stylus cannot also be a keyboard device.
1403 device->classes &= ~INPUT_DEVICE_CLASS_KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001404 }
1405
1406 // See if this device is a joystick.
1407 // Assumes that joysticks always have gamepad buttons in order to distinguish them
1408 // from other devices such as accelerometers that also have absolute axes.
1409 if (haveGamepadButtons) {
1410 uint32_t assumedClasses = device->classes | INPUT_DEVICE_CLASS_JOYSTICK;
1411 for (int i = 0; i <= ABS_MAX; i++) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001412 if (test_bit(i, device->absBitmask) &&
1413 (getAbsAxisUsage(i, assumedClasses) & INPUT_DEVICE_CLASS_JOYSTICK)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001414 device->classes = assumedClasses;
1415 break;
1416 }
1417 }
1418 }
1419
1420 // Check whether this device has switches.
1421 for (int i = 0; i <= SW_MAX; i++) {
1422 if (test_bit(i, device->swBitmask)) {
1423 device->classes |= INPUT_DEVICE_CLASS_SWITCH;
1424 break;
1425 }
1426 }
1427
1428 // Check whether this device supports the vibrator.
1429 if (test_bit(FF_RUMBLE, device->ffBitmask)) {
1430 device->classes |= INPUT_DEVICE_CLASS_VIBRATOR;
1431 }
1432
1433 // Configure virtual keys.
1434 if ((device->classes & INPUT_DEVICE_CLASS_TOUCH)) {
1435 // Load the virtual keys for the touch screen, if any.
1436 // We do this now so that we can make sure to load the keymap if necessary.
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001437 bool success = loadVirtualKeyMapLocked(device);
1438 if (success) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001439 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1440 }
1441 }
1442
1443 // Load the key map.
1444 // We need to do this for joysticks too because the key layout may specify axes.
1445 status_t keyMapStatus = NAME_NOT_FOUND;
1446 if (device->classes & (INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_JOYSTICK)) {
1447 // Load the keymap for the device.
1448 keyMapStatus = loadKeyMapLocked(device);
1449 }
1450
1451 // Configure the keyboard, gamepad or virtual keyboard.
1452 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1453 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001454 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
1455 isEligibleBuiltInKeyboard(device->identifier, device->configuration, &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001456 mBuiltInKeyboardId = device->id;
1457 }
1458
1459 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
1460 if (hasKeycodeLocked(device, AKEYCODE_Q)) {
1461 device->classes |= INPUT_DEVICE_CLASS_ALPHAKEY;
1462 }
1463
1464 // See if this device has a DPAD.
1465 if (hasKeycodeLocked(device, AKEYCODE_DPAD_UP) &&
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001466 hasKeycodeLocked(device, AKEYCODE_DPAD_DOWN) &&
1467 hasKeycodeLocked(device, AKEYCODE_DPAD_LEFT) &&
1468 hasKeycodeLocked(device, AKEYCODE_DPAD_RIGHT) &&
1469 hasKeycodeLocked(device, AKEYCODE_DPAD_CENTER)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001470 device->classes |= INPUT_DEVICE_CLASS_DPAD;
1471 }
1472
1473 // See if this device has a gamepad.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001474 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES) / sizeof(GAMEPAD_KEYCODES[0]); i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001475 if (hasKeycodeLocked(device, GAMEPAD_KEYCODES[i])) {
1476 device->classes |= INPUT_DEVICE_CLASS_GAMEPAD;
1477 break;
1478 }
1479 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480 }
1481
1482 // If the device isn't recognized as something we handle, don't monitor it.
1483 if (device->classes == 0) {
Chris Yedb924702020-07-14 10:34:06 -07001484 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001485 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001486 delete device;
1487 return -1;
1488 }
1489
Tim Kilbourn063ff532015-04-08 10:26:18 -07001490 // Determine whether the device has a mic.
1491 if (deviceHasMicLocked(device)) {
1492 device->classes |= INPUT_DEVICE_CLASS_MIC;
1493 }
1494
Michael Wrightd02c5b62014-02-10 15:10:22 -08001495 // Determine whether the device is external or internal.
1496 if (isExternalDeviceLocked(device)) {
1497 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL;
1498 }
1499
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001500 if (device->classes & (INPUT_DEVICE_CLASS_JOYSTICK | INPUT_DEVICE_CLASS_DPAD) &&
1501 device->classes & INPUT_DEVICE_CLASS_GAMEPAD) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001502 device->controllerNumber = getNextControllerNumberLocked(device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001503 setLedForControllerLocked(device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001504 }
1505
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001506 // Find a matching video device by comparing device names
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001507 // This should be done before registerDeviceForEpollLocked, so that both fds are added to epoll
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001508 for (std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
1509 if (device->identifier.name == videoDevice->getName()) {
1510 device->videoDevice = std::move(videoDevice);
1511 break;
1512 }
1513 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001514 mUnattachedVideoDevices
1515 .erase(std::remove_if(mUnattachedVideoDevices.begin(), mUnattachedVideoDevices.end(),
1516 [](const std::unique_ptr<TouchVideoDevice>& videoDevice) {
1517 return videoDevice == nullptr;
1518 }),
1519 mUnattachedVideoDevices.end());
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001520
1521 if (registerDeviceForEpollLocked(device) != OK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001522 delete device;
1523 return -1;
1524 }
1525
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001526 configureFd(device);
1527
1528 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=0x%x, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001529 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Chris Yedb924702020-07-14 10:34:06 -07001530 deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(), device->classes,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001531 device->configurationFile.c_str(), device->keyMap.keyLayoutFile.c_str(),
1532 device->keyMap.keyCharacterMapFile.c_str(), toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001533
1534 addDeviceLocked(device);
1535 return OK;
1536}
1537
1538void EventHub::configureFd(Device* device) {
1539 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
1540 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1541 // Disable kernel key repeat since we handle it ourselves
1542 unsigned int repeatRate[] = {0, 0};
1543 if (ioctl(device->fd, EVIOCSREP, repeatRate)) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001544 ALOGW("Unable to disable kernel key repeat for %s: %s", device->path.c_str(),
1545 strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001546 }
1547 }
1548
Michael Wrightd02c5b62014-02-10 15:10:22 -08001549 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
1550 // associated with input events. This is important because the input system
1551 // uses the timestamps extensively and assumes they were recorded using the monotonic
1552 // clock.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001553 int clockId = CLOCK_MONOTONIC;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001554 bool usingClockIoctl = !ioctl(device->fd, EVIOCSCLOCKID, &clockId);
Atif Niyaz4180aa42019-05-10 16:27:48 -07001555 ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001556}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001557
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001558void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
1559 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
1560 if (!videoDevice) {
1561 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
1562 return;
1563 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001564 // Transfer ownership of this video device to a matching input device
1565 for (size_t i = 0; i < mDevices.size(); i++) {
1566 Device* device = mDevices.valueAt(i);
1567 if (videoDevice->getName() == device->identifier.name) {
1568 device->videoDevice = std::move(videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001569 if (device->enabled) {
1570 registerVideoDeviceForEpollLocked(*device->videoDevice);
1571 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001572 return;
1573 }
1574 }
1575
1576 // Couldn't find a matching input device, so just add it to a temporary holding queue.
1577 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001578 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001579 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001580 mUnattachedVideoDevices.push_back(std::move(videoDevice));
1581}
1582
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001583bool EventHub::isDeviceEnabled(int32_t deviceId) {
1584 AutoMutex _l(mLock);
1585 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001586 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001587 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1588 return false;
1589 }
1590 return device->enabled;
1591}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001592
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001593status_t EventHub::enableDevice(int32_t deviceId) {
1594 AutoMutex _l(mLock);
1595 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001596 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001597 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1598 return BAD_VALUE;
1599 }
1600 if (device->enabled) {
1601 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
1602 return OK;
1603 }
1604 status_t result = device->enable();
1605 if (result != OK) {
1606 ALOGE("Failed to enable device %" PRId32, deviceId);
1607 return result;
1608 }
1609
1610 configureFd(device);
1611
1612 return registerDeviceForEpollLocked(device);
1613}
1614
1615status_t EventHub::disableDevice(int32_t deviceId) {
1616 AutoMutex _l(mLock);
1617 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001618 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001619 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1620 return BAD_VALUE;
1621 }
1622 if (!device->enabled) {
1623 ALOGW("Duplicate call to %s, input device already disabled", __func__);
1624 return OK;
1625 }
1626 unregisterDeviceFromEpollLocked(device);
1627 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001628}
1629
1630void EventHub::createVirtualKeyboardLocked() {
1631 InputDeviceIdentifier identifier;
1632 identifier.name = "Virtual";
1633 identifier.uniqueId = "<virtual>";
1634 assignDescriptorLocked(identifier);
1635
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001636 Device* device =
1637 new Device(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>", identifier);
1638 device->classes = INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_ALPHAKEY |
1639 INPUT_DEVICE_CLASS_DPAD | INPUT_DEVICE_CLASS_VIRTUAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001640 loadKeyMapLocked(device);
1641 addDeviceLocked(device);
1642}
1643
1644void EventHub::addDeviceLocked(Device* device) {
1645 mDevices.add(device->id, device);
1646 device->next = mOpeningDevices;
1647 mOpeningDevices = device;
1648}
1649
1650void EventHub::loadConfigurationLocked(Device* device) {
1651 device->configurationFile = getInputDeviceConfigurationFilePathByDeviceIdentifier(
1652 device->identifier, INPUT_DEVICE_CONFIGURATION_FILE_TYPE_CONFIGURATION);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001653 if (device->configurationFile.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001654 ALOGD("No input device configuration file found for device '%s'.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001655 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001656 } else {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001657 status_t status = PropertyMap::load(String8(device->configurationFile.c_str()),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001658 &device->configuration);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001659 if (status) {
1660 ALOGE("Error loading input device configuration file for device '%s'. "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001661 "Using default configuration.",
1662 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001663 }
1664 }
1665}
1666
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001667bool EventHub::loadVirtualKeyMapLocked(Device* device) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001668 // The virtual key map is supplied by the kernel as a system board property file.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001669 std::string path;
1670 path += "/sys/board_properties/virtualkeys.";
Siarhei Vishniakoub45635c2019-02-20 19:22:09 -06001671 path += device->identifier.getCanonicalName();
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001672 if (access(path.c_str(), R_OK)) {
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001673 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001674 }
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001675 device->virtualKeyMap = VirtualKeyMap::load(path);
1676 return device->virtualKeyMap != nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001677}
1678
1679status_t EventHub::loadKeyMapLocked(Device* device) {
1680 return device->keyMap.load(device->identifier, device->configuration);
1681}
1682
1683bool EventHub::isExternalDeviceLocked(Device* device) {
1684 if (device->configuration) {
1685 bool value;
1686 if (device->configuration->tryGetProperty(String8("device.internal"), value)) {
1687 return !value;
1688 }
1689 }
1690 return device->identifier.bus == BUS_USB || device->identifier.bus == BUS_BLUETOOTH;
1691}
1692
Tim Kilbourn063ff532015-04-08 10:26:18 -07001693bool EventHub::deviceHasMicLocked(Device* device) {
1694 if (device->configuration) {
1695 bool value;
1696 if (device->configuration->tryGetProperty(String8("audio.mic"), value)) {
1697 return value;
1698 }
1699 }
1700 return false;
1701}
1702
Michael Wrightd02c5b62014-02-10 15:10:22 -08001703int32_t EventHub::getNextControllerNumberLocked(Device* device) {
1704 if (mControllerNumbers.isFull()) {
1705 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001706 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001707 return 0;
1708 }
1709 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
1710 // one
1711 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
1712}
1713
1714void EventHub::releaseControllerNumberLocked(Device* device) {
1715 int32_t num = device->controllerNumber;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001716 device->controllerNumber = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001717 if (num == 0) {
1718 return;
1719 }
1720 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
1721}
1722
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001723void EventHub::setLedForControllerLocked(Device* device) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001724 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
1725 setLedStateLocked(device, ALED_CONTROLLER_1 + i, device->controllerNumber == i + 1);
1726 }
1727}
1728
1729bool EventHub::hasKeycodeLocked(Device* device, int keycode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001730 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001731 return false;
1732 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001733
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001734 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001735 device->keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes);
1736 const size_t N = scanCodes.size();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001737 for (size_t i = 0; i < N && i <= KEY_MAX; i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001738 int32_t sc = scanCodes[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001739 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, device->keyBitmask)) {
1740 return true;
1741 }
1742 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001743
Michael Wrightd02c5b62014-02-10 15:10:22 -08001744 return false;
1745}
1746
1747status_t EventHub::mapLed(Device* device, int32_t led, int32_t* outScanCode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001748 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001749 return NAME_NOT_FOUND;
1750 }
1751
1752 int32_t scanCode;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001753 if (device->keyMap.keyLayoutMap->findScanCodeForLed(led, &scanCode) != NAME_NOT_FOUND) {
1754 if (scanCode >= 0 && scanCode <= LED_MAX && test_bit(scanCode, device->ledBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001755 *outScanCode = scanCode;
1756 return NO_ERROR;
1757 }
1758 }
1759 return NAME_NOT_FOUND;
1760}
1761
Chris Yedb924702020-07-14 10:34:06 -07001762void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001763 Device* device = getDeviceByPathLocked(devicePath);
1764 if (device) {
1765 closeDeviceLocked(device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001766 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001767 }
Chris Yedb924702020-07-14 10:34:06 -07001768 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001769}
1770
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001771/**
1772 * Find the video device by filename, and close it.
1773 * The video device is closed by path during an inotify event, where we don't have the
1774 * additional context about the video device fd, or the associated input device.
1775 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001776void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001777 // A video device may be owned by an existing input device, or it may be stored in
1778 // the mUnattachedVideoDevices queue. Check both locations.
1779 for (size_t i = 0; i < mDevices.size(); i++) {
1780 Device* device = mDevices.valueAt(i);
1781 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001782 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001783 device->videoDevice = nullptr;
1784 return;
1785 }
1786 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001787 mUnattachedVideoDevices
1788 .erase(std::remove_if(mUnattachedVideoDevices.begin(), mUnattachedVideoDevices.end(),
1789 [&devicePath](
1790 const std::unique_ptr<TouchVideoDevice>& videoDevice) {
1791 return videoDevice->getPath() == devicePath;
1792 }),
1793 mUnattachedVideoDevices.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001794}
1795
1796void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001797 mUnattachedVideoDevices.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001798 while (mDevices.size() > 0) {
1799 closeDeviceLocked(mDevices.valueAt(mDevices.size() - 1));
1800 }
1801}
1802
1803void EventHub::closeDeviceLocked(Device* device) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001804 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=0x%x", device->path.c_str(),
1805 device->identifier.name.c_str(), device->id, device->fd, device->classes);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001806
1807 if (device->id == mBuiltInKeyboardId) {
1808 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001809 device->path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001810 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
1811 }
1812
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001813 unregisterDeviceFromEpollLocked(device);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001814 if (device->videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001815 // This must be done after the video device is removed from epoll
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001816 mUnattachedVideoDevices.push_back(std::move(device->videoDevice));
1817 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001818
1819 releaseControllerNumberLocked(device);
1820
1821 mDevices.removeItem(device->id);
1822 device->close();
1823
1824 // Unlink for opening devices list if it is present.
Yi Kong9b14ac62018-07-17 13:48:38 -07001825 Device* pred = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001826 bool found = false;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001827 for (Device* entry = mOpeningDevices; entry != nullptr;) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001828 if (entry == device) {
1829 found = true;
1830 break;
1831 }
1832 pred = entry;
1833 entry = entry->next;
1834 }
1835 if (found) {
1836 // Unlink the device from the opening devices list then delete it.
1837 // We don't need to tell the client that the device was closed because
1838 // it does not even know it was opened in the first place.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001839 ALOGI("Device %s was immediately closed after opening.", device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001840 if (pred) {
1841 pred->next = device->next;
1842 } else {
1843 mOpeningDevices = device->next;
1844 }
1845 delete device;
1846 } else {
1847 // Link into closing devices list.
1848 // The device will be deleted later after we have informed the client.
1849 device->next = mClosingDevices;
1850 mClosingDevices = device;
1851 }
1852}
1853
1854status_t EventHub::readNotifyLocked() {
1855 int res;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001856 char event_buf[512];
1857 int event_size;
1858 int event_pos = 0;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001859 struct inotify_event* event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001860
1861 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
1862 res = read(mINotifyFd, event_buf, sizeof(event_buf));
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001863 if (res < (int)sizeof(*event)) {
1864 if (errno == EINTR) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001865 ALOGW("could not get event, %s\n", strerror(errno));
1866 return -1;
1867 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001868
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001869 while (res >= (int)sizeof(*event)) {
1870 event = (struct inotify_event*)(event_buf + event_pos);
1871 if (event->len) {
Usama Arifd9a25ed2021-06-03 16:44:09 +01001872 if (event->wd == mDeviceInputWd) {
1873 std::string filename = std::string(DEVICE_INPUT_PATH) + "/" + event->name;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001874 if (event->mask & IN_CREATE) {
Chris Yedb924702020-07-14 10:34:06 -07001875 openDeviceLocked(filename);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001876 } else {
1877 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
Chris Yedb924702020-07-14 10:34:06 -07001878 closeDeviceByPathLocked(filename);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001879 }
Usama Arifd9a25ed2021-06-03 16:44:09 +01001880 } else if (event->wd == mDeviceWd) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001881 if (isV4lTouchNode(event->name)) {
Usama Arifd9a25ed2021-06-03 16:44:09 +01001882 std::string filename = std::string(DEVICE_PATH) + "/" + event->name;
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001883 if (event->mask & IN_CREATE) {
1884 openVideoDeviceLocked(filename);
1885 } else {
1886 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
1887 closeVideoDeviceByPathLocked(filename);
1888 }
Usama Arifd9a25ed2021-06-03 16:44:09 +01001889 } else if (strcmp(event->name, "input") == 0 && event->mask & IN_CREATE ) {
1890 addDeviceInputInotify();
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001891 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001892 } else {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001893 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event->wd);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001894 }
1895 }
1896 event_size = sizeof(*event) + event->len;
1897 res -= event_size;
1898 event_pos += event_size;
1899 }
1900 return 0;
1901}
1902
Chris Yedb924702020-07-14 10:34:06 -07001903status_t EventHub::scanDirLocked(const std::string& dirname) {
1904 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
1905 openDeviceLocked(entry.path());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001906 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001907 return 0;
1908}
1909
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001910/**
1911 * Look for all dirname/v4l-touch* devices, and open them.
1912 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001913status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Chris Yedb924702020-07-14 10:34:06 -07001914 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
1915 if (isV4lTouchNode(entry.path())) {
1916 ALOGI("Found touch video device %s", entry.path().c_str());
1917 openVideoDeviceLocked(entry.path());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001918 }
1919 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001920 return OK;
1921}
1922
Michael Wrightd02c5b62014-02-10 15:10:22 -08001923void EventHub::requestReopenDevices() {
1924 ALOGV("requestReopenDevices() called");
1925
1926 AutoMutex _l(mLock);
1927 mNeedToReopenDevices = true;
1928}
1929
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001930void EventHub::dump(std::string& dump) {
1931 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001932
1933 { // acquire lock
1934 AutoMutex _l(mLock);
1935
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001936 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001937
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001938 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001939
1940 for (size_t i = 0; i < mDevices.size(); i++) {
1941 const Device* device = mDevices.valueAt(i);
1942 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001943 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001944 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001945 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001946 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001947 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001948 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001949 dump += StringPrintf(INDENT3 "Classes: 0x%08x\n", device->classes);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001950 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001951 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001952 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
1953 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001954 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001955 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001956 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001957 "product=0x%04x, version=0x%04x\n",
1958 device->identifier.bus, device->identifier.vendor,
1959 device->identifier.product, device->identifier.version);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001960 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001961 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001962 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001963 device->keyMap.keyCharacterMapFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001964 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001965 device->configurationFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001966 dump += StringPrintf(INDENT3 "HaveKeyboardLayoutOverlay: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001967 toString(device->overlayKeyMap != nullptr));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001968 dump += INDENT3 "VideoDevice: ";
1969 if (device->videoDevice) {
1970 dump += device->videoDevice->dump() + "\n";
1971 } else {
1972 dump += "<none>\n";
1973 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001974 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001975
1976 dump += INDENT "Unattached video devices:\n";
1977 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
1978 dump += INDENT2 + videoDevice->dump() + "\n";
1979 }
1980 if (mUnattachedVideoDevices.empty()) {
1981 dump += INDENT2 "<none>\n";
1982 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001983 } // release lock
1984}
1985
1986void EventHub::monitor() {
1987 // Acquire and release the lock to ensure that the event hub has not deadlocked.
1988 mLock.lock();
1989 mLock.unlock();
1990}
1991
Michael Wrightd02c5b62014-02-10 15:10:22 -08001992}; // namespace android