blob: f19d3e5848db0904a072f3f3ef6e15cc7ed6eff5 [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;
Chris Ye1b0c7342020-07-28 21:57:03 -070056using namespace android::flag_operators;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080057
Michael Wrightd02c5b62014-02-10 15:10:22 -080058namespace android {
59
Siarhei Vishniakou25920312018-12-12 15:24:44 -080060static constexpr bool DEBUG = false;
61
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070062static const char* DEVICE_PATH = "/dev/input";
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080063// v4l2 devices go directly into /dev
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070064static const char* VIDEO_DEVICE_PATH = "/dev";
Michael Wrightd02c5b62014-02-10 15:10:22 -080065
Michael Wrightd02c5b62014-02-10 15:10:22 -080066static inline const char* toString(bool value) {
67 return value ? "true" : "false";
68}
69
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010070static std::string sha1(const std::string& in) {
Dan Albert677d87e2014-06-16 17:31:28 -070071 SHA_CTX ctx;
72 SHA1_Init(&ctx);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010073 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
Dan Albert677d87e2014-06-16 17:31:28 -070074 u_char digest[SHA_DIGEST_LENGTH];
75 SHA1_Final(digest, &ctx);
Michael Wrightd02c5b62014-02-10 15:10:22 -080076
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010077 std::string out;
Dan Albert677d87e2014-06-16 17:31:28 -070078 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010079 out += StringPrintf("%02x", digest[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -080080 }
81 return out;
82}
83
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080084/**
85 * Return true if name matches "v4l-touch*"
86 */
Chris Ye8594e192020-07-14 10:34:06 -070087static bool isV4lTouchNode(std::string name) {
88 return name.find("v4l-touch") != std::string::npos;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080089}
90
Philip Quinn39b81682019-01-09 22:20:39 -080091/**
92 * Returns true if V4L devices should be scanned.
93 *
94 * The system property ro.input.video_enabled can be used to control whether
95 * EventHub scans and opens V4L devices. As V4L does not support multiple
96 * clients, EventHub effectively blocks access to these devices when it opens
Siarhei Vishniakou29f88492019-04-05 14:11:43 -070097 * them.
98 *
99 * Setting this to "false" would prevent any video devices from being discovered and
100 * associated with input devices.
101 *
102 * This property can be used as follows:
103 * 1. To turn off features that are dependent on video device presence.
104 * 2. During testing and development, to allow other clients to read video devices
105 * directly from /dev.
Philip Quinn39b81682019-01-09 22:20:39 -0800106 */
107static bool isV4lScanningEnabled() {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700108 return property_get_bool("ro.input.video_enabled", true /* default_value */);
Philip Quinn39b81682019-01-09 22:20:39 -0800109}
110
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800111static nsecs_t processEventTimestamp(const struct input_event& event) {
112 // Use the time specified in the event instead of the current time
113 // so that downstream code can get more accurate estimates of
114 // event dispatch latency from the time the event is enqueued onto
115 // the evdev client buffer.
116 //
117 // The event's timestamp fortuitously uses the same monotonic clock
118 // time base as the rest of Android. The kernel event device driver
119 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
120 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
121 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
122 // system call that also queries ktime_get_ts().
123
124 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.time.tv_sec) +
125 microseconds_to_nanoseconds(event.time.tv_usec);
126 return inputEventTime;
127}
128
Michael Wrightd02c5b62014-02-10 15:10:22 -0800129// --- Global Functions ---
130
Chris Ye1b0c7342020-07-28 21:57:03 -0700131Flags<InputDeviceClass> getAbsAxisUsage(int32_t axis, Flags<InputDeviceClass> deviceClasses) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800132 // Touch devices get dibs on touch-related axes.
Chris Ye1b0c7342020-07-28 21:57:03 -0700133 if (deviceClasses.test(InputDeviceClass::TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800134 switch (axis) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700135 case ABS_X:
136 case ABS_Y:
137 case ABS_PRESSURE:
138 case ABS_TOOL_WIDTH:
139 case ABS_DISTANCE:
140 case ABS_TILT_X:
141 case ABS_TILT_Y:
142 case ABS_MT_SLOT:
143 case ABS_MT_TOUCH_MAJOR:
144 case ABS_MT_TOUCH_MINOR:
145 case ABS_MT_WIDTH_MAJOR:
146 case ABS_MT_WIDTH_MINOR:
147 case ABS_MT_ORIENTATION:
148 case ABS_MT_POSITION_X:
149 case ABS_MT_POSITION_Y:
150 case ABS_MT_TOOL_TYPE:
151 case ABS_MT_BLOB_ID:
152 case ABS_MT_TRACKING_ID:
153 case ABS_MT_PRESSURE:
154 case ABS_MT_DISTANCE:
Chris Ye1b0c7342020-07-28 21:57:03 -0700155 return InputDeviceClass::TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800156 }
157 }
158
Michael Wright842500e2015-03-13 17:32:02 -0700159 // External stylus gets the pressure axis
Chris Ye1b0c7342020-07-28 21:57:03 -0700160 if (deviceClasses.test(InputDeviceClass::EXTERNAL_STYLUS)) {
Michael Wright842500e2015-03-13 17:32:02 -0700161 if (axis == ABS_PRESSURE) {
Chris Ye1b0c7342020-07-28 21:57:03 -0700162 return InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -0700163 }
164 }
165
Michael Wrightd02c5b62014-02-10 15:10:22 -0800166 // Joystick devices get the rest.
Chris Ye1b0c7342020-07-28 21:57:03 -0700167 return deviceClasses & InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800168}
169
170// --- EventHub::Device ---
171
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100172EventHub::Device::Device(int fd, int32_t id, const std::string& path,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700173 const InputDeviceIdentifier& identifier)
174 : next(nullptr),
175 fd(fd),
176 id(id),
177 path(path),
178 identifier(identifier),
179 classes(0),
180 configuration(nullptr),
181 virtualKeyMap(nullptr),
182 ffEffectPlaying(false),
183 ffEffectId(-1),
184 controllerNumber(0),
185 enabled(true),
Chris Ye66fbac32020-07-06 20:36:43 -0700186 isVirtual(fd < 0) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800187
188EventHub::Device::~Device() {
189 close();
190 delete configuration;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800191}
192
193void EventHub::Device::close() {
194 if (fd >= 0) {
195 ::close(fd);
196 fd = -1;
197 }
198}
199
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700200status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100201 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700202 if (fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100203 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700204 return -errno;
205 }
206 enabled = true;
207 return OK;
208}
209
210status_t EventHub::Device::disable() {
211 close();
212 enabled = false;
213 return OK;
214}
215
216bool EventHub::Device::hasValidFd() {
217 return !isVirtual && enabled;
218}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800219
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100220/**
221 * Get the capabilities for the current process.
222 * Crashes the system if unable to create / check / destroy the capabilities object.
223 */
224class Capabilities final {
225public:
226 explicit Capabilities() {
227 mCaps = cap_get_proc();
228 LOG_ALWAYS_FATAL_IF(mCaps == nullptr, "Could not get capabilities of the current process");
229 }
230
231 /**
232 * Check whether the current process has a specific capability
233 * in the set of effective capabilities.
234 * Return CAP_SET if the process has the requested capability
235 * Return CAP_CLEAR otherwise.
236 */
237 cap_flag_value_t checkEffectiveCapability(cap_value_t capability) {
238 cap_flag_value_t value;
239 const int result = cap_get_flag(mCaps, capability, CAP_EFFECTIVE, &value);
240 LOG_ALWAYS_FATAL_IF(result == -1, "Could not obtain the requested capability");
241 return value;
242 }
243
244 ~Capabilities() {
245 const int result = cap_free(mCaps);
246 LOG_ALWAYS_FATAL_IF(result == -1, "Could not release the capabilities structure");
247 }
248
249private:
250 cap_t mCaps;
251};
252
253static void ensureProcessCanBlockSuspend() {
254 Capabilities capabilities;
255 const bool canBlockSuspend =
256 capabilities.checkEffectiveCapability(CAP_BLOCK_SUSPEND) == CAP_SET;
257 LOG_ALWAYS_FATAL_IF(!canBlockSuspend,
258 "Input must be able to block suspend to properly process events");
259}
260
Michael Wrightd02c5b62014-02-10 15:10:22 -0800261// --- EventHub ---
262
Michael Wrightd02c5b62014-02-10 15:10:22 -0800263const int EventHub::EPOLL_MAX_EVENTS;
264
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700265EventHub::EventHub(void)
266 : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
267 mNextDeviceId(1),
268 mControllerNumbers(),
269 mOpeningDevices(nullptr),
270 mClosingDevices(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800271 mNeedToSendFinishedDeviceScan(false),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700272 mNeedToReopenDevices(false),
273 mNeedToScanDevices(true),
274 mPendingEventCount(0),
275 mPendingEventIndex(0),
276 mPendingINotify(false) {
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100277 ensureProcessCanBlockSuspend();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800278
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800279 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800280 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800281
282 mINotifyFd = inotify_init();
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800283 mInputWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700284 LOG_ALWAYS_FATAL_IF(mInputWd < 0, "Could not register INotify for %s: %s", DEVICE_PATH,
285 strerror(errno));
Philip Quinn39b81682019-01-09 22:20:39 -0800286 if (isV4lScanningEnabled()) {
287 mVideoWd = inotify_add_watch(mINotifyFd, VIDEO_DEVICE_PATH, IN_DELETE | IN_CREATE);
288 LOG_ALWAYS_FATAL_IF(mVideoWd < 0, "Could not register INotify for %s: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700289 VIDEO_DEVICE_PATH, strerror(errno));
Philip Quinn39b81682019-01-09 22:20:39 -0800290 } else {
291 mVideoWd = -1;
292 ALOGI("Video device scanning disabled");
293 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800294
Siarhei Vishniakou2d0e9482019-09-24 12:52:47 +0100295 struct epoll_event eventItem = {};
296 eventItem.events = EPOLLIN | EPOLLWAKEUP;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700297 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800298 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800299 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
300
301 int wakeFds[2];
302 result = pipe(wakeFds);
303 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
304
305 mWakeReadPipeFd = wakeFds[0];
306 mWakeWritePipeFd = wakeFds[1];
307
308 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
309 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700310 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800311
312 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
313 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700314 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800315
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700316 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800317 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
318 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700319 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800320}
321
322EventHub::~EventHub(void) {
323 closeAllDevicesLocked();
324
325 while (mClosingDevices) {
326 Device* device = mClosingDevices;
327 mClosingDevices = device->next;
328 delete device;
329 }
330
331 ::close(mEpollFd);
332 ::close(mINotifyFd);
333 ::close(mWakeReadPipeFd);
334 ::close(mWakeWritePipeFd);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800335}
336
337InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
338 AutoMutex _l(mLock);
339 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700340 if (device == nullptr) return InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800341 return device->identifier;
342}
343
Chris Ye1b0c7342020-07-28 21:57:03 -0700344Flags<InputDeviceClass> EventHub::getDeviceClasses(int32_t deviceId) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800345 AutoMutex _l(mLock);
346 Device* device = getDeviceLocked(deviceId);
Chris Ye1b0c7342020-07-28 21:57:03 -0700347 if (device == nullptr) {
348 return Flags<InputDeviceClass>(0);
349 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800350 return device->classes;
351}
352
353int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
354 AutoMutex _l(mLock);
355 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700356 if (device == nullptr) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800357 return device->controllerNumber;
358}
359
360void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
361 AutoMutex _l(mLock);
362 Device* device = getDeviceLocked(deviceId);
363 if (device && device->configuration) {
364 *outConfiguration = *device->configuration;
365 } else {
366 outConfiguration->clear();
367 }
368}
369
370status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700371 RawAbsoluteAxisInfo* outAxisInfo) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800372 outAxisInfo->clear();
373
374 if (axis >= 0 && axis <= ABS_MAX) {
375 AutoMutex _l(mLock);
376
377 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700378 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800379 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700380 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
381 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
382 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800383 return -errno;
384 }
385
386 if (info.minimum != info.maximum) {
387 outAxisInfo->valid = true;
388 outAxisInfo->minValue = info.minimum;
389 outAxisInfo->maxValue = info.maximum;
390 outAxisInfo->flat = info.flat;
391 outAxisInfo->fuzz = info.fuzz;
392 outAxisInfo->resolution = info.resolution;
393 }
394 return OK;
395 }
396 }
397 return -1;
398}
399
400bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
401 if (axis >= 0 && axis <= REL_MAX) {
402 AutoMutex _l(mLock);
403
404 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700405 return device != nullptr ? device->relBitmask.test(axis) : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800406 }
407 return false;
408}
409
410bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
411 if (property >= 0 && property <= INPUT_PROP_MAX) {
412 AutoMutex _l(mLock);
413
414 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700415 return device != nullptr ? device->propBitmask.test(property) : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800416 }
417 return false;
418}
419
420int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
421 if (scanCode >= 0 && scanCode <= KEY_MAX) {
422 AutoMutex _l(mLock);
423
424 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700425 if (device != nullptr && device->hasValidFd() && device->keyBitmask.test(scanCode)) {
426 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
427 return device->keyState.test(scanCode) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800428 }
429 }
430 }
431 return AKEY_STATE_UNKNOWN;
432}
433
434int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
435 AutoMutex _l(mLock);
436
437 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700438 if (device != nullptr && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800439 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800440 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode, &scanCodes);
441 if (scanCodes.size() != 0) {
Chris Ye66fbac32020-07-06 20:36:43 -0700442 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800443 for (size_t i = 0; i < scanCodes.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800444 int32_t sc = scanCodes[i];
Chris Ye66fbac32020-07-06 20:36:43 -0700445 if (sc >= 0 && sc <= KEY_MAX && device->keyState.test(sc)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800446 return AKEY_STATE_DOWN;
447 }
448 }
449 return AKEY_STATE_UP;
450 }
451 }
452 }
453 return AKEY_STATE_UNKNOWN;
454}
455
456int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
457 if (sw >= 0 && sw <= SW_MAX) {
458 AutoMutex _l(mLock);
459
460 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700461 if (device != nullptr && device->hasValidFd() && device->swBitmask.test(sw)) {
462 if (device->readDeviceBitMask(EVIOCGSW(0), device->swState) >= 0) {
463 return device->swState.test(sw) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800464 }
465 }
466 }
467 return AKEY_STATE_UNKNOWN;
468}
469
470status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
471 *outValue = 0;
472
473 if (axis >= 0 && axis <= ABS_MAX) {
474 AutoMutex _l(mLock);
475
476 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700477 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800478 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700479 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
480 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
481 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800482 return -errno;
483 }
484
485 *outValue = info.value;
486 return OK;
487 }
488 }
489 return -1;
490}
491
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700492bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes, const int32_t* keyCodes,
493 uint8_t* outFlags) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800494 AutoMutex _l(mLock);
495
496 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700497 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800498 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800499 for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) {
500 scanCodes.clear();
501
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700502 status_t err = device->keyMap.keyLayoutMap->findScanCodesForKey(keyCodes[codeIndex],
503 &scanCodes);
504 if (!err) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800505 // check the possible scan codes identified by the layout map against the
506 // map of codes actually emitted by the driver
507 for (size_t sc = 0; sc < scanCodes.size(); sc++) {
Chris Ye66fbac32020-07-06 20:36:43 -0700508 if (device->keyBitmask.test(scanCodes[sc])) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800509 outFlags[codeIndex] = 1;
510 break;
511 }
512 }
513 }
514 }
515 return true;
516 }
517 return false;
518}
519
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700520status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
521 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800522 AutoMutex _l(mLock);
523 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700524 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800525
Chris Ye66fbac32020-07-06 20:36:43 -0700526 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800527 // Check the key character map first.
528 sp<KeyCharacterMap> kcm = device->getKeyCharacterMap();
Yi Kong9b14ac62018-07-17 13:48:38 -0700529 if (kcm != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800530 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
531 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700532 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800533 }
534 }
535
536 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700537 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800538 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700539 status = NO_ERROR;
540 }
541 }
542
543 if (status == NO_ERROR) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700544 if (kcm != nullptr) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700545 kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState);
546 } else {
547 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800548 }
549 }
550 }
551
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700552 if (status != NO_ERROR) {
553 *outKeycode = 0;
554 *outFlags = 0;
555 *outMetaState = metaState;
556 }
557
558 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800559}
560
561status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
562 AutoMutex _l(mLock);
563 Device* device = getDeviceLocked(deviceId);
564
Chris Ye66fbac32020-07-06 20:36:43 -0700565 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800566 status_t err = device->keyMap.keyLayoutMap->mapAxis(scanCode, outAxisInfo);
567 if (err == NO_ERROR) {
568 return NO_ERROR;
569 }
570 }
571
572 return NAME_NOT_FOUND;
573}
574
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100575void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800576 AutoMutex _l(mLock);
577
578 mExcludedDevices = devices;
579}
580
581bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
582 AutoMutex _l(mLock);
583 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700584 if (device != nullptr && scanCode >= 0 && scanCode <= KEY_MAX) {
585 return device->keyBitmask.test(scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800586 }
587 return false;
588}
589
590bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
591 AutoMutex _l(mLock);
592 Device* device = getDeviceLocked(deviceId);
593 int32_t sc;
Chris Ye66fbac32020-07-06 20:36:43 -0700594 if (device != nullptr && mapLed(device, led, &sc) == NO_ERROR) {
595 return device->ledBitmask.test(sc);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800596 }
597 return false;
598}
599
600void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
601 AutoMutex _l(mLock);
602 Device* device = getDeviceLocked(deviceId);
603 setLedStateLocked(device, led, on);
604}
605
606void EventHub::setLedStateLocked(Device* device, int32_t led, bool on) {
607 int32_t sc;
Chris Ye66fbac32020-07-06 20:36:43 -0700608 if (device != nullptr && device->hasValidFd() && mapLed(device, led, &sc) != NAME_NOT_FOUND) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800609 struct input_event ev;
610 ev.time.tv_sec = 0;
611 ev.time.tv_usec = 0;
612 ev.type = EV_LED;
613 ev.code = sc;
614 ev.value = on ? 1 : 0;
615
616 ssize_t nWrite;
617 do {
618 nWrite = write(device->fd, &ev, sizeof(struct input_event));
619 } while (nWrite == -1 && errno == EINTR);
620 }
621}
622
623void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700624 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800625 outVirtualKeys.clear();
626
627 AutoMutex _l(mLock);
628 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700629 if (device != nullptr && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800630 const std::vector<VirtualKeyDefinition> virtualKeys =
631 device->virtualKeyMap->getVirtualKeys();
632 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800633 }
634}
635
636sp<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
637 AutoMutex _l(mLock);
638 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700639 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800640 return device->getKeyCharacterMap();
641 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700642 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800643}
644
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700645bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, const sp<KeyCharacterMap>& map) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800646 AutoMutex _l(mLock);
647 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700648 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800649 if (map != device->overlayKeyMap) {
650 device->overlayKeyMap = map;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700651 device->combinedKeyMap = KeyCharacterMap::combine(device->keyMap.keyCharacterMap, map);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800652 return true;
653 }
654 }
655 return false;
656}
657
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100658static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
659 std::string rawDescriptor;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700660 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800661 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100662 if (!identifier.uniqueId.empty()) {
663 rawDescriptor += "uniqueId:";
664 rawDescriptor += identifier.uniqueId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800665 } else if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100666 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800667 }
668
669 if (identifier.vendor == 0 && identifier.product == 0) {
670 // If we don't know the vendor and product id, then the device is probably
671 // built-in so we need to rely on other information to uniquely identify
672 // the input device. Usually we try to avoid relying on the device name or
673 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100674 if (!identifier.name.empty()) {
675 rawDescriptor += "name:";
676 rawDescriptor += identifier.name;
677 } else if (!identifier.location.empty()) {
678 rawDescriptor += "location:";
679 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800680 }
681 }
682 identifier.descriptor = sha1(rawDescriptor);
683 return rawDescriptor;
684}
685
686void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
687 // Compute a device descriptor that uniquely identifies the device.
688 // The descriptor is assumed to be a stable identifier. Its value should not
689 // change between reboots, reconnections, firmware updates or new releases
690 // of Android. In practice we sometimes get devices that cannot be uniquely
691 // identified. In this case we enforce uniqueness between connected devices.
692 // Ideally, we also want the descriptor to be short and relatively opaque.
693
694 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100695 std::string rawDescriptor = generateDescriptor(identifier);
696 if (identifier.uniqueId.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800697 // If it didn't have a unique id check for conflicts and enforce
698 // uniqueness if necessary.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700699 while (getDeviceByDescriptorLocked(identifier.descriptor) != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800700 identifier.nonce++;
701 rawDescriptor = generateDescriptor(identifier);
702 }
703 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100704 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700705 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800706}
707
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +0000708void EventHub::vibrate(int32_t deviceId, const VibrationElement& element) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800709 AutoMutex _l(mLock);
710 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700711 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800712 ff_effect effect;
713 memset(&effect, 0, sizeof(effect));
714 effect.type = FF_RUMBLE;
715 effect.id = device->ffEffectId;
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +0000716 // evdev FF_RUMBLE effect only supports two channels of vibration.
717 effect.u.rumble.strong_magnitude = element.getChannel(0);
718 effect.u.rumble.weak_magnitude = element.getChannel(1);
719 effect.replay.length = element.duration.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800720 effect.replay.delay = 0;
721 if (ioctl(device->fd, EVIOCSFF, &effect)) {
722 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700723 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800724 return;
725 }
726 device->ffEffectId = effect.id;
727
728 struct input_event ev;
729 ev.time.tv_sec = 0;
730 ev.time.tv_usec = 0;
731 ev.type = EV_FF;
732 ev.code = device->ffEffectId;
733 ev.value = 1;
734 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
735 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700736 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800737 return;
738 }
739 device->ffEffectPlaying = true;
740 }
741}
742
743void EventHub::cancelVibrate(int32_t deviceId) {
744 AutoMutex _l(mLock);
745 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700746 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800747 if (device->ffEffectPlaying) {
748 device->ffEffectPlaying = false;
749
750 struct input_event ev;
751 ev.time.tv_sec = 0;
752 ev.time.tv_usec = 0;
753 ev.type = EV_FF;
754 ev.code = device->ffEffectId;
755 ev.value = 0;
756 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
757 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700758 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800759 return;
760 }
761 }
762 }
763}
764
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100765EventHub::Device* EventHub::getDeviceByDescriptorLocked(const std::string& descriptor) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800766 size_t size = mDevices.size();
767 for (size_t i = 0; i < size; i++) {
768 Device* device = mDevices.valueAt(i);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100769 if (descriptor == device->identifier.descriptor) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800770 return device;
771 }
772 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700773 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800774}
775
776EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -0800777 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800778 deviceId = mBuiltInKeyboardId;
779 }
780 ssize_t index = mDevices.indexOfKey(deviceId);
781 return index >= 0 ? mDevices.valueAt(index) : NULL;
782}
783
Chris Ye8594e192020-07-14 10:34:06 -0700784EventHub::Device* EventHub::getDeviceByPathLocked(const std::string& devicePath) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800785 for (size_t i = 0; i < mDevices.size(); i++) {
786 Device* device = mDevices.valueAt(i);
787 if (device->path == devicePath) {
788 return device;
789 }
790 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700791 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800792}
793
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700794/**
795 * The file descriptor could be either input device, or a video device (associated with a
796 * specific input device). Check both cases here, and return the device that this event
797 * belongs to. Caller can compare the fd's once more to determine event type.
798 * Looks through all input devices, and only attached video devices. Unattached video
799 * devices are ignored.
800 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700801EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
802 for (size_t i = 0; i < mDevices.size(); i++) {
803 Device* device = mDevices.valueAt(i);
804 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700805 // This is an input device event
806 return device;
807 }
808 if (device->videoDevice && device->videoDevice->getFd() == fd) {
809 // This is a video device event
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700810 return device;
811 }
812 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700813 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
814 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700815 return nullptr;
816}
817
Michael Wrightd02c5b62014-02-10 15:10:22 -0800818size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
819 ALOG_ASSERT(bufferSize >= 1);
820
821 AutoMutex _l(mLock);
822
823 struct input_event readBuffer[bufferSize];
824
825 RawEvent* event = buffer;
826 size_t capacity = bufferSize;
827 bool awoken = false;
828 for (;;) {
829 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
830
831 // Reopen input devices if needed.
832 if (mNeedToReopenDevices) {
833 mNeedToReopenDevices = false;
834
835 ALOGI("Reopening all input devices due to a configuration change.");
836
837 closeAllDevicesLocked();
838 mNeedToScanDevices = true;
839 break; // return to the caller before we actually rescan
840 }
841
842 // Report any devices that had last been added/removed.
843 while (mClosingDevices) {
844 Device* device = mClosingDevices;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700845 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800846 mClosingDevices = device->next;
847 event->when = now;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700848 event->deviceId = (device->id == mBuiltInKeyboardId)
849 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
850 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800851 event->type = DEVICE_REMOVED;
852 event += 1;
853 delete device;
854 mNeedToSendFinishedDeviceScan = true;
855 if (--capacity == 0) {
856 break;
857 }
858 }
859
860 if (mNeedToScanDevices) {
861 mNeedToScanDevices = false;
862 scanDevicesLocked();
863 mNeedToSendFinishedDeviceScan = true;
864 }
865
Yi Kong9b14ac62018-07-17 13:48:38 -0700866 while (mOpeningDevices != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800867 Device* device = mOpeningDevices;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700868 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800869 mOpeningDevices = device->next;
870 event->when = now;
871 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
872 event->type = DEVICE_ADDED;
873 event += 1;
874 mNeedToSendFinishedDeviceScan = true;
875 if (--capacity == 0) {
876 break;
877 }
878 }
879
880 if (mNeedToSendFinishedDeviceScan) {
881 mNeedToSendFinishedDeviceScan = false;
882 event->when = now;
883 event->type = FINISHED_DEVICE_SCAN;
884 event += 1;
885 if (--capacity == 0) {
886 break;
887 }
888 }
889
890 // Grab the next input event.
891 bool deviceChanged = false;
892 while (mPendingEventIndex < mPendingEventCount) {
893 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700894 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800895 if (eventItem.events & EPOLLIN) {
896 mPendingINotify = true;
897 } else {
898 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
899 }
900 continue;
901 }
902
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700903 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904 if (eventItem.events & EPOLLIN) {
905 ALOGV("awoken after wake()");
906 awoken = true;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -0500907 char wakeReadBuffer[16];
Michael Wrightd02c5b62014-02-10 15:10:22 -0800908 ssize_t nRead;
909 do {
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -0500910 nRead = read(mWakeReadPipeFd, wakeReadBuffer, sizeof(wakeReadBuffer));
911 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(wakeReadBuffer));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800912 } else {
913 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700914 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800915 }
916 continue;
917 }
918
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700919 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700920 if (!device) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700921 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
922 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700923 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800924 continue;
925 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700926 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
927 if (eventItem.events & EPOLLIN) {
928 size_t numFrames = device->videoDevice->readAndQueueFrames();
929 if (numFrames == 0) {
930 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700931 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700932 }
933 } else if (eventItem.events & EPOLLHUP) {
934 // TODO(b/121395353) - consider adding EPOLLRDHUP
935 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700936 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700937 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
938 device->videoDevice = nullptr;
939 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700940 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
941 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700942 ALOG_ASSERT(!DEBUG);
943 }
944 continue;
945 }
946 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -0800947 if (eventItem.events & EPOLLIN) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700948 int32_t readSize =
949 read(device->fd, readBuffer, sizeof(struct input_event) * capacity);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800950 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
951 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -0700952 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700953 " bufferSize: %zu capacity: %zu errno: %d)\n",
954 device->fd, readSize, bufferSize, capacity, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800955 deviceChanged = true;
956 closeDeviceLocked(device);
957 } else if (readSize < 0) {
958 if (errno != EAGAIN && errno != EINTR) {
959 ALOGW("could not get event (errno=%d)", errno);
960 }
961 } else if ((readSize % sizeof(struct input_event)) != 0) {
962 ALOGE("could not get event (wrong size: %d)", readSize);
963 } else {
964 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
965
966 size_t count = size_t(readSize) / sizeof(struct input_event);
967 for (size_t i = 0; i < count; i++) {
968 struct input_event& iev = readBuffer[i];
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800969 event->when = processEventTimestamp(iev);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800970 event->deviceId = deviceId;
971 event->type = iev.type;
972 event->code = iev.code;
973 event->value = iev.value;
974 event += 1;
975 capacity -= 1;
976 }
977 if (capacity == 0) {
978 // The result buffer is full. Reset the pending event index
979 // so we will try to read the device again on the next iteration.
980 mPendingEventIndex -= 1;
981 break;
982 }
983 }
984 } else if (eventItem.events & EPOLLHUP) {
985 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700986 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800987 deviceChanged = true;
988 closeDeviceLocked(device);
989 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700990 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
991 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800992 }
993 }
994
995 // readNotify() will modify the list of devices so this must be done after
996 // processing all other events to ensure that we read all remaining events
997 // before closing the devices.
998 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
999 mPendingINotify = false;
1000 readNotifyLocked();
1001 deviceChanged = true;
1002 }
1003
1004 // Report added or removed devices immediately.
1005 if (deviceChanged) {
1006 continue;
1007 }
1008
1009 // Return now if we have collected any events or if we were explicitly awoken.
1010 if (event != buffer || awoken) {
1011 break;
1012 }
1013
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001014 // Poll for events.
1015 // When a device driver has pending (unread) events, it acquires
1016 // a kernel wake lock. Once the last pending event has been read, the device
1017 // driver will release the kernel wake lock, but the epoll will hold the wakelock,
1018 // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
1019 // is called again for the same fd that produced the event.
1020 // Thus the system can only sleep if there are no events pending or
1021 // currently being processed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001022 //
1023 // The timeout is advisory only. If the device is asleep, it will not wake just to
1024 // service the timeout.
1025 mPendingEventIndex = 0;
1026
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001027 mLock.unlock(); // release lock before poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001028
1029 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1030
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001031 mLock.lock(); // reacquire lock after poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001032
1033 if (pollResult == 0) {
1034 // Timed out.
1035 mPendingEventCount = 0;
1036 break;
1037 }
1038
1039 if (pollResult < 0) {
1040 // An error occurred.
1041 mPendingEventCount = 0;
1042
1043 // Sleep after errors to avoid locking up the system.
1044 // Hopefully the error is transient.
1045 if (errno != EINTR) {
1046 ALOGW("poll failed (errno=%d)\n", errno);
1047 usleep(100000);
1048 }
1049 } else {
1050 // Some events occurred.
1051 mPendingEventCount = size_t(pollResult);
1052 }
1053 }
1054
1055 // All done, return the number of events we read.
1056 return event - buffer;
1057}
1058
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001059std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
1060 AutoMutex _l(mLock);
1061
1062 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001063 if (device == nullptr || !device->videoDevice) {
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001064 return {};
1065 }
1066 return device->videoDevice->consumeFrames();
1067}
1068
Michael Wrightd02c5b62014-02-10 15:10:22 -08001069void EventHub::wake() {
1070 ALOGV("wake() called");
1071
1072 ssize_t nWrite;
1073 do {
1074 nWrite = write(mWakeWritePipeFd, "W", 1);
1075 } while (nWrite == -1 && errno == EINTR);
1076
1077 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001078 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001079 }
1080}
1081
1082void EventHub::scanDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001083 status_t result = scanDirLocked(DEVICE_PATH);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001084 if (result < 0) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001085 ALOGE("scan dir failed for %s", DEVICE_PATH);
1086 }
Philip Quinn39b81682019-01-09 22:20:39 -08001087 if (isV4lScanningEnabled()) {
1088 result = scanVideoDirLocked(VIDEO_DEVICE_PATH);
1089 if (result != OK) {
1090 ALOGE("scan video dir failed for %s", VIDEO_DEVICE_PATH);
1091 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001092 }
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001093 if (mDevices.indexOfKey(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) < 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001094 createVirtualKeyboardLocked();
1095 }
1096}
1097
1098// ----------------------------------------------------------------------------
1099
Michael Wrightd02c5b62014-02-10 15:10:22 -08001100static const int32_t GAMEPAD_KEYCODES[] = {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001101 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C, //
1102 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z, //
1103 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1, //
1104 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2, //
1105 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR, //
1106 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE, //
Michael Wrightd02c5b62014-02-10 15:10:22 -08001107};
1108
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001109status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001110 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001111 struct epoll_event eventItem = {};
1112 eventItem.events = EPOLLIN | EPOLLWAKEUP;
1113 eventItem.data.fd = fd;
1114 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1115 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001116 return -errno;
1117 }
1118 return OK;
1119}
1120
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001121status_t EventHub::unregisterFdFromEpoll(int fd) {
1122 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
1123 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
1124 return -errno;
1125 }
1126 return OK;
1127}
1128
1129status_t EventHub::registerDeviceForEpollLocked(Device* device) {
1130 if (device == nullptr) {
1131 if (DEBUG) {
1132 LOG_ALWAYS_FATAL("Cannot call registerDeviceForEpollLocked with null Device");
1133 }
1134 return BAD_VALUE;
1135 }
1136 status_t result = registerFdForEpoll(device->fd);
1137 if (result != OK) {
1138 ALOGE("Could not add input device fd to epoll for device %" PRId32, device->id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001139 return result;
1140 }
1141 if (device->videoDevice) {
1142 registerVideoDeviceForEpollLocked(*device->videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001143 }
1144 return result;
1145}
1146
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001147void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
1148 status_t result = registerFdForEpoll(videoDevice.getFd());
1149 if (result != OK) {
1150 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
1151 }
1152}
1153
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001154status_t EventHub::unregisterDeviceFromEpollLocked(Device* device) {
1155 if (device->hasValidFd()) {
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001156 status_t result = unregisterFdFromEpoll(device->fd);
1157 if (result != OK) {
1158 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device->id);
1159 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001160 }
1161 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001162 if (device->videoDevice) {
1163 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1164 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001165 return OK;
1166}
1167
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001168void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
1169 if (videoDevice.hasValidFd()) {
1170 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
1171 if (result != OK) {
1172 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001173 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001174 }
1175 }
1176}
1177
Chris Ye8594e192020-07-14 10:34:06 -07001178status_t EventHub::openDeviceLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001179 char buffer[80];
1180
Chris Ye8594e192020-07-14 10:34:06 -07001181 ALOGV("Opening device: %s", devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001182
Chris Ye8594e192020-07-14 10:34:06 -07001183 int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001184 if (fd < 0) {
Chris Ye8594e192020-07-14 10:34:06 -07001185 ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001186 return -1;
1187 }
1188
1189 InputDeviceIdentifier identifier;
1190
1191 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001192 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Chris Ye8594e192020-07-14 10:34:06 -07001193 ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194 } else {
1195 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001196 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001197 }
1198
1199 // Check to see if the device is on our excluded list
1200 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001201 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001202 if (identifier.name == item) {
Chris Ye8594e192020-07-14 10:34:06 -07001203 ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001204 close(fd);
1205 return -1;
1206 }
1207 }
1208
1209 // Get device driver version.
1210 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001211 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Chris Ye8594e192020-07-14 10:34:06 -07001212 ALOGE("could not get driver version for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001213 close(fd);
1214 return -1;
1215 }
1216
1217 // Get device identifier.
1218 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001219 if (ioctl(fd, EVIOCGID, &inputId)) {
Chris Ye8594e192020-07-14 10:34:06 -07001220 ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001221 close(fd);
1222 return -1;
1223 }
1224 identifier.bus = inputId.bustype;
1225 identifier.product = inputId.product;
1226 identifier.vendor = inputId.vendor;
1227 identifier.version = inputId.version;
1228
1229 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001230 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
1231 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001232 } else {
1233 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001234 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001235 }
1236
1237 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001238 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
1239 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001240 } else {
1241 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001242 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243 }
1244
1245 // Fill in the descriptor.
1246 assignDescriptorLocked(identifier);
1247
Michael Wrightd02c5b62014-02-10 15:10:22 -08001248 // Allocate device. (The device object takes ownership of the fd at this point.)
1249 int32_t deviceId = mNextDeviceId++;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001250 Device* device = new Device(fd, deviceId, devicePath, identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001251
Chris Ye8594e192020-07-14 10:34:06 -07001252 ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001253 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001254 " vendor %04x\n"
1255 " product %04x\n"
1256 " version %04x\n",
1257 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001258 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
1259 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
1260 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
1261 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001262 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
1263 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001264
1265 // Load the configuration file for the device.
1266 loadConfigurationLocked(device);
1267
1268 // Figure out the kinds of events the device reports.
Chris Ye66fbac32020-07-06 20:36:43 -07001269 device->readDeviceBitMask(EVIOCGBIT(EV_KEY, 0), device->keyBitmask);
1270 device->readDeviceBitMask(EVIOCGBIT(EV_ABS, 0), device->absBitmask);
1271 device->readDeviceBitMask(EVIOCGBIT(EV_REL, 0), device->relBitmask);
1272 device->readDeviceBitMask(EVIOCGBIT(EV_SW, 0), device->swBitmask);
1273 device->readDeviceBitMask(EVIOCGBIT(EV_LED, 0), device->ledBitmask);
1274 device->readDeviceBitMask(EVIOCGBIT(EV_FF, 0), device->ffBitmask);
1275 device->readDeviceBitMask(EVIOCGPROP(0), device->propBitmask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001276
1277 // See if this is a keyboard. Ignore everything in the button range except for
1278 // joystick and gamepad buttons which are handled like keyboards for the most part.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001279 bool haveKeyboardKeys =
Chris Ye66fbac32020-07-06 20:36:43 -07001280 device->keyBitmask.any(0, BTN_MISC) || device->keyBitmask.any(BTN_WHEEL, KEY_MAX + 1);
1281 bool haveGamepadButtons = device->keyBitmask.any(BTN_MISC, BTN_MOUSE) ||
1282 device->keyBitmask.any(BTN_JOYSTICK, BTN_DIGI);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001283 if (haveKeyboardKeys || haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001284 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001285 }
1286
1287 // See if this is a cursor device such as a trackball or mouse.
Chris Ye66fbac32020-07-06 20:36:43 -07001288 if (device->keyBitmask.test(BTN_MOUSE) && device->relBitmask.test(REL_X) &&
1289 device->relBitmask.test(REL_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001290 device->classes |= InputDeviceClass::CURSOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001291 }
1292
Prashant Malani1941ff52015-08-11 18:29:28 -07001293 // See if this is a rotary encoder type device.
1294 String8 deviceType = String8();
1295 if (device->configuration &&
1296 device->configuration->tryGetProperty(String8("device.type"), deviceType)) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001297 if (!deviceType.compare(String8("rotaryEncoder"))) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001298 device->classes |= InputDeviceClass::ROTARY_ENCODER;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001299 }
Prashant Malani1941ff52015-08-11 18:29:28 -07001300 }
1301
Michael Wrightd02c5b62014-02-10 15:10:22 -08001302 // See if this is a touch pad.
1303 // Is this a new modern multi-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07001304 if (device->absBitmask.test(ABS_MT_POSITION_X) && device->absBitmask.test(ABS_MT_POSITION_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001305 // Some joysticks such as the PS3 controller report axes that conflict
1306 // with the ABS_MT range. Try to confirm that the device really is
1307 // a touch screen.
Chris Ye66fbac32020-07-06 20:36:43 -07001308 if (device->keyBitmask.test(BTN_TOUCH) || !haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001309 device->classes |= (InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001310 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001311 // Is this an old style single-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07001312 } else if (device->keyBitmask.test(BTN_TOUCH) && device->absBitmask.test(ABS_X) &&
1313 device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001314 device->classes |= InputDeviceClass::TOUCH;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001315 // Is this a BT stylus?
Chris Ye66fbac32020-07-06 20:36:43 -07001316 } else if ((device->absBitmask.test(ABS_PRESSURE) || device->keyBitmask.test(BTN_TOUCH)) &&
1317 !device->absBitmask.test(ABS_X) && !device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001318 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -07001319 // Keyboard will try to claim some of the buttons but we really want to reserve those so we
1320 // can fuse it with the touch screen data, so just take them back. Note this means an
1321 // external stylus cannot also be a keyboard device.
Chris Ye1b0c7342020-07-28 21:57:03 -07001322 device->classes &= ~InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001323 }
1324
1325 // See if this device is a joystick.
1326 // Assumes that joysticks always have gamepad buttons in order to distinguish them
1327 // from other devices such as accelerometers that also have absolute axes.
1328 if (haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001329 auto assumedClasses = device->classes | InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001330 for (int i = 0; i <= ABS_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07001331 if (device->absBitmask.test(i) &&
Chris Ye1b0c7342020-07-28 21:57:03 -07001332 (getAbsAxisUsage(i, assumedClasses).test(InputDeviceClass::JOYSTICK))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001333 device->classes = assumedClasses;
1334 break;
1335 }
1336 }
1337 }
1338
1339 // Check whether this device has switches.
1340 for (int i = 0; i <= SW_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07001341 if (device->swBitmask.test(i)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001342 device->classes |= InputDeviceClass::SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001343 break;
1344 }
1345 }
1346
1347 // Check whether this device supports the vibrator.
Chris Ye66fbac32020-07-06 20:36:43 -07001348 if (device->ffBitmask.test(FF_RUMBLE)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001349 device->classes |= InputDeviceClass::VIBRATOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001350 }
1351
1352 // Configure virtual keys.
Chris Ye1b0c7342020-07-28 21:57:03 -07001353 if ((device->classes.test(InputDeviceClass::TOUCH))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001354 // Load the virtual keys for the touch screen, if any.
1355 // We do this now so that we can make sure to load the keymap if necessary.
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001356 bool success = loadVirtualKeyMapLocked(device);
1357 if (success) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001358 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001359 }
1360 }
1361
1362 // Load the key map.
1363 // We need to do this for joysticks too because the key layout may specify axes.
1364 status_t keyMapStatus = NAME_NOT_FOUND;
Chris Ye1b0c7342020-07-28 21:57:03 -07001365 if (device->classes.any(InputDeviceClass::KEYBOARD | InputDeviceClass::JOYSTICK)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001366 // Load the keymap for the device.
1367 keyMapStatus = loadKeyMapLocked(device);
1368 }
1369
1370 // Configure the keyboard, gamepad or virtual keyboard.
Chris Ye1b0c7342020-07-28 21:57:03 -07001371 if (device->classes.test(InputDeviceClass::KEYBOARD)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001372 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001373 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
1374 isEligibleBuiltInKeyboard(device->identifier, device->configuration, &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001375 mBuiltInKeyboardId = device->id;
1376 }
1377
1378 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
1379 if (hasKeycodeLocked(device, AKEYCODE_Q)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001380 device->classes |= InputDeviceClass::ALPHAKEY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001381 }
1382
1383 // See if this device has a DPAD.
1384 if (hasKeycodeLocked(device, AKEYCODE_DPAD_UP) &&
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001385 hasKeycodeLocked(device, AKEYCODE_DPAD_DOWN) &&
1386 hasKeycodeLocked(device, AKEYCODE_DPAD_LEFT) &&
1387 hasKeycodeLocked(device, AKEYCODE_DPAD_RIGHT) &&
1388 hasKeycodeLocked(device, AKEYCODE_DPAD_CENTER)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001389 device->classes |= InputDeviceClass::DPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001390 }
1391
1392 // See if this device has a gamepad.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001393 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES) / sizeof(GAMEPAD_KEYCODES[0]); i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001394 if (hasKeycodeLocked(device, GAMEPAD_KEYCODES[i])) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001395 device->classes |= InputDeviceClass::GAMEPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001396 break;
1397 }
1398 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001399 }
1400
1401 // If the device isn't recognized as something we handle, don't monitor it.
Chris Ye1b0c7342020-07-28 21:57:03 -07001402 if (device->classes == Flags<InputDeviceClass>(0)) {
Chris Ye8594e192020-07-14 10:34:06 -07001403 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001404 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001405 delete device;
1406 return -1;
1407 }
1408
Tim Kilbourn063ff532015-04-08 10:26:18 -07001409 // Determine whether the device has a mic.
1410 if (deviceHasMicLocked(device)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001411 device->classes |= InputDeviceClass::MIC;
Tim Kilbourn063ff532015-04-08 10:26:18 -07001412 }
1413
Michael Wrightd02c5b62014-02-10 15:10:22 -08001414 // Determine whether the device is external or internal.
1415 if (isExternalDeviceLocked(device)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001416 device->classes |= InputDeviceClass::EXTERNAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001417 }
1418
Chris Ye1b0c7342020-07-28 21:57:03 -07001419 if (device->classes.any(InputDeviceClass::JOYSTICK | InputDeviceClass::DPAD) &&
1420 device->classes.test(InputDeviceClass::GAMEPAD)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001421 device->controllerNumber = getNextControllerNumberLocked(device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001422 setLedForControllerLocked(device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001423 }
1424
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001425 // Find a matching video device by comparing device names
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001426 // This should be done before registerDeviceForEpollLocked, so that both fds are added to epoll
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001427 for (std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
1428 if (device->identifier.name == videoDevice->getName()) {
1429 device->videoDevice = std::move(videoDevice);
1430 break;
1431 }
1432 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001433 mUnattachedVideoDevices
1434 .erase(std::remove_if(mUnattachedVideoDevices.begin(), mUnattachedVideoDevices.end(),
1435 [](const std::unique_ptr<TouchVideoDevice>& videoDevice) {
1436 return videoDevice == nullptr;
1437 }),
1438 mUnattachedVideoDevices.end());
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001439
1440 if (registerDeviceForEpollLocked(device) != OK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001441 delete device;
1442 return -1;
1443 }
1444
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001445 configureFd(device);
1446
Chris Ye1b0c7342020-07-28 21:57:03 -07001447 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=%s, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001448 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Chris Ye1b0c7342020-07-28 21:57:03 -07001449 deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(),
1450 device->classes.string().c_str(), device->configurationFile.c_str(),
1451 device->keyMap.keyLayoutFile.c_str(), device->keyMap.keyCharacterMapFile.c_str(),
1452 toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001453
1454 addDeviceLocked(device);
1455 return OK;
1456}
1457
1458void EventHub::configureFd(Device* device) {
1459 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
Chris Ye1b0c7342020-07-28 21:57:03 -07001460 if (device->classes.test(InputDeviceClass::KEYBOARD)) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001461 // Disable kernel key repeat since we handle it ourselves
1462 unsigned int repeatRate[] = {0, 0};
1463 if (ioctl(device->fd, EVIOCSREP, repeatRate)) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001464 ALOGW("Unable to disable kernel key repeat for %s: %s", device->path.c_str(),
1465 strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001466 }
1467 }
1468
Michael Wrightd02c5b62014-02-10 15:10:22 -08001469 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
1470 // associated with input events. This is important because the input system
1471 // uses the timestamps extensively and assumes they were recorded using the monotonic
1472 // clock.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001473 int clockId = CLOCK_MONOTONIC;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001474 bool usingClockIoctl = !ioctl(device->fd, EVIOCSCLOCKID, &clockId);
Atif Niyaz4180aa42019-05-10 16:27:48 -07001475 ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001476}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001477
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001478void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
1479 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
1480 if (!videoDevice) {
1481 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
1482 return;
1483 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001484 // Transfer ownership of this video device to a matching input device
1485 for (size_t i = 0; i < mDevices.size(); i++) {
1486 Device* device = mDevices.valueAt(i);
1487 if (videoDevice->getName() == device->identifier.name) {
1488 device->videoDevice = std::move(videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001489 if (device->enabled) {
1490 registerVideoDeviceForEpollLocked(*device->videoDevice);
1491 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001492 return;
1493 }
1494 }
1495
1496 // Couldn't find a matching input device, so just add it to a temporary holding queue.
1497 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001498 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001499 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001500 mUnattachedVideoDevices.push_back(std::move(videoDevice));
1501}
1502
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001503bool EventHub::isDeviceEnabled(int32_t deviceId) {
1504 AutoMutex _l(mLock);
1505 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001506 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001507 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1508 return false;
1509 }
1510 return device->enabled;
1511}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001512
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001513status_t EventHub::enableDevice(int32_t deviceId) {
1514 AutoMutex _l(mLock);
1515 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001516 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001517 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1518 return BAD_VALUE;
1519 }
1520 if (device->enabled) {
1521 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
1522 return OK;
1523 }
1524 status_t result = device->enable();
1525 if (result != OK) {
1526 ALOGE("Failed to enable device %" PRId32, deviceId);
1527 return result;
1528 }
1529
1530 configureFd(device);
1531
1532 return registerDeviceForEpollLocked(device);
1533}
1534
1535status_t EventHub::disableDevice(int32_t deviceId) {
1536 AutoMutex _l(mLock);
1537 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001538 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001539 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1540 return BAD_VALUE;
1541 }
1542 if (!device->enabled) {
1543 ALOGW("Duplicate call to %s, input device already disabled", __func__);
1544 return OK;
1545 }
1546 unregisterDeviceFromEpollLocked(device);
1547 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001548}
1549
1550void EventHub::createVirtualKeyboardLocked() {
1551 InputDeviceIdentifier identifier;
1552 identifier.name = "Virtual";
1553 identifier.uniqueId = "<virtual>";
1554 assignDescriptorLocked(identifier);
1555
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001556 Device* device =
1557 new Device(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>", identifier);
Chris Ye1b0c7342020-07-28 21:57:03 -07001558 device->classes = InputDeviceClass::KEYBOARD | InputDeviceClass::ALPHAKEY |
1559 InputDeviceClass::DPAD | InputDeviceClass::VIRTUAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001560 loadKeyMapLocked(device);
1561 addDeviceLocked(device);
1562}
1563
1564void EventHub::addDeviceLocked(Device* device) {
1565 mDevices.add(device->id, device);
1566 device->next = mOpeningDevices;
1567 mOpeningDevices = device;
1568}
1569
1570void EventHub::loadConfigurationLocked(Device* device) {
Chris Ye1d927aa2020-07-04 18:22:41 -07001571 device->configurationFile =
1572 getInputDeviceConfigurationFilePathByDeviceIdentifier(device->identifier,
1573 InputDeviceConfigurationFileType::
1574 CONFIGURATION);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001575 if (device->configurationFile.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001576 ALOGD("No input device configuration file found for device '%s'.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001577 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001578 } else {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001579 status_t status = PropertyMap::load(String8(device->configurationFile.c_str()),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001580 &device->configuration);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001581 if (status) {
1582 ALOGE("Error loading input device configuration file for device '%s'. "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001583 "Using default configuration.",
1584 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001585 }
1586 }
1587}
1588
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001589bool EventHub::loadVirtualKeyMapLocked(Device* device) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001590 // The virtual key map is supplied by the kernel as a system board property file.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001591 std::string path;
1592 path += "/sys/board_properties/virtualkeys.";
Siarhei Vishniakoub45635c2019-02-20 19:22:09 -06001593 path += device->identifier.getCanonicalName();
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001594 if (access(path.c_str(), R_OK)) {
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001595 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001596 }
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001597 device->virtualKeyMap = VirtualKeyMap::load(path);
1598 return device->virtualKeyMap != nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001599}
1600
1601status_t EventHub::loadKeyMapLocked(Device* device) {
1602 return device->keyMap.load(device->identifier, device->configuration);
1603}
1604
1605bool EventHub::isExternalDeviceLocked(Device* device) {
1606 if (device->configuration) {
1607 bool value;
1608 if (device->configuration->tryGetProperty(String8("device.internal"), value)) {
1609 return !value;
1610 }
1611 }
1612 return device->identifier.bus == BUS_USB || device->identifier.bus == BUS_BLUETOOTH;
1613}
1614
Tim Kilbourn063ff532015-04-08 10:26:18 -07001615bool EventHub::deviceHasMicLocked(Device* device) {
1616 if (device->configuration) {
1617 bool value;
1618 if (device->configuration->tryGetProperty(String8("audio.mic"), value)) {
1619 return value;
1620 }
1621 }
1622 return false;
1623}
1624
Michael Wrightd02c5b62014-02-10 15:10:22 -08001625int32_t EventHub::getNextControllerNumberLocked(Device* device) {
1626 if (mControllerNumbers.isFull()) {
1627 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001628 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001629 return 0;
1630 }
1631 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
1632 // one
1633 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
1634}
1635
1636void EventHub::releaseControllerNumberLocked(Device* device) {
1637 int32_t num = device->controllerNumber;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001638 device->controllerNumber = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001639 if (num == 0) {
1640 return;
1641 }
1642 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
1643}
1644
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001645void EventHub::setLedForControllerLocked(Device* device) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001646 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
1647 setLedStateLocked(device, ALED_CONTROLLER_1 + i, device->controllerNumber == i + 1);
1648 }
1649}
1650
1651bool EventHub::hasKeycodeLocked(Device* device, int keycode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001652 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001653 return false;
1654 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001655
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001656 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001657 device->keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes);
1658 const size_t N = scanCodes.size();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001659 for (size_t i = 0; i < N && i <= KEY_MAX; i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001660 int32_t sc = scanCodes[i];
Chris Ye66fbac32020-07-06 20:36:43 -07001661 if (sc >= 0 && sc <= KEY_MAX && device->keyBitmask.test(sc)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001662 return true;
1663 }
1664 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001665
Michael Wrightd02c5b62014-02-10 15:10:22 -08001666 return false;
1667}
1668
1669status_t EventHub::mapLed(Device* device, int32_t led, int32_t* outScanCode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001670 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001671 return NAME_NOT_FOUND;
1672 }
1673
1674 int32_t scanCode;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001675 if (device->keyMap.keyLayoutMap->findScanCodeForLed(led, &scanCode) != NAME_NOT_FOUND) {
Chris Ye66fbac32020-07-06 20:36:43 -07001676 if (scanCode >= 0 && scanCode <= LED_MAX && device->ledBitmask.test(scanCode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001677 *outScanCode = scanCode;
1678 return NO_ERROR;
1679 }
1680 }
1681 return NAME_NOT_FOUND;
1682}
1683
Chris Ye8594e192020-07-14 10:34:06 -07001684void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001685 Device* device = getDeviceByPathLocked(devicePath);
1686 if (device) {
1687 closeDeviceLocked(device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001688 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001689 }
Chris Ye8594e192020-07-14 10:34:06 -07001690 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001691}
1692
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001693/**
1694 * Find the video device by filename, and close it.
1695 * The video device is closed by path during an inotify event, where we don't have the
1696 * additional context about the video device fd, or the associated input device.
1697 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001698void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001699 // A video device may be owned by an existing input device, or it may be stored in
1700 // the mUnattachedVideoDevices queue. Check both locations.
1701 for (size_t i = 0; i < mDevices.size(); i++) {
1702 Device* device = mDevices.valueAt(i);
1703 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001704 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001705 device->videoDevice = nullptr;
1706 return;
1707 }
1708 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001709 mUnattachedVideoDevices
1710 .erase(std::remove_if(mUnattachedVideoDevices.begin(), mUnattachedVideoDevices.end(),
1711 [&devicePath](
1712 const std::unique_ptr<TouchVideoDevice>& videoDevice) {
1713 return videoDevice->getPath() == devicePath;
1714 }),
1715 mUnattachedVideoDevices.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001716}
1717
1718void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001719 mUnattachedVideoDevices.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001720 while (mDevices.size() > 0) {
1721 closeDeviceLocked(mDevices.valueAt(mDevices.size() - 1));
1722 }
1723}
1724
1725void EventHub::closeDeviceLocked(Device* device) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001726 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=%s", device->path.c_str(),
1727 device->identifier.name.c_str(), device->id, device->fd,
1728 device->classes.string().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001729
1730 if (device->id == mBuiltInKeyboardId) {
1731 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001732 device->path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001733 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
1734 }
1735
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001736 unregisterDeviceFromEpollLocked(device);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001737 if (device->videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001738 // This must be done after the video device is removed from epoll
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001739 mUnattachedVideoDevices.push_back(std::move(device->videoDevice));
1740 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001741
1742 releaseControllerNumberLocked(device);
1743
1744 mDevices.removeItem(device->id);
1745 device->close();
1746
1747 // Unlink for opening devices list if it is present.
Yi Kong9b14ac62018-07-17 13:48:38 -07001748 Device* pred = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001749 bool found = false;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001750 for (Device* entry = mOpeningDevices; entry != nullptr;) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001751 if (entry == device) {
1752 found = true;
1753 break;
1754 }
1755 pred = entry;
1756 entry = entry->next;
1757 }
1758 if (found) {
1759 // Unlink the device from the opening devices list then delete it.
1760 // We don't need to tell the client that the device was closed because
1761 // it does not even know it was opened in the first place.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001762 ALOGI("Device %s was immediately closed after opening.", device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001763 if (pred) {
1764 pred->next = device->next;
1765 } else {
1766 mOpeningDevices = device->next;
1767 }
1768 delete device;
1769 } else {
1770 // Link into closing devices list.
1771 // The device will be deleted later after we have informed the client.
1772 device->next = mClosingDevices;
1773 mClosingDevices = device;
1774 }
1775}
1776
1777status_t EventHub::readNotifyLocked() {
1778 int res;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001779 char event_buf[512];
1780 int event_size;
1781 int event_pos = 0;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001782 struct inotify_event* event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001783
1784 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
1785 res = read(mINotifyFd, event_buf, sizeof(event_buf));
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001786 if (res < (int)sizeof(*event)) {
1787 if (errno == EINTR) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001788 ALOGW("could not get event, %s\n", strerror(errno));
1789 return -1;
1790 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001791
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001792 while (res >= (int)sizeof(*event)) {
1793 event = (struct inotify_event*)(event_buf + event_pos);
1794 if (event->len) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001795 if (event->wd == mInputWd) {
Chris Ye8594e192020-07-14 10:34:06 -07001796 std::string filename = std::string(DEVICE_PATH) + "/" + event->name;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001797 if (event->mask & IN_CREATE) {
Chris Ye8594e192020-07-14 10:34:06 -07001798 openDeviceLocked(filename);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001799 } else {
1800 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
Chris Ye8594e192020-07-14 10:34:06 -07001801 closeDeviceByPathLocked(filename);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001802 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001803 } else if (event->wd == mVideoWd) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001804 if (isV4lTouchNode(event->name)) {
Chris Ye8594e192020-07-14 10:34:06 -07001805 std::string filename = std::string(VIDEO_DEVICE_PATH) + "/" + event->name;
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001806 if (event->mask & IN_CREATE) {
1807 openVideoDeviceLocked(filename);
1808 } else {
1809 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
1810 closeVideoDeviceByPathLocked(filename);
1811 }
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001812 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001813 } else {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001814 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event->wd);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001815 }
1816 }
1817 event_size = sizeof(*event) + event->len;
1818 res -= event_size;
1819 event_pos += event_size;
1820 }
1821 return 0;
1822}
1823
Chris Ye8594e192020-07-14 10:34:06 -07001824status_t EventHub::scanDirLocked(const std::string& dirname) {
1825 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
1826 openDeviceLocked(entry.path());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001827 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001828 return 0;
1829}
1830
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001831/**
1832 * Look for all dirname/v4l-touch* devices, and open them.
1833 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001834status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Chris Ye8594e192020-07-14 10:34:06 -07001835 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
1836 if (isV4lTouchNode(entry.path())) {
1837 ALOGI("Found touch video device %s", entry.path().c_str());
1838 openVideoDeviceLocked(entry.path());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001839 }
1840 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001841 return OK;
1842}
1843
Michael Wrightd02c5b62014-02-10 15:10:22 -08001844void EventHub::requestReopenDevices() {
1845 ALOGV("requestReopenDevices() called");
1846
1847 AutoMutex _l(mLock);
1848 mNeedToReopenDevices = true;
1849}
1850
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001851void EventHub::dump(std::string& dump) {
1852 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001853
1854 { // acquire lock
1855 AutoMutex _l(mLock);
1856
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001857 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001858
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001859 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001860
1861 for (size_t i = 0; i < mDevices.size(); i++) {
1862 const Device* device = mDevices.valueAt(i);
1863 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001864 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001865 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001866 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001867 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001868 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001869 }
Chris Ye1b0c7342020-07-28 21:57:03 -07001870 dump += StringPrintf(INDENT3 "Classes: %s\n", device->classes.string().c_str());
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001871 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001872 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001873 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
1874 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001875 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001876 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001877 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001878 "product=0x%04x, version=0x%04x\n",
1879 device->identifier.bus, device->identifier.vendor,
1880 device->identifier.product, device->identifier.version);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001881 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001882 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001883 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001884 device->keyMap.keyCharacterMapFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001885 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001886 device->configurationFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001887 dump += StringPrintf(INDENT3 "HaveKeyboardLayoutOverlay: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001888 toString(device->overlayKeyMap != nullptr));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001889 dump += INDENT3 "VideoDevice: ";
1890 if (device->videoDevice) {
1891 dump += device->videoDevice->dump() + "\n";
1892 } else {
1893 dump += "<none>\n";
1894 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001895 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001896
1897 dump += INDENT "Unattached video devices:\n";
1898 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
1899 dump += INDENT2 + videoDevice->dump() + "\n";
1900 }
1901 if (mUnattachedVideoDevices.empty()) {
1902 dump += INDENT2 "<none>\n";
1903 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001904 } // release lock
1905}
1906
1907void EventHub::monitor() {
1908 // Acquire and release the lock to ensure that the event hub has not deadlocked.
1909 mLock.lock();
1910 mLock.unlock();
1911}
1912
Michael Wrightd02c5b62014-02-10 15:10:22 -08001913}; // namespace android