blob: cef2b4ca14fa0a776e7617c2eac61bbe076b6be8 [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
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +0000705void EventHub::vibrate(int32_t deviceId, const VibrationElement& element) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800706 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;
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +0000713 // evdev FF_RUMBLE effect only supports two channels of vibration.
714 effect.u.rumble.strong_magnitude = element.getChannel(0);
715 effect.u.rumble.weak_magnitude = element.getChannel(1);
716 effect.replay.length = element.duration.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800717 effect.replay.delay = 0;
718 if (ioctl(device->fd, EVIOCSFF, &effect)) {
719 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700720 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800721 return;
722 }
723 device->ffEffectId = effect.id;
724
725 struct input_event ev;
726 ev.time.tv_sec = 0;
727 ev.time.tv_usec = 0;
728 ev.type = EV_FF;
729 ev.code = device->ffEffectId;
730 ev.value = 1;
731 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
732 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700733 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800734 return;
735 }
736 device->ffEffectPlaying = true;
737 }
738}
739
740void EventHub::cancelVibrate(int32_t deviceId) {
741 AutoMutex _l(mLock);
742 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700743 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800744 if (device->ffEffectPlaying) {
745 device->ffEffectPlaying = false;
746
747 struct input_event ev;
748 ev.time.tv_sec = 0;
749 ev.time.tv_usec = 0;
750 ev.type = EV_FF;
751 ev.code = device->ffEffectId;
752 ev.value = 0;
753 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
754 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700755 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800756 return;
757 }
758 }
759 }
760}
761
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100762EventHub::Device* EventHub::getDeviceByDescriptorLocked(const std::string& descriptor) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800763 size_t size = mDevices.size();
764 for (size_t i = 0; i < size; i++) {
765 Device* device = mDevices.valueAt(i);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100766 if (descriptor == device->identifier.descriptor) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800767 return device;
768 }
769 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700770 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800771}
772
773EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -0800774 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800775 deviceId = mBuiltInKeyboardId;
776 }
777 ssize_t index = mDevices.indexOfKey(deviceId);
778 return index >= 0 ? mDevices.valueAt(index) : NULL;
779}
780
Chris Ye8594e192020-07-14 10:34:06 -0700781EventHub::Device* EventHub::getDeviceByPathLocked(const std::string& devicePath) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800782 for (size_t i = 0; i < mDevices.size(); i++) {
783 Device* device = mDevices.valueAt(i);
784 if (device->path == devicePath) {
785 return device;
786 }
787 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700788 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800789}
790
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700791/**
792 * The file descriptor could be either input device, or a video device (associated with a
793 * specific input device). Check both cases here, and return the device that this event
794 * belongs to. Caller can compare the fd's once more to determine event type.
795 * Looks through all input devices, and only attached video devices. Unattached video
796 * devices are ignored.
797 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700798EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
799 for (size_t i = 0; i < mDevices.size(); i++) {
800 Device* device = mDevices.valueAt(i);
801 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700802 // This is an input device event
803 return device;
804 }
805 if (device->videoDevice && device->videoDevice->getFd() == fd) {
806 // This is a video device event
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700807 return device;
808 }
809 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700810 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
811 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700812 return nullptr;
813}
814
Michael Wrightd02c5b62014-02-10 15:10:22 -0800815size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
816 ALOG_ASSERT(bufferSize >= 1);
817
818 AutoMutex _l(mLock);
819
820 struct input_event readBuffer[bufferSize];
821
822 RawEvent* event = buffer;
823 size_t capacity = bufferSize;
824 bool awoken = false;
825 for (;;) {
826 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
827
828 // Reopen input devices if needed.
829 if (mNeedToReopenDevices) {
830 mNeedToReopenDevices = false;
831
832 ALOGI("Reopening all input devices due to a configuration change.");
833
834 closeAllDevicesLocked();
835 mNeedToScanDevices = true;
836 break; // return to the caller before we actually rescan
837 }
838
839 // Report any devices that had last been added/removed.
840 while (mClosingDevices) {
841 Device* device = mClosingDevices;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700842 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800843 mClosingDevices = device->next;
844 event->when = now;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700845 event->deviceId = (device->id == mBuiltInKeyboardId)
846 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
847 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800848 event->type = DEVICE_REMOVED;
849 event += 1;
850 delete device;
851 mNeedToSendFinishedDeviceScan = true;
852 if (--capacity == 0) {
853 break;
854 }
855 }
856
857 if (mNeedToScanDevices) {
858 mNeedToScanDevices = false;
859 scanDevicesLocked();
860 mNeedToSendFinishedDeviceScan = true;
861 }
862
Yi Kong9b14ac62018-07-17 13:48:38 -0700863 while (mOpeningDevices != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800864 Device* device = mOpeningDevices;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700865 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800866 mOpeningDevices = device->next;
867 event->when = now;
868 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
869 event->type = DEVICE_ADDED;
870 event += 1;
871 mNeedToSendFinishedDeviceScan = true;
872 if (--capacity == 0) {
873 break;
874 }
875 }
876
877 if (mNeedToSendFinishedDeviceScan) {
878 mNeedToSendFinishedDeviceScan = false;
879 event->when = now;
880 event->type = FINISHED_DEVICE_SCAN;
881 event += 1;
882 if (--capacity == 0) {
883 break;
884 }
885 }
886
887 // Grab the next input event.
888 bool deviceChanged = false;
889 while (mPendingEventIndex < mPendingEventCount) {
890 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700891 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800892 if (eventItem.events & EPOLLIN) {
893 mPendingINotify = true;
894 } else {
895 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
896 }
897 continue;
898 }
899
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700900 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800901 if (eventItem.events & EPOLLIN) {
902 ALOGV("awoken after wake()");
903 awoken = true;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -0500904 char wakeReadBuffer[16];
Michael Wrightd02c5b62014-02-10 15:10:22 -0800905 ssize_t nRead;
906 do {
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -0500907 nRead = read(mWakeReadPipeFd, wakeReadBuffer, sizeof(wakeReadBuffer));
908 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(wakeReadBuffer));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800909 } else {
910 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700911 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800912 }
913 continue;
914 }
915
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700916 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700917 if (!device) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700918 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
919 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700920 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800921 continue;
922 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700923 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
924 if (eventItem.events & EPOLLIN) {
925 size_t numFrames = device->videoDevice->readAndQueueFrames();
926 if (numFrames == 0) {
927 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700928 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700929 }
930 } else if (eventItem.events & EPOLLHUP) {
931 // TODO(b/121395353) - consider adding EPOLLRDHUP
932 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700933 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700934 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
935 device->videoDevice = nullptr;
936 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700937 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
938 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700939 ALOG_ASSERT(!DEBUG);
940 }
941 continue;
942 }
943 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -0800944 if (eventItem.events & EPOLLIN) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700945 int32_t readSize =
946 read(device->fd, readBuffer, sizeof(struct input_event) * capacity);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800947 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
948 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -0700949 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700950 " bufferSize: %zu capacity: %zu errno: %d)\n",
951 device->fd, readSize, bufferSize, capacity, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800952 deviceChanged = true;
953 closeDeviceLocked(device);
954 } else if (readSize < 0) {
955 if (errno != EAGAIN && errno != EINTR) {
956 ALOGW("could not get event (errno=%d)", errno);
957 }
958 } else if ((readSize % sizeof(struct input_event)) != 0) {
959 ALOGE("could not get event (wrong size: %d)", readSize);
960 } else {
961 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
962
963 size_t count = size_t(readSize) / sizeof(struct input_event);
964 for (size_t i = 0; i < count; i++) {
965 struct input_event& iev = readBuffer[i];
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800966 event->when = processEventTimestamp(iev);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800967 event->deviceId = deviceId;
968 event->type = iev.type;
969 event->code = iev.code;
970 event->value = iev.value;
971 event += 1;
972 capacity -= 1;
973 }
974 if (capacity == 0) {
975 // The result buffer is full. Reset the pending event index
976 // so we will try to read the device again on the next iteration.
977 mPendingEventIndex -= 1;
978 break;
979 }
980 }
981 } else if (eventItem.events & EPOLLHUP) {
982 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700983 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800984 deviceChanged = true;
985 closeDeviceLocked(device);
986 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700987 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
988 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800989 }
990 }
991
992 // readNotify() will modify the list of devices so this must be done after
993 // processing all other events to ensure that we read all remaining events
994 // before closing the devices.
995 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
996 mPendingINotify = false;
997 readNotifyLocked();
998 deviceChanged = true;
999 }
1000
1001 // Report added or removed devices immediately.
1002 if (deviceChanged) {
1003 continue;
1004 }
1005
1006 // Return now if we have collected any events or if we were explicitly awoken.
1007 if (event != buffer || awoken) {
1008 break;
1009 }
1010
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001011 // Poll for events.
1012 // When a device driver has pending (unread) events, it acquires
1013 // a kernel wake lock. Once the last pending event has been read, the device
1014 // driver will release the kernel wake lock, but the epoll will hold the wakelock,
1015 // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
1016 // is called again for the same fd that produced the event.
1017 // Thus the system can only sleep if there are no events pending or
1018 // currently being processed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001019 //
1020 // The timeout is advisory only. If the device is asleep, it will not wake just to
1021 // service the timeout.
1022 mPendingEventIndex = 0;
1023
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001024 mLock.unlock(); // release lock before poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001025
1026 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1027
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001028 mLock.lock(); // reacquire lock after poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001029
1030 if (pollResult == 0) {
1031 // Timed out.
1032 mPendingEventCount = 0;
1033 break;
1034 }
1035
1036 if (pollResult < 0) {
1037 // An error occurred.
1038 mPendingEventCount = 0;
1039
1040 // Sleep after errors to avoid locking up the system.
1041 // Hopefully the error is transient.
1042 if (errno != EINTR) {
1043 ALOGW("poll failed (errno=%d)\n", errno);
1044 usleep(100000);
1045 }
1046 } else {
1047 // Some events occurred.
1048 mPendingEventCount = size_t(pollResult);
1049 }
1050 }
1051
1052 // All done, return the number of events we read.
1053 return event - buffer;
1054}
1055
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001056std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
1057 AutoMutex _l(mLock);
1058
1059 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001060 if (device == nullptr || !device->videoDevice) {
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001061 return {};
1062 }
1063 return device->videoDevice->consumeFrames();
1064}
1065
Michael Wrightd02c5b62014-02-10 15:10:22 -08001066void EventHub::wake() {
1067 ALOGV("wake() called");
1068
1069 ssize_t nWrite;
1070 do {
1071 nWrite = write(mWakeWritePipeFd, "W", 1);
1072 } while (nWrite == -1 && errno == EINTR);
1073
1074 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001075 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001076 }
1077}
1078
1079void EventHub::scanDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001080 status_t result = scanDirLocked(DEVICE_PATH);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001081 if (result < 0) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001082 ALOGE("scan dir failed for %s", DEVICE_PATH);
1083 }
Philip Quinn39b81682019-01-09 22:20:39 -08001084 if (isV4lScanningEnabled()) {
1085 result = scanVideoDirLocked(VIDEO_DEVICE_PATH);
1086 if (result != OK) {
1087 ALOGE("scan video dir failed for %s", VIDEO_DEVICE_PATH);
1088 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001089 }
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001090 if (mDevices.indexOfKey(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) < 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001091 createVirtualKeyboardLocked();
1092 }
1093}
1094
1095// ----------------------------------------------------------------------------
1096
Michael Wrightd02c5b62014-02-10 15:10:22 -08001097static const int32_t GAMEPAD_KEYCODES[] = {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001098 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C, //
1099 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z, //
1100 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1, //
1101 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2, //
1102 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR, //
1103 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE, //
Michael Wrightd02c5b62014-02-10 15:10:22 -08001104};
1105
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001106status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001107 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001108 struct epoll_event eventItem = {};
1109 eventItem.events = EPOLLIN | EPOLLWAKEUP;
1110 eventItem.data.fd = fd;
1111 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1112 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001113 return -errno;
1114 }
1115 return OK;
1116}
1117
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001118status_t EventHub::unregisterFdFromEpoll(int fd) {
1119 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
1120 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
1121 return -errno;
1122 }
1123 return OK;
1124}
1125
1126status_t EventHub::registerDeviceForEpollLocked(Device* device) {
1127 if (device == nullptr) {
1128 if (DEBUG) {
1129 LOG_ALWAYS_FATAL("Cannot call registerDeviceForEpollLocked with null Device");
1130 }
1131 return BAD_VALUE;
1132 }
1133 status_t result = registerFdForEpoll(device->fd);
1134 if (result != OK) {
1135 ALOGE("Could not add input device fd to epoll for device %" PRId32, device->id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001136 return result;
1137 }
1138 if (device->videoDevice) {
1139 registerVideoDeviceForEpollLocked(*device->videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001140 }
1141 return result;
1142}
1143
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001144void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
1145 status_t result = registerFdForEpoll(videoDevice.getFd());
1146 if (result != OK) {
1147 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
1148 }
1149}
1150
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001151status_t EventHub::unregisterDeviceFromEpollLocked(Device* device) {
1152 if (device->hasValidFd()) {
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001153 status_t result = unregisterFdFromEpoll(device->fd);
1154 if (result != OK) {
1155 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device->id);
1156 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001157 }
1158 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001159 if (device->videoDevice) {
1160 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1161 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001162 return OK;
1163}
1164
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001165void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
1166 if (videoDevice.hasValidFd()) {
1167 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
1168 if (result != OK) {
1169 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001170 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001171 }
1172 }
1173}
1174
Chris Ye8594e192020-07-14 10:34:06 -07001175status_t EventHub::openDeviceLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001176 char buffer[80];
1177
Chris Ye8594e192020-07-14 10:34:06 -07001178 ALOGV("Opening device: %s", devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001179
Chris Ye8594e192020-07-14 10:34:06 -07001180 int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001181 if (fd < 0) {
Chris Ye8594e192020-07-14 10:34:06 -07001182 ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001183 return -1;
1184 }
1185
1186 InputDeviceIdentifier identifier;
1187
1188 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001189 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Chris Ye8594e192020-07-14 10:34:06 -07001190 ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001191 } else {
1192 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001193 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194 }
1195
1196 // Check to see if the device is on our excluded list
1197 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001198 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001199 if (identifier.name == item) {
Chris Ye8594e192020-07-14 10:34:06 -07001200 ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001201 close(fd);
1202 return -1;
1203 }
1204 }
1205
1206 // Get device driver version.
1207 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001208 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Chris Ye8594e192020-07-14 10:34:06 -07001209 ALOGE("could not get driver version for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001210 close(fd);
1211 return -1;
1212 }
1213
1214 // Get device identifier.
1215 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001216 if (ioctl(fd, EVIOCGID, &inputId)) {
Chris Ye8594e192020-07-14 10:34:06 -07001217 ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001218 close(fd);
1219 return -1;
1220 }
1221 identifier.bus = inputId.bustype;
1222 identifier.product = inputId.product;
1223 identifier.vendor = inputId.vendor;
1224 identifier.version = inputId.version;
1225
1226 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001227 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
1228 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001229 } else {
1230 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001231 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001232 }
1233
1234 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001235 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
1236 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237 } else {
1238 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001239 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001240 }
1241
1242 // Fill in the descriptor.
1243 assignDescriptorLocked(identifier);
1244
Michael Wrightd02c5b62014-02-10 15:10:22 -08001245 // Allocate device. (The device object takes ownership of the fd at this point.)
1246 int32_t deviceId = mNextDeviceId++;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001247 Device* device = new Device(fd, deviceId, devicePath, identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001248
Chris Ye8594e192020-07-14 10:34:06 -07001249 ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001250 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001251 " vendor %04x\n"
1252 " product %04x\n"
1253 " version %04x\n",
1254 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001255 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
1256 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
1257 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
1258 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001259 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
1260 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001261
1262 // Load the configuration file for the device.
1263 loadConfigurationLocked(device);
1264
1265 // Figure out the kinds of events the device reports.
Chris Ye66fbac32020-07-06 20:36:43 -07001266 device->readDeviceBitMask(EVIOCGBIT(EV_KEY, 0), device->keyBitmask);
1267 device->readDeviceBitMask(EVIOCGBIT(EV_ABS, 0), device->absBitmask);
1268 device->readDeviceBitMask(EVIOCGBIT(EV_REL, 0), device->relBitmask);
1269 device->readDeviceBitMask(EVIOCGBIT(EV_SW, 0), device->swBitmask);
1270 device->readDeviceBitMask(EVIOCGBIT(EV_LED, 0), device->ledBitmask);
1271 device->readDeviceBitMask(EVIOCGBIT(EV_FF, 0), device->ffBitmask);
1272 device->readDeviceBitMask(EVIOCGPROP(0), device->propBitmask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001273
1274 // See if this is a keyboard. Ignore everything in the button range except for
1275 // joystick and gamepad buttons which are handled like keyboards for the most part.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001276 bool haveKeyboardKeys =
Chris Ye66fbac32020-07-06 20:36:43 -07001277 device->keyBitmask.any(0, BTN_MISC) || device->keyBitmask.any(BTN_WHEEL, KEY_MAX + 1);
1278 bool haveGamepadButtons = device->keyBitmask.any(BTN_MISC, BTN_MOUSE) ||
1279 device->keyBitmask.any(BTN_JOYSTICK, BTN_DIGI);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001280 if (haveKeyboardKeys || haveGamepadButtons) {
1281 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1282 }
1283
1284 // See if this is a cursor device such as a trackball or mouse.
Chris Ye66fbac32020-07-06 20:36:43 -07001285 if (device->keyBitmask.test(BTN_MOUSE) && device->relBitmask.test(REL_X) &&
1286 device->relBitmask.test(REL_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001287 device->classes |= INPUT_DEVICE_CLASS_CURSOR;
1288 }
1289
Prashant Malani1941ff52015-08-11 18:29:28 -07001290 // See if this is a rotary encoder type device.
1291 String8 deviceType = String8();
1292 if (device->configuration &&
1293 device->configuration->tryGetProperty(String8("device.type"), deviceType)) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001294 if (!deviceType.compare(String8("rotaryEncoder"))) {
1295 device->classes |= INPUT_DEVICE_CLASS_ROTARY_ENCODER;
1296 }
Prashant Malani1941ff52015-08-11 18:29:28 -07001297 }
1298
Michael Wrightd02c5b62014-02-10 15:10:22 -08001299 // See if this is a touch pad.
1300 // Is this a new modern multi-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07001301 if (device->absBitmask.test(ABS_MT_POSITION_X) && device->absBitmask.test(ABS_MT_POSITION_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001302 // Some joysticks such as the PS3 controller report axes that conflict
1303 // with the ABS_MT range. Try to confirm that the device really is
1304 // a touch screen.
Chris Ye66fbac32020-07-06 20:36:43 -07001305 if (device->keyBitmask.test(BTN_TOUCH) || !haveGamepadButtons) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001306 device->classes |= INPUT_DEVICE_CLASS_TOUCH | INPUT_DEVICE_CLASS_TOUCH_MT;
1307 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001308 // Is this an old style single-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07001309 } else if (device->keyBitmask.test(BTN_TOUCH) && device->absBitmask.test(ABS_X) &&
1310 device->absBitmask.test(ABS_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001311 device->classes |= INPUT_DEVICE_CLASS_TOUCH;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001312 // Is this a BT stylus?
Chris Ye66fbac32020-07-06 20:36:43 -07001313 } else if ((device->absBitmask.test(ABS_PRESSURE) || device->keyBitmask.test(BTN_TOUCH)) &&
1314 !device->absBitmask.test(ABS_X) && !device->absBitmask.test(ABS_Y)) {
Michael Wright842500e2015-03-13 17:32:02 -07001315 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
1316 // Keyboard will try to claim some of the buttons but we really want to reserve those so we
1317 // can fuse it with the touch screen data, so just take them back. Note this means an
1318 // external stylus cannot also be a keyboard device.
1319 device->classes &= ~INPUT_DEVICE_CLASS_KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001320 }
1321
1322 // See if this device is a joystick.
1323 // Assumes that joysticks always have gamepad buttons in order to distinguish them
1324 // from other devices such as accelerometers that also have absolute axes.
1325 if (haveGamepadButtons) {
1326 uint32_t assumedClasses = device->classes | INPUT_DEVICE_CLASS_JOYSTICK;
1327 for (int i = 0; i <= ABS_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07001328 if (device->absBitmask.test(i) &&
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001329 (getAbsAxisUsage(i, assumedClasses) & INPUT_DEVICE_CLASS_JOYSTICK)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001330 device->classes = assumedClasses;
1331 break;
1332 }
1333 }
1334 }
1335
1336 // Check whether this device has switches.
1337 for (int i = 0; i <= SW_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07001338 if (device->swBitmask.test(i)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001339 device->classes |= INPUT_DEVICE_CLASS_SWITCH;
1340 break;
1341 }
1342 }
1343
1344 // Check whether this device supports the vibrator.
Chris Ye66fbac32020-07-06 20:36:43 -07001345 if (device->ffBitmask.test(FF_RUMBLE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001346 device->classes |= INPUT_DEVICE_CLASS_VIBRATOR;
1347 }
1348
1349 // Configure virtual keys.
1350 if ((device->classes & INPUT_DEVICE_CLASS_TOUCH)) {
1351 // Load the virtual keys for the touch screen, if any.
1352 // We do this now so that we can make sure to load the keymap if necessary.
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001353 bool success = loadVirtualKeyMapLocked(device);
1354 if (success) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001355 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1356 }
1357 }
1358
1359 // Load the key map.
1360 // We need to do this for joysticks too because the key layout may specify axes.
1361 status_t keyMapStatus = NAME_NOT_FOUND;
1362 if (device->classes & (INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_JOYSTICK)) {
1363 // Load the keymap for the device.
1364 keyMapStatus = loadKeyMapLocked(device);
1365 }
1366
1367 // Configure the keyboard, gamepad or virtual keyboard.
1368 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1369 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001370 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
1371 isEligibleBuiltInKeyboard(device->identifier, device->configuration, &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001372 mBuiltInKeyboardId = device->id;
1373 }
1374
1375 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
1376 if (hasKeycodeLocked(device, AKEYCODE_Q)) {
1377 device->classes |= INPUT_DEVICE_CLASS_ALPHAKEY;
1378 }
1379
1380 // See if this device has a DPAD.
1381 if (hasKeycodeLocked(device, AKEYCODE_DPAD_UP) &&
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001382 hasKeycodeLocked(device, AKEYCODE_DPAD_DOWN) &&
1383 hasKeycodeLocked(device, AKEYCODE_DPAD_LEFT) &&
1384 hasKeycodeLocked(device, AKEYCODE_DPAD_RIGHT) &&
1385 hasKeycodeLocked(device, AKEYCODE_DPAD_CENTER)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001386 device->classes |= INPUT_DEVICE_CLASS_DPAD;
1387 }
1388
1389 // See if this device has a gamepad.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001390 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES) / sizeof(GAMEPAD_KEYCODES[0]); i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001391 if (hasKeycodeLocked(device, GAMEPAD_KEYCODES[i])) {
1392 device->classes |= INPUT_DEVICE_CLASS_GAMEPAD;
1393 break;
1394 }
1395 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001396 }
1397
1398 // If the device isn't recognized as something we handle, don't monitor it.
1399 if (device->classes == 0) {
Chris Ye8594e192020-07-14 10:34:06 -07001400 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001401 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001402 delete device;
1403 return -1;
1404 }
1405
Tim Kilbourn063ff532015-04-08 10:26:18 -07001406 // Determine whether the device has a mic.
1407 if (deviceHasMicLocked(device)) {
1408 device->classes |= INPUT_DEVICE_CLASS_MIC;
1409 }
1410
Michael Wrightd02c5b62014-02-10 15:10:22 -08001411 // Determine whether the device is external or internal.
1412 if (isExternalDeviceLocked(device)) {
1413 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL;
1414 }
1415
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001416 if (device->classes & (INPUT_DEVICE_CLASS_JOYSTICK | INPUT_DEVICE_CLASS_DPAD) &&
1417 device->classes & INPUT_DEVICE_CLASS_GAMEPAD) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001418 device->controllerNumber = getNextControllerNumberLocked(device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001419 setLedForControllerLocked(device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001420 }
1421
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001422 // Find a matching video device by comparing device names
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001423 // This should be done before registerDeviceForEpollLocked, so that both fds are added to epoll
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001424 for (std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
1425 if (device->identifier.name == videoDevice->getName()) {
1426 device->videoDevice = std::move(videoDevice);
1427 break;
1428 }
1429 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001430 mUnattachedVideoDevices
1431 .erase(std::remove_if(mUnattachedVideoDevices.begin(), mUnattachedVideoDevices.end(),
1432 [](const std::unique_ptr<TouchVideoDevice>& videoDevice) {
1433 return videoDevice == nullptr;
1434 }),
1435 mUnattachedVideoDevices.end());
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001436
1437 if (registerDeviceForEpollLocked(device) != OK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001438 delete device;
1439 return -1;
1440 }
1441
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001442 configureFd(device);
1443
1444 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=0x%x, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001445 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Chris Ye8594e192020-07-14 10:34:06 -07001446 deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(), device->classes,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001447 device->configurationFile.c_str(), device->keyMap.keyLayoutFile.c_str(),
1448 device->keyMap.keyCharacterMapFile.c_str(), toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001449
1450 addDeviceLocked(device);
1451 return OK;
1452}
1453
1454void EventHub::configureFd(Device* device) {
1455 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
1456 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1457 // Disable kernel key repeat since we handle it ourselves
1458 unsigned int repeatRate[] = {0, 0};
1459 if (ioctl(device->fd, EVIOCSREP, repeatRate)) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001460 ALOGW("Unable to disable kernel key repeat for %s: %s", device->path.c_str(),
1461 strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001462 }
1463 }
1464
Michael Wrightd02c5b62014-02-10 15:10:22 -08001465 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
1466 // associated with input events. This is important because the input system
1467 // uses the timestamps extensively and assumes they were recorded using the monotonic
1468 // clock.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001469 int clockId = CLOCK_MONOTONIC;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001470 bool usingClockIoctl = !ioctl(device->fd, EVIOCSCLOCKID, &clockId);
Atif Niyaz4180aa42019-05-10 16:27:48 -07001471 ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001472}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001473
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001474void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
1475 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
1476 if (!videoDevice) {
1477 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
1478 return;
1479 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001480 // Transfer ownership of this video device to a matching input device
1481 for (size_t i = 0; i < mDevices.size(); i++) {
1482 Device* device = mDevices.valueAt(i);
1483 if (videoDevice->getName() == device->identifier.name) {
1484 device->videoDevice = std::move(videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001485 if (device->enabled) {
1486 registerVideoDeviceForEpollLocked(*device->videoDevice);
1487 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001488 return;
1489 }
1490 }
1491
1492 // Couldn't find a matching input device, so just add it to a temporary holding queue.
1493 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001494 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001495 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001496 mUnattachedVideoDevices.push_back(std::move(videoDevice));
1497}
1498
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001499bool EventHub::isDeviceEnabled(int32_t deviceId) {
1500 AutoMutex _l(mLock);
1501 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001502 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001503 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1504 return false;
1505 }
1506 return device->enabled;
1507}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001508
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001509status_t EventHub::enableDevice(int32_t deviceId) {
1510 AutoMutex _l(mLock);
1511 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001512 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001513 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1514 return BAD_VALUE;
1515 }
1516 if (device->enabled) {
1517 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
1518 return OK;
1519 }
1520 status_t result = device->enable();
1521 if (result != OK) {
1522 ALOGE("Failed to enable device %" PRId32, deviceId);
1523 return result;
1524 }
1525
1526 configureFd(device);
1527
1528 return registerDeviceForEpollLocked(device);
1529}
1530
1531status_t EventHub::disableDevice(int32_t deviceId) {
1532 AutoMutex _l(mLock);
1533 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001534 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001535 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1536 return BAD_VALUE;
1537 }
1538 if (!device->enabled) {
1539 ALOGW("Duplicate call to %s, input device already disabled", __func__);
1540 return OK;
1541 }
1542 unregisterDeviceFromEpollLocked(device);
1543 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001544}
1545
1546void EventHub::createVirtualKeyboardLocked() {
1547 InputDeviceIdentifier identifier;
1548 identifier.name = "Virtual";
1549 identifier.uniqueId = "<virtual>";
1550 assignDescriptorLocked(identifier);
1551
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001552 Device* device =
1553 new Device(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>", identifier);
1554 device->classes = INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_ALPHAKEY |
1555 INPUT_DEVICE_CLASS_DPAD | INPUT_DEVICE_CLASS_VIRTUAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001556 loadKeyMapLocked(device);
1557 addDeviceLocked(device);
1558}
1559
1560void EventHub::addDeviceLocked(Device* device) {
1561 mDevices.add(device->id, device);
1562 device->next = mOpeningDevices;
1563 mOpeningDevices = device;
1564}
1565
1566void EventHub::loadConfigurationLocked(Device* device) {
Chris Ye1d927aa2020-07-04 18:22:41 -07001567 device->configurationFile =
1568 getInputDeviceConfigurationFilePathByDeviceIdentifier(device->identifier,
1569 InputDeviceConfigurationFileType::
1570 CONFIGURATION);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001571 if (device->configurationFile.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001572 ALOGD("No input device configuration file found for device '%s'.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001573 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001574 } else {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001575 status_t status = PropertyMap::load(String8(device->configurationFile.c_str()),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001576 &device->configuration);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001577 if (status) {
1578 ALOGE("Error loading input device configuration file for device '%s'. "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001579 "Using default configuration.",
1580 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001581 }
1582 }
1583}
1584
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001585bool EventHub::loadVirtualKeyMapLocked(Device* device) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001586 // The virtual key map is supplied by the kernel as a system board property file.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001587 std::string path;
1588 path += "/sys/board_properties/virtualkeys.";
Siarhei Vishniakoub45635c2019-02-20 19:22:09 -06001589 path += device->identifier.getCanonicalName();
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001590 if (access(path.c_str(), R_OK)) {
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001591 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001592 }
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001593 device->virtualKeyMap = VirtualKeyMap::load(path);
1594 return device->virtualKeyMap != nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001595}
1596
1597status_t EventHub::loadKeyMapLocked(Device* device) {
1598 return device->keyMap.load(device->identifier, device->configuration);
1599}
1600
1601bool EventHub::isExternalDeviceLocked(Device* device) {
1602 if (device->configuration) {
1603 bool value;
1604 if (device->configuration->tryGetProperty(String8("device.internal"), value)) {
1605 return !value;
1606 }
1607 }
1608 return device->identifier.bus == BUS_USB || device->identifier.bus == BUS_BLUETOOTH;
1609}
1610
Tim Kilbourn063ff532015-04-08 10:26:18 -07001611bool EventHub::deviceHasMicLocked(Device* device) {
1612 if (device->configuration) {
1613 bool value;
1614 if (device->configuration->tryGetProperty(String8("audio.mic"), value)) {
1615 return value;
1616 }
1617 }
1618 return false;
1619}
1620
Michael Wrightd02c5b62014-02-10 15:10:22 -08001621int32_t EventHub::getNextControllerNumberLocked(Device* device) {
1622 if (mControllerNumbers.isFull()) {
1623 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001624 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001625 return 0;
1626 }
1627 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
1628 // one
1629 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
1630}
1631
1632void EventHub::releaseControllerNumberLocked(Device* device) {
1633 int32_t num = device->controllerNumber;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001634 device->controllerNumber = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001635 if (num == 0) {
1636 return;
1637 }
1638 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
1639}
1640
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001641void EventHub::setLedForControllerLocked(Device* device) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001642 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
1643 setLedStateLocked(device, ALED_CONTROLLER_1 + i, device->controllerNumber == i + 1);
1644 }
1645}
1646
1647bool EventHub::hasKeycodeLocked(Device* device, int keycode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001648 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001649 return false;
1650 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001651
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001652 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001653 device->keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes);
1654 const size_t N = scanCodes.size();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001655 for (size_t i = 0; i < N && i <= KEY_MAX; i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001656 int32_t sc = scanCodes[i];
Chris Ye66fbac32020-07-06 20:36:43 -07001657 if (sc >= 0 && sc <= KEY_MAX && device->keyBitmask.test(sc)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001658 return true;
1659 }
1660 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001661
Michael Wrightd02c5b62014-02-10 15:10:22 -08001662 return false;
1663}
1664
1665status_t EventHub::mapLed(Device* device, int32_t led, int32_t* outScanCode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001666 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001667 return NAME_NOT_FOUND;
1668 }
1669
1670 int32_t scanCode;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001671 if (device->keyMap.keyLayoutMap->findScanCodeForLed(led, &scanCode) != NAME_NOT_FOUND) {
Chris Ye66fbac32020-07-06 20:36:43 -07001672 if (scanCode >= 0 && scanCode <= LED_MAX && device->ledBitmask.test(scanCode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001673 *outScanCode = scanCode;
1674 return NO_ERROR;
1675 }
1676 }
1677 return NAME_NOT_FOUND;
1678}
1679
Chris Ye8594e192020-07-14 10:34:06 -07001680void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001681 Device* device = getDeviceByPathLocked(devicePath);
1682 if (device) {
1683 closeDeviceLocked(device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001684 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001685 }
Chris Ye8594e192020-07-14 10:34:06 -07001686 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001687}
1688
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001689/**
1690 * Find the video device by filename, and close it.
1691 * The video device is closed by path during an inotify event, where we don't have the
1692 * additional context about the video device fd, or the associated input device.
1693 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001694void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001695 // A video device may be owned by an existing input device, or it may be stored in
1696 // the mUnattachedVideoDevices queue. Check both locations.
1697 for (size_t i = 0; i < mDevices.size(); i++) {
1698 Device* device = mDevices.valueAt(i);
1699 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001700 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001701 device->videoDevice = nullptr;
1702 return;
1703 }
1704 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001705 mUnattachedVideoDevices
1706 .erase(std::remove_if(mUnattachedVideoDevices.begin(), mUnattachedVideoDevices.end(),
1707 [&devicePath](
1708 const std::unique_ptr<TouchVideoDevice>& videoDevice) {
1709 return videoDevice->getPath() == devicePath;
1710 }),
1711 mUnattachedVideoDevices.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001712}
1713
1714void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001715 mUnattachedVideoDevices.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001716 while (mDevices.size() > 0) {
1717 closeDeviceLocked(mDevices.valueAt(mDevices.size() - 1));
1718 }
1719}
1720
1721void EventHub::closeDeviceLocked(Device* device) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001722 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=0x%x", device->path.c_str(),
1723 device->identifier.name.c_str(), device->id, device->fd, device->classes);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001724
1725 if (device->id == mBuiltInKeyboardId) {
1726 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001727 device->path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001728 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
1729 }
1730
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001731 unregisterDeviceFromEpollLocked(device);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001732 if (device->videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001733 // This must be done after the video device is removed from epoll
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001734 mUnattachedVideoDevices.push_back(std::move(device->videoDevice));
1735 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001736
1737 releaseControllerNumberLocked(device);
1738
1739 mDevices.removeItem(device->id);
1740 device->close();
1741
1742 // Unlink for opening devices list if it is present.
Yi Kong9b14ac62018-07-17 13:48:38 -07001743 Device* pred = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001744 bool found = false;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001745 for (Device* entry = mOpeningDevices; entry != nullptr;) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001746 if (entry == device) {
1747 found = true;
1748 break;
1749 }
1750 pred = entry;
1751 entry = entry->next;
1752 }
1753 if (found) {
1754 // Unlink the device from the opening devices list then delete it.
1755 // We don't need to tell the client that the device was closed because
1756 // it does not even know it was opened in the first place.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001757 ALOGI("Device %s was immediately closed after opening.", device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001758 if (pred) {
1759 pred->next = device->next;
1760 } else {
1761 mOpeningDevices = device->next;
1762 }
1763 delete device;
1764 } else {
1765 // Link into closing devices list.
1766 // The device will be deleted later after we have informed the client.
1767 device->next = mClosingDevices;
1768 mClosingDevices = device;
1769 }
1770}
1771
1772status_t EventHub::readNotifyLocked() {
1773 int res;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001774 char event_buf[512];
1775 int event_size;
1776 int event_pos = 0;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001777 struct inotify_event* event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001778
1779 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
1780 res = read(mINotifyFd, event_buf, sizeof(event_buf));
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001781 if (res < (int)sizeof(*event)) {
1782 if (errno == EINTR) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001783 ALOGW("could not get event, %s\n", strerror(errno));
1784 return -1;
1785 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001786
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001787 while (res >= (int)sizeof(*event)) {
1788 event = (struct inotify_event*)(event_buf + event_pos);
1789 if (event->len) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001790 if (event->wd == mInputWd) {
Chris Ye8594e192020-07-14 10:34:06 -07001791 std::string filename = std::string(DEVICE_PATH) + "/" + event->name;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001792 if (event->mask & IN_CREATE) {
Chris Ye8594e192020-07-14 10:34:06 -07001793 openDeviceLocked(filename);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001794 } else {
1795 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
Chris Ye8594e192020-07-14 10:34:06 -07001796 closeDeviceByPathLocked(filename);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001797 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001798 } else if (event->wd == mVideoWd) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001799 if (isV4lTouchNode(event->name)) {
Chris Ye8594e192020-07-14 10:34:06 -07001800 std::string filename = std::string(VIDEO_DEVICE_PATH) + "/" + event->name;
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001801 if (event->mask & IN_CREATE) {
1802 openVideoDeviceLocked(filename);
1803 } else {
1804 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
1805 closeVideoDeviceByPathLocked(filename);
1806 }
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001807 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001808 } else {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001809 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event->wd);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001810 }
1811 }
1812 event_size = sizeof(*event) + event->len;
1813 res -= event_size;
1814 event_pos += event_size;
1815 }
1816 return 0;
1817}
1818
Chris Ye8594e192020-07-14 10:34:06 -07001819status_t EventHub::scanDirLocked(const std::string& dirname) {
1820 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
1821 openDeviceLocked(entry.path());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001822 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001823 return 0;
1824}
1825
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001826/**
1827 * Look for all dirname/v4l-touch* devices, and open them.
1828 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001829status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Chris Ye8594e192020-07-14 10:34:06 -07001830 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
1831 if (isV4lTouchNode(entry.path())) {
1832 ALOGI("Found touch video device %s", entry.path().c_str());
1833 openVideoDeviceLocked(entry.path());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001834 }
1835 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001836 return OK;
1837}
1838
Michael Wrightd02c5b62014-02-10 15:10:22 -08001839void EventHub::requestReopenDevices() {
1840 ALOGV("requestReopenDevices() called");
1841
1842 AutoMutex _l(mLock);
1843 mNeedToReopenDevices = true;
1844}
1845
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001846void EventHub::dump(std::string& dump) {
1847 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001848
1849 { // acquire lock
1850 AutoMutex _l(mLock);
1851
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001852 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001853
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001854 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001855
1856 for (size_t i = 0; i < mDevices.size(); i++) {
1857 const Device* device = mDevices.valueAt(i);
1858 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001859 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001860 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001861 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001862 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001863 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001864 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001865 dump += StringPrintf(INDENT3 "Classes: 0x%08x\n", device->classes);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001866 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001867 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001868 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
1869 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001870 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001871 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001872 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001873 "product=0x%04x, version=0x%04x\n",
1874 device->identifier.bus, device->identifier.vendor,
1875 device->identifier.product, device->identifier.version);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001876 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001877 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001878 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001879 device->keyMap.keyCharacterMapFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001880 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001881 device->configurationFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001882 dump += StringPrintf(INDENT3 "HaveKeyboardLayoutOverlay: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001883 toString(device->overlayKeyMap != nullptr));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001884 dump += INDENT3 "VideoDevice: ";
1885 if (device->videoDevice) {
1886 dump += device->videoDevice->dump() + "\n";
1887 } else {
1888 dump += "<none>\n";
1889 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001890 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001891
1892 dump += INDENT "Unattached video devices:\n";
1893 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
1894 dump += INDENT2 + videoDevice->dump() + "\n";
1895 }
1896 if (mUnattachedVideoDevices.empty()) {
1897 dump += INDENT2 "<none>\n";
1898 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001899 } // release lock
1900}
1901
1902void EventHub::monitor() {
1903 // Acquire and release the lock to ensure that the event hub has not deadlocked.
1904 mLock.lock();
1905 mLock.unlock();
1906}
1907
Michael Wrightd02c5b62014-02-10 15:10:22 -08001908}; // namespace android