blob: fe428f101f6879d963ba4ab419f2855c7f2dae99 [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 Ye8594e192020-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>
Michael Wrightd02c5b62014-02-10 15:10:22 -080046
Chris Ye8594e192020-07-14 10:34:06 -070047#include <filesystem>
48
49#include "EventHub.h"
Michael Wrightd02c5b62014-02-10 15:10:22 -080050
Michael Wrightd02c5b62014-02-10 15:10:22 -080051#define INDENT " "
52#define INDENT2 " "
53#define INDENT3 " "
54
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080055using android::base::StringPrintf;
56
Michael Wrightd02c5b62014-02-10 15:10:22 -080057namespace android {
58
Siarhei Vishniakou25920312018-12-12 15:24:44 -080059static constexpr bool DEBUG = false;
60
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070061static const char* DEVICE_PATH = "/dev/input";
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080062// v4l2 devices go directly into /dev
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070063static const char* VIDEO_DEVICE_PATH = "/dev";
Michael Wrightd02c5b62014-02-10 15:10:22 -080064
Michael Wrightd02c5b62014-02-10 15:10:22 -080065static inline const char* toString(bool value) {
66 return value ? "true" : "false";
67}
68
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010069static std::string sha1(const std::string& in) {
Dan Albert677d87e2014-06-16 17:31:28 -070070 SHA_CTX ctx;
71 SHA1_Init(&ctx);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010072 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
Dan Albert677d87e2014-06-16 17:31:28 -070073 u_char digest[SHA_DIGEST_LENGTH];
74 SHA1_Final(digest, &ctx);
Michael Wrightd02c5b62014-02-10 15:10:22 -080075
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010076 std::string out;
Dan Albert677d87e2014-06-16 17:31:28 -070077 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010078 out += StringPrintf("%02x", digest[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -080079 }
80 return out;
81}
82
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080083/**
84 * Return true if name matches "v4l-touch*"
85 */
Chris Ye8594e192020-07-14 10:34:06 -070086static bool isV4lTouchNode(std::string name) {
87 return name.find("v4l-touch") != std::string::npos;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080088}
89
Philip Quinn39b81682019-01-09 22:20:39 -080090/**
91 * Returns true if V4L devices should be scanned.
92 *
93 * The system property ro.input.video_enabled can be used to control whether
94 * EventHub scans and opens V4L devices. As V4L does not support multiple
95 * clients, EventHub effectively blocks access to these devices when it opens
Siarhei Vishniakou29f88492019-04-05 14:11:43 -070096 * them.
97 *
98 * Setting this to "false" would prevent any video devices from being discovered and
99 * associated with input devices.
100 *
101 * This property can be used as follows:
102 * 1. To turn off features that are dependent on video device presence.
103 * 2. During testing and development, to allow other clients to read video devices
104 * directly from /dev.
Philip Quinn39b81682019-01-09 22:20:39 -0800105 */
106static bool isV4lScanningEnabled() {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700107 return property_get_bool("ro.input.video_enabled", true /* default_value */);
Philip Quinn39b81682019-01-09 22:20:39 -0800108}
109
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800110static nsecs_t processEventTimestamp(const struct input_event& event) {
111 // Use the time specified in the event instead of the current time
112 // so that downstream code can get more accurate estimates of
113 // event dispatch latency from the time the event is enqueued onto
114 // the evdev client buffer.
115 //
116 // The event's timestamp fortuitously uses the same monotonic clock
117 // time base as the rest of Android. The kernel event device driver
118 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
119 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
120 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
121 // system call that also queries ktime_get_ts().
122
123 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.time.tv_sec) +
124 microseconds_to_nanoseconds(event.time.tv_usec);
125 return inputEventTime;
126}
127
Michael Wrightd02c5b62014-02-10 15:10:22 -0800128// --- Global Functions ---
129
130uint32_t getAbsAxisUsage(int32_t axis, uint32_t deviceClasses) {
131 // Touch devices get dibs on touch-related axes.
132 if (deviceClasses & INPUT_DEVICE_CLASS_TOUCH) {
133 switch (axis) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700134 case ABS_X:
135 case ABS_Y:
136 case ABS_PRESSURE:
137 case ABS_TOOL_WIDTH:
138 case ABS_DISTANCE:
139 case ABS_TILT_X:
140 case ABS_TILT_Y:
141 case ABS_MT_SLOT:
142 case ABS_MT_TOUCH_MAJOR:
143 case ABS_MT_TOUCH_MINOR:
144 case ABS_MT_WIDTH_MAJOR:
145 case ABS_MT_WIDTH_MINOR:
146 case ABS_MT_ORIENTATION:
147 case ABS_MT_POSITION_X:
148 case ABS_MT_POSITION_Y:
149 case ABS_MT_TOOL_TYPE:
150 case ABS_MT_BLOB_ID:
151 case ABS_MT_TRACKING_ID:
152 case ABS_MT_PRESSURE:
153 case ABS_MT_DISTANCE:
154 return INPUT_DEVICE_CLASS_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800155 }
156 }
157
Michael Wright842500e2015-03-13 17:32:02 -0700158 // External stylus gets the pressure axis
159 if (deviceClasses & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
160 if (axis == ABS_PRESSURE) {
161 return INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
162 }
163 }
164
Michael Wrightd02c5b62014-02-10 15:10:22 -0800165 // Joystick devices get the rest.
166 return deviceClasses & INPUT_DEVICE_CLASS_JOYSTICK;
167}
168
169// --- EventHub::Device ---
170
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100171EventHub::Device::Device(int fd, int32_t id, const std::string& path,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700172 const InputDeviceIdentifier& identifier)
173 : next(nullptr),
174 fd(fd),
175 id(id),
176 path(path),
177 identifier(identifier),
178 classes(0),
179 configuration(nullptr),
180 virtualKeyMap(nullptr),
181 ffEffectPlaying(false),
182 ffEffectId(-1),
183 controllerNumber(0),
184 enabled(true),
Chris Ye66fbac32020-07-06 20:36:43 -0700185 isVirtual(fd < 0) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800186
187EventHub::Device::~Device() {
188 close();
189 delete configuration;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800190}
191
192void EventHub::Device::close() {
193 if (fd >= 0) {
194 ::close(fd);
195 fd = -1;
196 }
197}
198
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700199status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100200 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700201 if (fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100202 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700203 return -errno;
204 }
205 enabled = true;
206 return OK;
207}
208
209status_t EventHub::Device::disable() {
210 close();
211 enabled = false;
212 return OK;
213}
214
215bool EventHub::Device::hasValidFd() {
216 return !isVirtual && enabled;
217}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800218
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100219/**
220 * Get the capabilities for the current process.
221 * Crashes the system if unable to create / check / destroy the capabilities object.
222 */
223class Capabilities final {
224public:
225 explicit Capabilities() {
226 mCaps = cap_get_proc();
227 LOG_ALWAYS_FATAL_IF(mCaps == nullptr, "Could not get capabilities of the current process");
228 }
229
230 /**
231 * Check whether the current process has a specific capability
232 * in the set of effective capabilities.
233 * Return CAP_SET if the process has the requested capability
234 * Return CAP_CLEAR otherwise.
235 */
236 cap_flag_value_t checkEffectiveCapability(cap_value_t capability) {
237 cap_flag_value_t value;
238 const int result = cap_get_flag(mCaps, capability, CAP_EFFECTIVE, &value);
239 LOG_ALWAYS_FATAL_IF(result == -1, "Could not obtain the requested capability");
240 return value;
241 }
242
243 ~Capabilities() {
244 const int result = cap_free(mCaps);
245 LOG_ALWAYS_FATAL_IF(result == -1, "Could not release the capabilities structure");
246 }
247
248private:
249 cap_t mCaps;
250};
251
252static void ensureProcessCanBlockSuspend() {
253 Capabilities capabilities;
254 const bool canBlockSuspend =
255 capabilities.checkEffectiveCapability(CAP_BLOCK_SUSPEND) == CAP_SET;
256 LOG_ALWAYS_FATAL_IF(!canBlockSuspend,
257 "Input must be able to block suspend to properly process events");
258}
259
Michael Wrightd02c5b62014-02-10 15:10:22 -0800260// --- EventHub ---
261
Michael Wrightd02c5b62014-02-10 15:10:22 -0800262const int EventHub::EPOLL_MAX_EVENTS;
263
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700264EventHub::EventHub(void)
265 : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
266 mNextDeviceId(1),
267 mControllerNumbers(),
268 mOpeningDevices(nullptr),
269 mClosingDevices(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800270 mNeedToSendFinishedDeviceScan(false),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700271 mNeedToReopenDevices(false),
272 mNeedToScanDevices(true),
273 mPendingEventCount(0),
274 mPendingEventIndex(0),
275 mPendingINotify(false) {
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100276 ensureProcessCanBlockSuspend();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800277
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800278 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800279 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800280
281 mINotifyFd = inotify_init();
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800282 mInputWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700283 LOG_ALWAYS_FATAL_IF(mInputWd < 0, "Could not register INotify for %s: %s", DEVICE_PATH,
284 strerror(errno));
Philip Quinn39b81682019-01-09 22:20:39 -0800285 if (isV4lScanningEnabled()) {
286 mVideoWd = inotify_add_watch(mINotifyFd, VIDEO_DEVICE_PATH, IN_DELETE | IN_CREATE);
287 LOG_ALWAYS_FATAL_IF(mVideoWd < 0, "Could not register INotify for %s: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700288 VIDEO_DEVICE_PATH, strerror(errno));
Philip Quinn39b81682019-01-09 22:20:39 -0800289 } else {
290 mVideoWd = -1;
291 ALOGI("Video device scanning disabled");
292 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800293
Siarhei Vishniakou2d0e9482019-09-24 12:52:47 +0100294 struct epoll_event eventItem = {};
295 eventItem.events = EPOLLIN | EPOLLWAKEUP;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700296 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800297 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800298 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
299
300 int wakeFds[2];
301 result = pipe(wakeFds);
302 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
303
304 mWakeReadPipeFd = wakeFds[0];
305 mWakeWritePipeFd = wakeFds[1];
306
307 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
308 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700309 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800310
311 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
312 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700313 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800314
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700315 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800316 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
317 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700318 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800319}
320
321EventHub::~EventHub(void) {
322 closeAllDevicesLocked();
323
324 while (mClosingDevices) {
325 Device* device = mClosingDevices;
326 mClosingDevices = device->next;
327 delete device;
328 }
329
330 ::close(mEpollFd);
331 ::close(mINotifyFd);
332 ::close(mWakeReadPipeFd);
333 ::close(mWakeWritePipeFd);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800334}
335
336InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
337 AutoMutex _l(mLock);
338 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700339 if (device == nullptr) return InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800340 return device->identifier;
341}
342
343uint32_t EventHub::getDeviceClasses(int32_t deviceId) const {
344 AutoMutex _l(mLock);
345 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700346 if (device == nullptr) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800347 return device->classes;
348}
349
350int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
351 AutoMutex _l(mLock);
352 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700353 if (device == nullptr) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800354 return device->controllerNumber;
355}
356
357void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
358 AutoMutex _l(mLock);
359 Device* device = getDeviceLocked(deviceId);
360 if (device && device->configuration) {
361 *outConfiguration = *device->configuration;
362 } else {
363 outConfiguration->clear();
364 }
365}
366
367status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700368 RawAbsoluteAxisInfo* outAxisInfo) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800369 outAxisInfo->clear();
370
371 if (axis >= 0 && axis <= ABS_MAX) {
372 AutoMutex _l(mLock);
373
374 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700375 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800376 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700377 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
378 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
379 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800380 return -errno;
381 }
382
383 if (info.minimum != info.maximum) {
384 outAxisInfo->valid = true;
385 outAxisInfo->minValue = info.minimum;
386 outAxisInfo->maxValue = info.maximum;
387 outAxisInfo->flat = info.flat;
388 outAxisInfo->fuzz = info.fuzz;
389 outAxisInfo->resolution = info.resolution;
390 }
391 return OK;
392 }
393 }
394 return -1;
395}
396
397bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
398 if (axis >= 0 && axis <= REL_MAX) {
399 AutoMutex _l(mLock);
400
401 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700402 return device != nullptr ? device->relBitmask.test(axis) : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800403 }
404 return false;
405}
406
407bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
408 if (property >= 0 && property <= INPUT_PROP_MAX) {
409 AutoMutex _l(mLock);
410
411 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700412 return device != nullptr ? device->propBitmask.test(property) : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800413 }
414 return false;
415}
416
417int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
418 if (scanCode >= 0 && scanCode <= KEY_MAX) {
419 AutoMutex _l(mLock);
420
421 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700422 if (device != nullptr && device->hasValidFd() && device->keyBitmask.test(scanCode)) {
423 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
424 return device->keyState.test(scanCode) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800425 }
426 }
427 }
428 return AKEY_STATE_UNKNOWN;
429}
430
431int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
432 AutoMutex _l(mLock);
433
434 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700435 if (device != nullptr && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800436 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800437 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode, &scanCodes);
438 if (scanCodes.size() != 0) {
Chris Ye66fbac32020-07-06 20:36:43 -0700439 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800440 for (size_t i = 0; i < scanCodes.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800441 int32_t sc = scanCodes[i];
Chris Ye66fbac32020-07-06 20:36:43 -0700442 if (sc >= 0 && sc <= KEY_MAX && device->keyState.test(sc)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800443 return AKEY_STATE_DOWN;
444 }
445 }
446 return AKEY_STATE_UP;
447 }
448 }
449 }
450 return AKEY_STATE_UNKNOWN;
451}
452
453int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
454 if (sw >= 0 && sw <= SW_MAX) {
455 AutoMutex _l(mLock);
456
457 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700458 if (device != nullptr && device->hasValidFd() && device->swBitmask.test(sw)) {
459 if (device->readDeviceBitMask(EVIOCGSW(0), device->swState) >= 0) {
460 return device->swState.test(sw) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800461 }
462 }
463 }
464 return AKEY_STATE_UNKNOWN;
465}
466
467status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
468 *outValue = 0;
469
470 if (axis >= 0 && axis <= ABS_MAX) {
471 AutoMutex _l(mLock);
472
473 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700474 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800475 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700476 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
477 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
478 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800479 return -errno;
480 }
481
482 *outValue = info.value;
483 return OK;
484 }
485 }
486 return -1;
487}
488
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700489bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes, const int32_t* keyCodes,
490 uint8_t* outFlags) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800491 AutoMutex _l(mLock);
492
493 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700494 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800495 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800496 for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) {
497 scanCodes.clear();
498
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700499 status_t err = device->keyMap.keyLayoutMap->findScanCodesForKey(keyCodes[codeIndex],
500 &scanCodes);
501 if (!err) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800502 // check the possible scan codes identified by the layout map against the
503 // map of codes actually emitted by the driver
504 for (size_t sc = 0; sc < scanCodes.size(); sc++) {
Chris Ye66fbac32020-07-06 20:36:43 -0700505 if (device->keyBitmask.test(scanCodes[sc])) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800506 outFlags[codeIndex] = 1;
507 break;
508 }
509 }
510 }
511 }
512 return true;
513 }
514 return false;
515}
516
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700517status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
518 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800519 AutoMutex _l(mLock);
520 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700521 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800522
Chris Ye66fbac32020-07-06 20:36:43 -0700523 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800524 // Check the key character map first.
525 sp<KeyCharacterMap> kcm = device->getKeyCharacterMap();
Yi Kong9b14ac62018-07-17 13:48:38 -0700526 if (kcm != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800527 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
528 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700529 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800530 }
531 }
532
533 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700534 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800535 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700536 status = NO_ERROR;
537 }
538 }
539
540 if (status == NO_ERROR) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700541 if (kcm != nullptr) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700542 kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState);
543 } else {
544 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800545 }
546 }
547 }
548
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700549 if (status != NO_ERROR) {
550 *outKeycode = 0;
551 *outFlags = 0;
552 *outMetaState = metaState;
553 }
554
555 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800556}
557
558status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
559 AutoMutex _l(mLock);
560 Device* device = getDeviceLocked(deviceId);
561
Chris Ye66fbac32020-07-06 20:36:43 -0700562 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800563 status_t err = device->keyMap.keyLayoutMap->mapAxis(scanCode, outAxisInfo);
564 if (err == NO_ERROR) {
565 return NO_ERROR;
566 }
567 }
568
569 return NAME_NOT_FOUND;
570}
571
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100572void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800573 AutoMutex _l(mLock);
574
575 mExcludedDevices = devices;
576}
577
578bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
579 AutoMutex _l(mLock);
580 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700581 if (device != nullptr && scanCode >= 0 && scanCode <= KEY_MAX) {
582 return device->keyBitmask.test(scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800583 }
584 return false;
585}
586
587bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
588 AutoMutex _l(mLock);
589 Device* device = getDeviceLocked(deviceId);
590 int32_t sc;
Chris Ye66fbac32020-07-06 20:36:43 -0700591 if (device != nullptr && mapLed(device, led, &sc) == NO_ERROR) {
592 return device->ledBitmask.test(sc);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800593 }
594 return false;
595}
596
597void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
598 AutoMutex _l(mLock);
599 Device* device = getDeviceLocked(deviceId);
600 setLedStateLocked(device, led, on);
601}
602
603void EventHub::setLedStateLocked(Device* device, int32_t led, bool on) {
604 int32_t sc;
Chris Ye66fbac32020-07-06 20:36:43 -0700605 if (device != nullptr && device->hasValidFd() && mapLed(device, led, &sc) != NAME_NOT_FOUND) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800606 struct input_event ev;
607 ev.time.tv_sec = 0;
608 ev.time.tv_usec = 0;
609 ev.type = EV_LED;
610 ev.code = sc;
611 ev.value = on ? 1 : 0;
612
613 ssize_t nWrite;
614 do {
615 nWrite = write(device->fd, &ev, sizeof(struct input_event));
616 } while (nWrite == -1 && errno == EINTR);
617 }
618}
619
620void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700621 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800622 outVirtualKeys.clear();
623
624 AutoMutex _l(mLock);
625 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700626 if (device != nullptr && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800627 const std::vector<VirtualKeyDefinition> virtualKeys =
628 device->virtualKeyMap->getVirtualKeys();
629 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800630 }
631}
632
633sp<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
634 AutoMutex _l(mLock);
635 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700636 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800637 return device->getKeyCharacterMap();
638 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700639 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800640}
641
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700642bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, const sp<KeyCharacterMap>& map) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800643 AutoMutex _l(mLock);
644 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700645 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800646 if (map != device->overlayKeyMap) {
647 device->overlayKeyMap = map;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700648 device->combinedKeyMap = KeyCharacterMap::combine(device->keyMap.keyCharacterMap, map);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800649 return true;
650 }
651 }
652 return false;
653}
654
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100655static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
656 std::string rawDescriptor;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700657 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800658 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100659 if (!identifier.uniqueId.empty()) {
660 rawDescriptor += "uniqueId:";
661 rawDescriptor += identifier.uniqueId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800662 } else if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100663 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800664 }
665
666 if (identifier.vendor == 0 && identifier.product == 0) {
667 // If we don't know the vendor and product id, then the device is probably
668 // built-in so we need to rely on other information to uniquely identify
669 // the input device. Usually we try to avoid relying on the device name or
670 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100671 if (!identifier.name.empty()) {
672 rawDescriptor += "name:";
673 rawDescriptor += identifier.name;
674 } else if (!identifier.location.empty()) {
675 rawDescriptor += "location:";
676 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800677 }
678 }
679 identifier.descriptor = sha1(rawDescriptor);
680 return rawDescriptor;
681}
682
683void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
684 // Compute a device descriptor that uniquely identifies the device.
685 // The descriptor is assumed to be a stable identifier. Its value should not
686 // change between reboots, reconnections, firmware updates or new releases
687 // of Android. In practice we sometimes get devices that cannot be uniquely
688 // identified. In this case we enforce uniqueness between connected devices.
689 // Ideally, we also want the descriptor to be short and relatively opaque.
690
691 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100692 std::string rawDescriptor = generateDescriptor(identifier);
693 if (identifier.uniqueId.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800694 // If it didn't have a unique id check for conflicts and enforce
695 // uniqueness if necessary.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700696 while (getDeviceByDescriptorLocked(identifier.descriptor) != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800697 identifier.nonce++;
698 rawDescriptor = generateDescriptor(identifier);
699 }
700 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100701 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700702 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800703}
704
705void EventHub::vibrate(int32_t deviceId, nsecs_t duration) {
706 AutoMutex _l(mLock);
707 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700708 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800709 ff_effect effect;
710 memset(&effect, 0, sizeof(effect));
711 effect.type = FF_RUMBLE;
712 effect.id = device->ffEffectId;
713 effect.u.rumble.strong_magnitude = 0xc000;
714 effect.u.rumble.weak_magnitude = 0xc000;
715 effect.replay.length = (duration + 999999LL) / 1000000LL;
716 effect.replay.delay = 0;
717 if (ioctl(device->fd, EVIOCSFF, &effect)) {
718 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700719 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800720 return;
721 }
722 device->ffEffectId = effect.id;
723
724 struct input_event ev;
725 ev.time.tv_sec = 0;
726 ev.time.tv_usec = 0;
727 ev.type = EV_FF;
728 ev.code = device->ffEffectId;
729 ev.value = 1;
730 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
731 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700732 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800733 return;
734 }
735 device->ffEffectPlaying = true;
736 }
737}
738
739void EventHub::cancelVibrate(int32_t deviceId) {
740 AutoMutex _l(mLock);
741 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700742 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800743 if (device->ffEffectPlaying) {
744 device->ffEffectPlaying = false;
745
746 struct input_event ev;
747 ev.time.tv_sec = 0;
748 ev.time.tv_usec = 0;
749 ev.type = EV_FF;
750 ev.code = device->ffEffectId;
751 ev.value = 0;
752 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
753 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700754 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800755 return;
756 }
757 }
758 }
759}
760
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100761EventHub::Device* EventHub::getDeviceByDescriptorLocked(const std::string& descriptor) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800762 size_t size = mDevices.size();
763 for (size_t i = 0; i < size; i++) {
764 Device* device = mDevices.valueAt(i);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100765 if (descriptor == device->identifier.descriptor) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800766 return device;
767 }
768 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700769 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800770}
771
772EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -0800773 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800774 deviceId = mBuiltInKeyboardId;
775 }
776 ssize_t index = mDevices.indexOfKey(deviceId);
777 return index >= 0 ? mDevices.valueAt(index) : NULL;
778}
779
Chris Ye8594e192020-07-14 10:34:06 -0700780EventHub::Device* EventHub::getDeviceByPathLocked(const std::string& devicePath) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800781 for (size_t i = 0; i < mDevices.size(); i++) {
782 Device* device = mDevices.valueAt(i);
783 if (device->path == devicePath) {
784 return device;
785 }
786 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700787 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788}
789
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700790/**
791 * The file descriptor could be either input device, or a video device (associated with a
792 * specific input device). Check both cases here, and return the device that this event
793 * belongs to. Caller can compare the fd's once more to determine event type.
794 * Looks through all input devices, and only attached video devices. Unattached video
795 * devices are ignored.
796 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700797EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
798 for (size_t i = 0; i < mDevices.size(); i++) {
799 Device* device = mDevices.valueAt(i);
800 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700801 // This is an input device event
802 return device;
803 }
804 if (device->videoDevice && device->videoDevice->getFd() == fd) {
805 // This is a video device event
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700806 return device;
807 }
808 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700809 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
810 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700811 return nullptr;
812}
813
Michael Wrightd02c5b62014-02-10 15:10:22 -0800814size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
815 ALOG_ASSERT(bufferSize >= 1);
816
817 AutoMutex _l(mLock);
818
819 struct input_event readBuffer[bufferSize];
820
821 RawEvent* event = buffer;
822 size_t capacity = bufferSize;
823 bool awoken = false;
824 for (;;) {
825 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
826
827 // Reopen input devices if needed.
828 if (mNeedToReopenDevices) {
829 mNeedToReopenDevices = false;
830
831 ALOGI("Reopening all input devices due to a configuration change.");
832
833 closeAllDevicesLocked();
834 mNeedToScanDevices = true;
835 break; // return to the caller before we actually rescan
836 }
837
838 // Report any devices that had last been added/removed.
839 while (mClosingDevices) {
840 Device* device = mClosingDevices;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700841 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800842 mClosingDevices = device->next;
843 event->when = now;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700844 event->deviceId = (device->id == mBuiltInKeyboardId)
845 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
846 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800847 event->type = DEVICE_REMOVED;
848 event += 1;
849 delete device;
850 mNeedToSendFinishedDeviceScan = true;
851 if (--capacity == 0) {
852 break;
853 }
854 }
855
856 if (mNeedToScanDevices) {
857 mNeedToScanDevices = false;
858 scanDevicesLocked();
859 mNeedToSendFinishedDeviceScan = true;
860 }
861
Yi Kong9b14ac62018-07-17 13:48:38 -0700862 while (mOpeningDevices != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800863 Device* device = mOpeningDevices;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700864 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800865 mOpeningDevices = device->next;
866 event->when = now;
867 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
868 event->type = DEVICE_ADDED;
869 event += 1;
870 mNeedToSendFinishedDeviceScan = true;
871 if (--capacity == 0) {
872 break;
873 }
874 }
875
876 if (mNeedToSendFinishedDeviceScan) {
877 mNeedToSendFinishedDeviceScan = false;
878 event->when = now;
879 event->type = FINISHED_DEVICE_SCAN;
880 event += 1;
881 if (--capacity == 0) {
882 break;
883 }
884 }
885
886 // Grab the next input event.
887 bool deviceChanged = false;
888 while (mPendingEventIndex < mPendingEventCount) {
889 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700890 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800891 if (eventItem.events & EPOLLIN) {
892 mPendingINotify = true;
893 } else {
894 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
895 }
896 continue;
897 }
898
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700899 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800900 if (eventItem.events & EPOLLIN) {
901 ALOGV("awoken after wake()");
902 awoken = true;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -0500903 char wakeReadBuffer[16];
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904 ssize_t nRead;
905 do {
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -0500906 nRead = read(mWakeReadPipeFd, wakeReadBuffer, sizeof(wakeReadBuffer));
907 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(wakeReadBuffer));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800908 } else {
909 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700910 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800911 }
912 continue;
913 }
914
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700915 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700916 if (!device) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700917 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
918 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700919 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800920 continue;
921 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700922 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
923 if (eventItem.events & EPOLLIN) {
924 size_t numFrames = device->videoDevice->readAndQueueFrames();
925 if (numFrames == 0) {
926 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700927 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700928 }
929 } else if (eventItem.events & EPOLLHUP) {
930 // TODO(b/121395353) - consider adding EPOLLRDHUP
931 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700932 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700933 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
934 device->videoDevice = nullptr;
935 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700936 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
937 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700938 ALOG_ASSERT(!DEBUG);
939 }
940 continue;
941 }
942 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -0800943 if (eventItem.events & EPOLLIN) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700944 int32_t readSize =
945 read(device->fd, readBuffer, sizeof(struct input_event) * capacity);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800946 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
947 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -0700948 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700949 " bufferSize: %zu capacity: %zu errno: %d)\n",
950 device->fd, readSize, bufferSize, capacity, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800951 deviceChanged = true;
952 closeDeviceLocked(device);
953 } else if (readSize < 0) {
954 if (errno != EAGAIN && errno != EINTR) {
955 ALOGW("could not get event (errno=%d)", errno);
956 }
957 } else if ((readSize % sizeof(struct input_event)) != 0) {
958 ALOGE("could not get event (wrong size: %d)", readSize);
959 } else {
960 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
961
962 size_t count = size_t(readSize) / sizeof(struct input_event);
963 for (size_t i = 0; i < count; i++) {
964 struct input_event& iev = readBuffer[i];
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800965 event->when = processEventTimestamp(iev);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800966 event->deviceId = deviceId;
967 event->type = iev.type;
968 event->code = iev.code;
969 event->value = iev.value;
970 event += 1;
971 capacity -= 1;
972 }
973 if (capacity == 0) {
974 // The result buffer is full. Reset the pending event index
975 // so we will try to read the device again on the next iteration.
976 mPendingEventIndex -= 1;
977 break;
978 }
979 }
980 } else if (eventItem.events & EPOLLHUP) {
981 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700982 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800983 deviceChanged = true;
984 closeDeviceLocked(device);
985 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700986 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
987 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800988 }
989 }
990
991 // readNotify() will modify the list of devices so this must be done after
992 // processing all other events to ensure that we read all remaining events
993 // before closing the devices.
994 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
995 mPendingINotify = false;
996 readNotifyLocked();
997 deviceChanged = true;
998 }
999
1000 // Report added or removed devices immediately.
1001 if (deviceChanged) {
1002 continue;
1003 }
1004
1005 // Return now if we have collected any events or if we were explicitly awoken.
1006 if (event != buffer || awoken) {
1007 break;
1008 }
1009
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001010 // Poll for events.
1011 // When a device driver has pending (unread) events, it acquires
1012 // a kernel wake lock. Once the last pending event has been read, the device
1013 // driver will release the kernel wake lock, but the epoll will hold the wakelock,
1014 // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
1015 // is called again for the same fd that produced the event.
1016 // Thus the system can only sleep if there are no events pending or
1017 // currently being processed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001018 //
1019 // The timeout is advisory only. If the device is asleep, it will not wake just to
1020 // service the timeout.
1021 mPendingEventIndex = 0;
1022
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001023 mLock.unlock(); // release lock before poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001024
1025 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1026
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001027 mLock.lock(); // reacquire lock after poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001028
1029 if (pollResult == 0) {
1030 // Timed out.
1031 mPendingEventCount = 0;
1032 break;
1033 }
1034
1035 if (pollResult < 0) {
1036 // An error occurred.
1037 mPendingEventCount = 0;
1038
1039 // Sleep after errors to avoid locking up the system.
1040 // Hopefully the error is transient.
1041 if (errno != EINTR) {
1042 ALOGW("poll failed (errno=%d)\n", errno);
1043 usleep(100000);
1044 }
1045 } else {
1046 // Some events occurred.
1047 mPendingEventCount = size_t(pollResult);
1048 }
1049 }
1050
1051 // All done, return the number of events we read.
1052 return event - buffer;
1053}
1054
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001055std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
1056 AutoMutex _l(mLock);
1057
1058 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001059 if (device == nullptr || !device->videoDevice) {
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001060 return {};
1061 }
1062 return device->videoDevice->consumeFrames();
1063}
1064
Michael Wrightd02c5b62014-02-10 15:10:22 -08001065void EventHub::wake() {
1066 ALOGV("wake() called");
1067
1068 ssize_t nWrite;
1069 do {
1070 nWrite = write(mWakeWritePipeFd, "W", 1);
1071 } while (nWrite == -1 && errno == EINTR);
1072
1073 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001074 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001075 }
1076}
1077
1078void EventHub::scanDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001079 status_t result = scanDirLocked(DEVICE_PATH);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001080 if (result < 0) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001081 ALOGE("scan dir failed for %s", DEVICE_PATH);
1082 }
Philip Quinn39b81682019-01-09 22:20:39 -08001083 if (isV4lScanningEnabled()) {
1084 result = scanVideoDirLocked(VIDEO_DEVICE_PATH);
1085 if (result != OK) {
1086 ALOGE("scan video dir failed for %s", VIDEO_DEVICE_PATH);
1087 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001088 }
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001089 if (mDevices.indexOfKey(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) < 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001090 createVirtualKeyboardLocked();
1091 }
1092}
1093
1094// ----------------------------------------------------------------------------
1095
Michael Wrightd02c5b62014-02-10 15:10:22 -08001096static const int32_t GAMEPAD_KEYCODES[] = {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001097 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C, //
1098 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z, //
1099 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1, //
1100 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2, //
1101 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR, //
1102 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE, //
Michael Wrightd02c5b62014-02-10 15:10:22 -08001103};
1104
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001105status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001106 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001107 struct epoll_event eventItem = {};
1108 eventItem.events = EPOLLIN | EPOLLWAKEUP;
1109 eventItem.data.fd = fd;
1110 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1111 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001112 return -errno;
1113 }
1114 return OK;
1115}
1116
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001117status_t EventHub::unregisterFdFromEpoll(int fd) {
1118 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
1119 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
1120 return -errno;
1121 }
1122 return OK;
1123}
1124
1125status_t EventHub::registerDeviceForEpollLocked(Device* device) {
1126 if (device == nullptr) {
1127 if (DEBUG) {
1128 LOG_ALWAYS_FATAL("Cannot call registerDeviceForEpollLocked with null Device");
1129 }
1130 return BAD_VALUE;
1131 }
1132 status_t result = registerFdForEpoll(device->fd);
1133 if (result != OK) {
1134 ALOGE("Could not add input device fd to epoll for device %" PRId32, device->id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001135 return result;
1136 }
1137 if (device->videoDevice) {
1138 registerVideoDeviceForEpollLocked(*device->videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001139 }
1140 return result;
1141}
1142
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001143void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
1144 status_t result = registerFdForEpoll(videoDevice.getFd());
1145 if (result != OK) {
1146 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
1147 }
1148}
1149
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001150status_t EventHub::unregisterDeviceFromEpollLocked(Device* device) {
1151 if (device->hasValidFd()) {
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001152 status_t result = unregisterFdFromEpoll(device->fd);
1153 if (result != OK) {
1154 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device->id);
1155 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001156 }
1157 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001158 if (device->videoDevice) {
1159 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1160 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001161 return OK;
1162}
1163
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001164void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
1165 if (videoDevice.hasValidFd()) {
1166 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
1167 if (result != OK) {
1168 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001169 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001170 }
1171 }
1172}
1173
Chris Ye8594e192020-07-14 10:34:06 -07001174status_t EventHub::openDeviceLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001175 char buffer[80];
1176
Chris Ye8594e192020-07-14 10:34:06 -07001177 ALOGV("Opening device: %s", devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001178
Chris Ye8594e192020-07-14 10:34:06 -07001179 int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001180 if (fd < 0) {
Chris Ye8594e192020-07-14 10:34:06 -07001181 ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001182 return -1;
1183 }
1184
1185 InputDeviceIdentifier identifier;
1186
1187 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001188 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Chris Ye8594e192020-07-14 10:34:06 -07001189 ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001190 } else {
1191 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001192 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001193 }
1194
1195 // Check to see if the device is on our excluded list
1196 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001197 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001198 if (identifier.name == item) {
Chris Ye8594e192020-07-14 10:34:06 -07001199 ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001200 close(fd);
1201 return -1;
1202 }
1203 }
1204
1205 // Get device driver version.
1206 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001207 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Chris Ye8594e192020-07-14 10:34:06 -07001208 ALOGE("could not get driver version for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001209 close(fd);
1210 return -1;
1211 }
1212
1213 // Get device identifier.
1214 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001215 if (ioctl(fd, EVIOCGID, &inputId)) {
Chris Ye8594e192020-07-14 10:34:06 -07001216 ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001217 close(fd);
1218 return -1;
1219 }
1220 identifier.bus = inputId.bustype;
1221 identifier.product = inputId.product;
1222 identifier.vendor = inputId.vendor;
1223 identifier.version = inputId.version;
1224
1225 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001226 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
1227 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228 } else {
1229 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001230 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001231 }
1232
1233 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001234 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
1235 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001236 } else {
1237 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001238 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001239 }
1240
1241 // Fill in the descriptor.
1242 assignDescriptorLocked(identifier);
1243
Michael Wrightd02c5b62014-02-10 15:10:22 -08001244 // Allocate device. (The device object takes ownership of the fd at this point.)
1245 int32_t deviceId = mNextDeviceId++;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001246 Device* device = new Device(fd, deviceId, devicePath, identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001247
Chris Ye8594e192020-07-14 10:34:06 -07001248 ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001249 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001250 " vendor %04x\n"
1251 " product %04x\n"
1252 " version %04x\n",
1253 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001254 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
1255 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
1256 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
1257 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001258 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
1259 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001260
1261 // Load the configuration file for the device.
1262 loadConfigurationLocked(device);
1263
1264 // Figure out the kinds of events the device reports.
Chris Ye66fbac32020-07-06 20:36:43 -07001265 device->readDeviceBitMask(EVIOCGBIT(EV_KEY, 0), device->keyBitmask);
1266 device->readDeviceBitMask(EVIOCGBIT(EV_ABS, 0), device->absBitmask);
1267 device->readDeviceBitMask(EVIOCGBIT(EV_REL, 0), device->relBitmask);
1268 device->readDeviceBitMask(EVIOCGBIT(EV_SW, 0), device->swBitmask);
1269 device->readDeviceBitMask(EVIOCGBIT(EV_LED, 0), device->ledBitmask);
1270 device->readDeviceBitMask(EVIOCGBIT(EV_FF, 0), device->ffBitmask);
1271 device->readDeviceBitMask(EVIOCGPROP(0), device->propBitmask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001272
1273 // See if this is a keyboard. Ignore everything in the button range except for
1274 // joystick and gamepad buttons which are handled like keyboards for the most part.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001275 bool haveKeyboardKeys =
Chris Ye66fbac32020-07-06 20:36:43 -07001276 device->keyBitmask.any(0, BTN_MISC) || device->keyBitmask.any(BTN_WHEEL, KEY_MAX + 1);
1277 bool haveGamepadButtons = device->keyBitmask.any(BTN_MISC, BTN_MOUSE) ||
1278 device->keyBitmask.any(BTN_JOYSTICK, BTN_DIGI);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001279 if (haveKeyboardKeys || haveGamepadButtons) {
1280 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1281 }
1282
1283 // See if this is a cursor device such as a trackball or mouse.
Chris Ye66fbac32020-07-06 20:36:43 -07001284 if (device->keyBitmask.test(BTN_MOUSE) && device->relBitmask.test(REL_X) &&
1285 device->relBitmask.test(REL_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001286 device->classes |= INPUT_DEVICE_CLASS_CURSOR;
1287 }
1288
Prashant Malani1941ff52015-08-11 18:29:28 -07001289 // See if this is a rotary encoder type device.
1290 String8 deviceType = String8();
1291 if (device->configuration &&
1292 device->configuration->tryGetProperty(String8("device.type"), deviceType)) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001293 if (!deviceType.compare(String8("rotaryEncoder"))) {
1294 device->classes |= INPUT_DEVICE_CLASS_ROTARY_ENCODER;
1295 }
Prashant Malani1941ff52015-08-11 18:29:28 -07001296 }
1297
Michael Wrightd02c5b62014-02-10 15:10:22 -08001298 // See if this is a touch pad.
1299 // Is this a new modern multi-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07001300 if (device->absBitmask.test(ABS_MT_POSITION_X) && device->absBitmask.test(ABS_MT_POSITION_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001301 // Some joysticks such as the PS3 controller report axes that conflict
1302 // with the ABS_MT range. Try to confirm that the device really is
1303 // a touch screen.
Chris Ye66fbac32020-07-06 20:36:43 -07001304 if (device->keyBitmask.test(BTN_TOUCH) || !haveGamepadButtons) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001305 device->classes |= INPUT_DEVICE_CLASS_TOUCH | INPUT_DEVICE_CLASS_TOUCH_MT;
1306 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001307 // Is this an old style single-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07001308 } else if (device->keyBitmask.test(BTN_TOUCH) && device->absBitmask.test(ABS_X) &&
1309 device->absBitmask.test(ABS_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001310 device->classes |= INPUT_DEVICE_CLASS_TOUCH;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001311 // Is this a BT stylus?
Chris Ye66fbac32020-07-06 20:36:43 -07001312 } else if ((device->absBitmask.test(ABS_PRESSURE) || device->keyBitmask.test(BTN_TOUCH)) &&
1313 !device->absBitmask.test(ABS_X) && !device->absBitmask.test(ABS_Y)) {
Michael Wright842500e2015-03-13 17:32:02 -07001314 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
1315 // Keyboard will try to claim some of the buttons but we really want to reserve those so we
1316 // can fuse it with the touch screen data, so just take them back. Note this means an
1317 // external stylus cannot also be a keyboard device.
1318 device->classes &= ~INPUT_DEVICE_CLASS_KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001319 }
1320
1321 // See if this device is a joystick.
1322 // Assumes that joysticks always have gamepad buttons in order to distinguish them
1323 // from other devices such as accelerometers that also have absolute axes.
1324 if (haveGamepadButtons) {
1325 uint32_t assumedClasses = device->classes | INPUT_DEVICE_CLASS_JOYSTICK;
1326 for (int i = 0; i <= ABS_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07001327 if (device->absBitmask.test(i) &&
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001328 (getAbsAxisUsage(i, assumedClasses) & INPUT_DEVICE_CLASS_JOYSTICK)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001329 device->classes = assumedClasses;
1330 break;
1331 }
1332 }
1333 }
1334
1335 // Check whether this device has switches.
1336 for (int i = 0; i <= SW_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07001337 if (device->swBitmask.test(i)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001338 device->classes |= INPUT_DEVICE_CLASS_SWITCH;
1339 break;
1340 }
1341 }
1342
1343 // Check whether this device supports the vibrator.
Chris Ye66fbac32020-07-06 20:36:43 -07001344 if (device->ffBitmask.test(FF_RUMBLE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001345 device->classes |= INPUT_DEVICE_CLASS_VIBRATOR;
1346 }
1347
1348 // Configure virtual keys.
1349 if ((device->classes & INPUT_DEVICE_CLASS_TOUCH)) {
1350 // Load the virtual keys for the touch screen, if any.
1351 // We do this now so that we can make sure to load the keymap if necessary.
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001352 bool success = loadVirtualKeyMapLocked(device);
1353 if (success) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001354 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1355 }
1356 }
1357
1358 // Load the key map.
1359 // We need to do this for joysticks too because the key layout may specify axes.
1360 status_t keyMapStatus = NAME_NOT_FOUND;
1361 if (device->classes & (INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_JOYSTICK)) {
1362 // Load the keymap for the device.
1363 keyMapStatus = loadKeyMapLocked(device);
1364 }
1365
1366 // Configure the keyboard, gamepad or virtual keyboard.
1367 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1368 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001369 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
1370 isEligibleBuiltInKeyboard(device->identifier, device->configuration, &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001371 mBuiltInKeyboardId = device->id;
1372 }
1373
1374 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
1375 if (hasKeycodeLocked(device, AKEYCODE_Q)) {
1376 device->classes |= INPUT_DEVICE_CLASS_ALPHAKEY;
1377 }
1378
1379 // See if this device has a DPAD.
1380 if (hasKeycodeLocked(device, AKEYCODE_DPAD_UP) &&
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001381 hasKeycodeLocked(device, AKEYCODE_DPAD_DOWN) &&
1382 hasKeycodeLocked(device, AKEYCODE_DPAD_LEFT) &&
1383 hasKeycodeLocked(device, AKEYCODE_DPAD_RIGHT) &&
1384 hasKeycodeLocked(device, AKEYCODE_DPAD_CENTER)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001385 device->classes |= INPUT_DEVICE_CLASS_DPAD;
1386 }
1387
1388 // See if this device has a gamepad.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001389 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES) / sizeof(GAMEPAD_KEYCODES[0]); i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001390 if (hasKeycodeLocked(device, GAMEPAD_KEYCODES[i])) {
1391 device->classes |= INPUT_DEVICE_CLASS_GAMEPAD;
1392 break;
1393 }
1394 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001395 }
1396
1397 // If the device isn't recognized as something we handle, don't monitor it.
1398 if (device->classes == 0) {
Chris Ye8594e192020-07-14 10:34:06 -07001399 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001400 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001401 delete device;
1402 return -1;
1403 }
1404
Tim Kilbourn063ff532015-04-08 10:26:18 -07001405 // Determine whether the device has a mic.
1406 if (deviceHasMicLocked(device)) {
1407 device->classes |= INPUT_DEVICE_CLASS_MIC;
1408 }
1409
Michael Wrightd02c5b62014-02-10 15:10:22 -08001410 // Determine whether the device is external or internal.
1411 if (isExternalDeviceLocked(device)) {
1412 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL;
1413 }
1414
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001415 if (device->classes & (INPUT_DEVICE_CLASS_JOYSTICK | INPUT_DEVICE_CLASS_DPAD) &&
1416 device->classes & INPUT_DEVICE_CLASS_GAMEPAD) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001417 device->controllerNumber = getNextControllerNumberLocked(device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001418 setLedForControllerLocked(device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001419 }
1420
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001421 // Find a matching video device by comparing device names
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001422 // This should be done before registerDeviceForEpollLocked, so that both fds are added to epoll
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001423 for (std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
1424 if (device->identifier.name == videoDevice->getName()) {
1425 device->videoDevice = std::move(videoDevice);
1426 break;
1427 }
1428 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001429 mUnattachedVideoDevices
1430 .erase(std::remove_if(mUnattachedVideoDevices.begin(), mUnattachedVideoDevices.end(),
1431 [](const std::unique_ptr<TouchVideoDevice>& videoDevice) {
1432 return videoDevice == nullptr;
1433 }),
1434 mUnattachedVideoDevices.end());
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001435
1436 if (registerDeviceForEpollLocked(device) != OK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001437 delete device;
1438 return -1;
1439 }
1440
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001441 configureFd(device);
1442
1443 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=0x%x, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001444 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Chris Ye8594e192020-07-14 10:34:06 -07001445 deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(), device->classes,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001446 device->configurationFile.c_str(), device->keyMap.keyLayoutFile.c_str(),
1447 device->keyMap.keyCharacterMapFile.c_str(), toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001448
1449 addDeviceLocked(device);
1450 return OK;
1451}
1452
1453void EventHub::configureFd(Device* device) {
1454 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
1455 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1456 // Disable kernel key repeat since we handle it ourselves
1457 unsigned int repeatRate[] = {0, 0};
1458 if (ioctl(device->fd, EVIOCSREP, repeatRate)) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001459 ALOGW("Unable to disable kernel key repeat for %s: %s", device->path.c_str(),
1460 strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001461 }
1462 }
1463
Michael Wrightd02c5b62014-02-10 15:10:22 -08001464 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
1465 // associated with input events. This is important because the input system
1466 // uses the timestamps extensively and assumes they were recorded using the monotonic
1467 // clock.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001468 int clockId = CLOCK_MONOTONIC;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001469 bool usingClockIoctl = !ioctl(device->fd, EVIOCSCLOCKID, &clockId);
Atif Niyaz4180aa42019-05-10 16:27:48 -07001470 ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001471}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001472
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001473void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
1474 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
1475 if (!videoDevice) {
1476 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
1477 return;
1478 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001479 // Transfer ownership of this video device to a matching input device
1480 for (size_t i = 0; i < mDevices.size(); i++) {
1481 Device* device = mDevices.valueAt(i);
1482 if (videoDevice->getName() == device->identifier.name) {
1483 device->videoDevice = std::move(videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001484 if (device->enabled) {
1485 registerVideoDeviceForEpollLocked(*device->videoDevice);
1486 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001487 return;
1488 }
1489 }
1490
1491 // Couldn't find a matching input device, so just add it to a temporary holding queue.
1492 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001493 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001494 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001495 mUnattachedVideoDevices.push_back(std::move(videoDevice));
1496}
1497
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001498bool EventHub::isDeviceEnabled(int32_t deviceId) {
1499 AutoMutex _l(mLock);
1500 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001501 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001502 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1503 return false;
1504 }
1505 return device->enabled;
1506}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001507
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001508status_t EventHub::enableDevice(int32_t deviceId) {
1509 AutoMutex _l(mLock);
1510 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001511 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001512 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1513 return BAD_VALUE;
1514 }
1515 if (device->enabled) {
1516 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
1517 return OK;
1518 }
1519 status_t result = device->enable();
1520 if (result != OK) {
1521 ALOGE("Failed to enable device %" PRId32, deviceId);
1522 return result;
1523 }
1524
1525 configureFd(device);
1526
1527 return registerDeviceForEpollLocked(device);
1528}
1529
1530status_t EventHub::disableDevice(int32_t deviceId) {
1531 AutoMutex _l(mLock);
1532 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001533 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001534 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1535 return BAD_VALUE;
1536 }
1537 if (!device->enabled) {
1538 ALOGW("Duplicate call to %s, input device already disabled", __func__);
1539 return OK;
1540 }
1541 unregisterDeviceFromEpollLocked(device);
1542 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001543}
1544
1545void EventHub::createVirtualKeyboardLocked() {
1546 InputDeviceIdentifier identifier;
1547 identifier.name = "Virtual";
1548 identifier.uniqueId = "<virtual>";
1549 assignDescriptorLocked(identifier);
1550
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001551 Device* device =
1552 new Device(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>", identifier);
1553 device->classes = INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_ALPHAKEY |
1554 INPUT_DEVICE_CLASS_DPAD | INPUT_DEVICE_CLASS_VIRTUAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001555 loadKeyMapLocked(device);
1556 addDeviceLocked(device);
1557}
1558
1559void EventHub::addDeviceLocked(Device* device) {
1560 mDevices.add(device->id, device);
1561 device->next = mOpeningDevices;
1562 mOpeningDevices = device;
1563}
1564
1565void EventHub::loadConfigurationLocked(Device* device) {
Chris Ye1d927aa2020-07-04 18:22:41 -07001566 device->configurationFile =
1567 getInputDeviceConfigurationFilePathByDeviceIdentifier(device->identifier,
1568 InputDeviceConfigurationFileType::
1569 CONFIGURATION);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001570 if (device->configurationFile.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001571 ALOGD("No input device configuration file found for device '%s'.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001572 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001573 } else {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001574 status_t status = PropertyMap::load(String8(device->configurationFile.c_str()),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001575 &device->configuration);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001576 if (status) {
1577 ALOGE("Error loading input device configuration file for device '%s'. "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001578 "Using default configuration.",
1579 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001580 }
1581 }
1582}
1583
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001584bool EventHub::loadVirtualKeyMapLocked(Device* device) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001585 // The virtual key map is supplied by the kernel as a system board property file.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001586 std::string path;
1587 path += "/sys/board_properties/virtualkeys.";
Siarhei Vishniakoub45635c2019-02-20 19:22:09 -06001588 path += device->identifier.getCanonicalName();
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001589 if (access(path.c_str(), R_OK)) {
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001590 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001591 }
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001592 device->virtualKeyMap = VirtualKeyMap::load(path);
1593 return device->virtualKeyMap != nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001594}
1595
1596status_t EventHub::loadKeyMapLocked(Device* device) {
1597 return device->keyMap.load(device->identifier, device->configuration);
1598}
1599
1600bool EventHub::isExternalDeviceLocked(Device* device) {
1601 if (device->configuration) {
1602 bool value;
1603 if (device->configuration->tryGetProperty(String8("device.internal"), value)) {
1604 return !value;
1605 }
1606 }
1607 return device->identifier.bus == BUS_USB || device->identifier.bus == BUS_BLUETOOTH;
1608}
1609
Tim Kilbourn063ff532015-04-08 10:26:18 -07001610bool EventHub::deviceHasMicLocked(Device* device) {
1611 if (device->configuration) {
1612 bool value;
1613 if (device->configuration->tryGetProperty(String8("audio.mic"), value)) {
1614 return value;
1615 }
1616 }
1617 return false;
1618}
1619
Michael Wrightd02c5b62014-02-10 15:10:22 -08001620int32_t EventHub::getNextControllerNumberLocked(Device* device) {
1621 if (mControllerNumbers.isFull()) {
1622 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001623 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001624 return 0;
1625 }
1626 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
1627 // one
1628 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
1629}
1630
1631void EventHub::releaseControllerNumberLocked(Device* device) {
1632 int32_t num = device->controllerNumber;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001633 device->controllerNumber = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001634 if (num == 0) {
1635 return;
1636 }
1637 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
1638}
1639
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001640void EventHub::setLedForControllerLocked(Device* device) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001641 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
1642 setLedStateLocked(device, ALED_CONTROLLER_1 + i, device->controllerNumber == i + 1);
1643 }
1644}
1645
1646bool EventHub::hasKeycodeLocked(Device* device, int keycode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001647 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001648 return false;
1649 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001650
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001651 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001652 device->keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes);
1653 const size_t N = scanCodes.size();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001654 for (size_t i = 0; i < N && i <= KEY_MAX; i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001655 int32_t sc = scanCodes[i];
Chris Ye66fbac32020-07-06 20:36:43 -07001656 if (sc >= 0 && sc <= KEY_MAX && device->keyBitmask.test(sc)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001657 return true;
1658 }
1659 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001660
Michael Wrightd02c5b62014-02-10 15:10:22 -08001661 return false;
1662}
1663
1664status_t EventHub::mapLed(Device* device, int32_t led, int32_t* outScanCode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001665 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001666 return NAME_NOT_FOUND;
1667 }
1668
1669 int32_t scanCode;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001670 if (device->keyMap.keyLayoutMap->findScanCodeForLed(led, &scanCode) != NAME_NOT_FOUND) {
Chris Ye66fbac32020-07-06 20:36:43 -07001671 if (scanCode >= 0 && scanCode <= LED_MAX && device->ledBitmask.test(scanCode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001672 *outScanCode = scanCode;
1673 return NO_ERROR;
1674 }
1675 }
1676 return NAME_NOT_FOUND;
1677}
1678
Chris Ye8594e192020-07-14 10:34:06 -07001679void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001680 Device* device = getDeviceByPathLocked(devicePath);
1681 if (device) {
1682 closeDeviceLocked(device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001683 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001684 }
Chris Ye8594e192020-07-14 10:34:06 -07001685 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001686}
1687
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001688/**
1689 * Find the video device by filename, and close it.
1690 * The video device is closed by path during an inotify event, where we don't have the
1691 * additional context about the video device fd, or the associated input device.
1692 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001693void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001694 // A video device may be owned by an existing input device, or it may be stored in
1695 // the mUnattachedVideoDevices queue. Check both locations.
1696 for (size_t i = 0; i < mDevices.size(); i++) {
1697 Device* device = mDevices.valueAt(i);
1698 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001699 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001700 device->videoDevice = nullptr;
1701 return;
1702 }
1703 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001704 mUnattachedVideoDevices
1705 .erase(std::remove_if(mUnattachedVideoDevices.begin(), mUnattachedVideoDevices.end(),
1706 [&devicePath](
1707 const std::unique_ptr<TouchVideoDevice>& videoDevice) {
1708 return videoDevice->getPath() == devicePath;
1709 }),
1710 mUnattachedVideoDevices.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001711}
1712
1713void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001714 mUnattachedVideoDevices.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001715 while (mDevices.size() > 0) {
1716 closeDeviceLocked(mDevices.valueAt(mDevices.size() - 1));
1717 }
1718}
1719
1720void EventHub::closeDeviceLocked(Device* device) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001721 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=0x%x", device->path.c_str(),
1722 device->identifier.name.c_str(), device->id, device->fd, device->classes);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001723
1724 if (device->id == mBuiltInKeyboardId) {
1725 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001726 device->path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001727 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
1728 }
1729
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001730 unregisterDeviceFromEpollLocked(device);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001731 if (device->videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001732 // This must be done after the video device is removed from epoll
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001733 mUnattachedVideoDevices.push_back(std::move(device->videoDevice));
1734 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001735
1736 releaseControllerNumberLocked(device);
1737
1738 mDevices.removeItem(device->id);
1739 device->close();
1740
1741 // Unlink for opening devices list if it is present.
Yi Kong9b14ac62018-07-17 13:48:38 -07001742 Device* pred = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001743 bool found = false;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001744 for (Device* entry = mOpeningDevices; entry != nullptr;) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001745 if (entry == device) {
1746 found = true;
1747 break;
1748 }
1749 pred = entry;
1750 entry = entry->next;
1751 }
1752 if (found) {
1753 // Unlink the device from the opening devices list then delete it.
1754 // We don't need to tell the client that the device was closed because
1755 // it does not even know it was opened in the first place.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001756 ALOGI("Device %s was immediately closed after opening.", device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001757 if (pred) {
1758 pred->next = device->next;
1759 } else {
1760 mOpeningDevices = device->next;
1761 }
1762 delete device;
1763 } else {
1764 // Link into closing devices list.
1765 // The device will be deleted later after we have informed the client.
1766 device->next = mClosingDevices;
1767 mClosingDevices = device;
1768 }
1769}
1770
1771status_t EventHub::readNotifyLocked() {
1772 int res;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001773 char event_buf[512];
1774 int event_size;
1775 int event_pos = 0;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001776 struct inotify_event* event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001777
1778 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
1779 res = read(mINotifyFd, event_buf, sizeof(event_buf));
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001780 if (res < (int)sizeof(*event)) {
1781 if (errno == EINTR) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001782 ALOGW("could not get event, %s\n", strerror(errno));
1783 return -1;
1784 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001785
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001786 while (res >= (int)sizeof(*event)) {
1787 event = (struct inotify_event*)(event_buf + event_pos);
1788 if (event->len) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001789 if (event->wd == mInputWd) {
Chris Ye8594e192020-07-14 10:34:06 -07001790 std::string filename = std::string(DEVICE_PATH) + "/" + event->name;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001791 if (event->mask & IN_CREATE) {
Chris Ye8594e192020-07-14 10:34:06 -07001792 openDeviceLocked(filename);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001793 } else {
1794 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
Chris Ye8594e192020-07-14 10:34:06 -07001795 closeDeviceByPathLocked(filename);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001796 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001797 } else if (event->wd == mVideoWd) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001798 if (isV4lTouchNode(event->name)) {
Chris Ye8594e192020-07-14 10:34:06 -07001799 std::string filename = std::string(VIDEO_DEVICE_PATH) + "/" + event->name;
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001800 if (event->mask & IN_CREATE) {
1801 openVideoDeviceLocked(filename);
1802 } else {
1803 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
1804 closeVideoDeviceByPathLocked(filename);
1805 }
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001806 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001807 } else {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001808 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event->wd);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001809 }
1810 }
1811 event_size = sizeof(*event) + event->len;
1812 res -= event_size;
1813 event_pos += event_size;
1814 }
1815 return 0;
1816}
1817
Chris Ye8594e192020-07-14 10:34:06 -07001818status_t EventHub::scanDirLocked(const std::string& dirname) {
1819 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
1820 openDeviceLocked(entry.path());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001821 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001822 return 0;
1823}
1824
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001825/**
1826 * Look for all dirname/v4l-touch* devices, and open them.
1827 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001828status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Chris Ye8594e192020-07-14 10:34:06 -07001829 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
1830 if (isV4lTouchNode(entry.path())) {
1831 ALOGI("Found touch video device %s", entry.path().c_str());
1832 openVideoDeviceLocked(entry.path());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001833 }
1834 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001835 return OK;
1836}
1837
Michael Wrightd02c5b62014-02-10 15:10:22 -08001838void EventHub::requestReopenDevices() {
1839 ALOGV("requestReopenDevices() called");
1840
1841 AutoMutex _l(mLock);
1842 mNeedToReopenDevices = true;
1843}
1844
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001845void EventHub::dump(std::string& dump) {
1846 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001847
1848 { // acquire lock
1849 AutoMutex _l(mLock);
1850
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001851 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001852
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001853 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001854
1855 for (size_t i = 0; i < mDevices.size(); i++) {
1856 const Device* device = mDevices.valueAt(i);
1857 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001858 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001859 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001860 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001861 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001862 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001863 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001864 dump += StringPrintf(INDENT3 "Classes: 0x%08x\n", device->classes);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001865 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001866 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001867 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
1868 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001869 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001870 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001871 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001872 "product=0x%04x, version=0x%04x\n",
1873 device->identifier.bus, device->identifier.vendor,
1874 device->identifier.product, device->identifier.version);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001875 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001876 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001877 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001878 device->keyMap.keyCharacterMapFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001879 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001880 device->configurationFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001881 dump += StringPrintf(INDENT3 "HaveKeyboardLayoutOverlay: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001882 toString(device->overlayKeyMap != nullptr));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001883 dump += INDENT3 "VideoDevice: ";
1884 if (device->videoDevice) {
1885 dump += device->videoDevice->dump() + "\n";
1886 } else {
1887 dump += "<none>\n";
1888 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001889 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001890
1891 dump += INDENT "Unattached video devices:\n";
1892 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
1893 dump += INDENT2 + videoDevice->dump() + "\n";
1894 }
1895 if (mUnattachedVideoDevices.empty()) {
1896 dump += INDENT2 "<none>\n";
1897 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001898 } // release lock
1899}
1900
1901void EventHub::monitor() {
1902 // Acquire and release the lock to ensure that the event hub has not deadlocked.
1903 mLock.lock();
1904 mLock.unlock();
1905}
1906
Michael Wrightd02c5b62014-02-10 15:10:22 -08001907}; // namespace android