blob: dda19c669539a4f2b2cdc3bf4a4c46b70cc972ff [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
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070060static const char* DEVICE_PATH = "/dev/input";
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080061// v4l2 devices go directly into /dev
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070062static const char* VIDEO_DEVICE_PATH = "/dev";
Michael Wrightd02c5b62014-02-10 15:10:22 -080063
Chris Ye6393a262020-08-04 19:41:36 -070064static constexpr size_t FF_STRONG_MAGNITUDE_CHANNEL_IDX = 0;
65static constexpr size_t FF_WEAK_MAGNITUDE_CHANNEL_IDX = 1;
66
Michael Wrightd02c5b62014-02-10 15:10:22 -080067static inline const char* toString(bool value) {
68 return value ? "true" : "false";
69}
70
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010071static std::string sha1(const std::string& in) {
Dan Albert677d87e2014-06-16 17:31:28 -070072 SHA_CTX ctx;
73 SHA1_Init(&ctx);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010074 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
Dan Albert677d87e2014-06-16 17:31:28 -070075 u_char digest[SHA_DIGEST_LENGTH];
76 SHA1_Final(digest, &ctx);
Michael Wrightd02c5b62014-02-10 15:10:22 -080077
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010078 std::string out;
Dan Albert677d87e2014-06-16 17:31:28 -070079 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010080 out += StringPrintf("%02x", digest[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -080081 }
82 return out;
83}
84
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080085/**
86 * Return true if name matches "v4l-touch*"
87 */
Chris Ye8594e192020-07-14 10:34:06 -070088static bool isV4lTouchNode(std::string name) {
89 return name.find("v4l-touch") != std::string::npos;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080090}
91
Philip Quinn39b81682019-01-09 22:20:39 -080092/**
93 * Returns true if V4L devices should be scanned.
94 *
95 * The system property ro.input.video_enabled can be used to control whether
96 * EventHub scans and opens V4L devices. As V4L does not support multiple
97 * clients, EventHub effectively blocks access to these devices when it opens
Siarhei Vishniakou29f88492019-04-05 14:11:43 -070098 * them.
99 *
100 * Setting this to "false" would prevent any video devices from being discovered and
101 * associated with input devices.
102 *
103 * This property can be used as follows:
104 * 1. To turn off features that are dependent on video device presence.
105 * 2. During testing and development, to allow other clients to read video devices
106 * directly from /dev.
Philip Quinn39b81682019-01-09 22:20:39 -0800107 */
108static bool isV4lScanningEnabled() {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700109 return property_get_bool("ro.input.video_enabled", true /* default_value */);
Philip Quinn39b81682019-01-09 22:20:39 -0800110}
111
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800112static nsecs_t processEventTimestamp(const struct input_event& event) {
113 // Use the time specified in the event instead of the current time
114 // so that downstream code can get more accurate estimates of
115 // event dispatch latency from the time the event is enqueued onto
116 // the evdev client buffer.
117 //
118 // The event's timestamp fortuitously uses the same monotonic clock
119 // time base as the rest of Android. The kernel event device driver
120 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
121 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
122 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
123 // system call that also queries ktime_get_ts().
124
125 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.time.tv_sec) +
126 microseconds_to_nanoseconds(event.time.tv_usec);
127 return inputEventTime;
128}
129
Michael Wrightd02c5b62014-02-10 15:10:22 -0800130// --- Global Functions ---
131
Chris Ye1b0c7342020-07-28 21:57:03 -0700132Flags<InputDeviceClass> getAbsAxisUsage(int32_t axis, Flags<InputDeviceClass> deviceClasses) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800133 // Touch devices get dibs on touch-related axes.
Chris Ye1b0c7342020-07-28 21:57:03 -0700134 if (deviceClasses.test(InputDeviceClass::TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800135 switch (axis) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700136 case ABS_X:
137 case ABS_Y:
138 case ABS_PRESSURE:
139 case ABS_TOOL_WIDTH:
140 case ABS_DISTANCE:
141 case ABS_TILT_X:
142 case ABS_TILT_Y:
143 case ABS_MT_SLOT:
144 case ABS_MT_TOUCH_MAJOR:
145 case ABS_MT_TOUCH_MINOR:
146 case ABS_MT_WIDTH_MAJOR:
147 case ABS_MT_WIDTH_MINOR:
148 case ABS_MT_ORIENTATION:
149 case ABS_MT_POSITION_X:
150 case ABS_MT_POSITION_Y:
151 case ABS_MT_TOOL_TYPE:
152 case ABS_MT_BLOB_ID:
153 case ABS_MT_TRACKING_ID:
154 case ABS_MT_PRESSURE:
155 case ABS_MT_DISTANCE:
Chris Ye1b0c7342020-07-28 21:57:03 -0700156 return InputDeviceClass::TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800157 }
158 }
159
Michael Wright842500e2015-03-13 17:32:02 -0700160 // External stylus gets the pressure axis
Chris Ye1b0c7342020-07-28 21:57:03 -0700161 if (deviceClasses.test(InputDeviceClass::EXTERNAL_STYLUS)) {
Michael Wright842500e2015-03-13 17:32:02 -0700162 if (axis == ABS_PRESSURE) {
Chris Ye1b0c7342020-07-28 21:57:03 -0700163 return InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -0700164 }
165 }
166
Michael Wrightd02c5b62014-02-10 15:10:22 -0800167 // Joystick devices get the rest.
Chris Ye1b0c7342020-07-28 21:57:03 -0700168 return deviceClasses & InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800169}
170
171// --- EventHub::Device ---
172
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100173EventHub::Device::Device(int fd, int32_t id, const std::string& path,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700174 const InputDeviceIdentifier& identifier)
Chris Ye989bb932020-07-04 16:18:59 -0700175 : fd(fd),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700176 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();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800190}
191
192void EventHub::Device::close() {
193 if (fd >= 0) {
194 ::close(fd);
195 fd = -1;
196 }
197}
198
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700199status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100200 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700201 if (fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100202 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700203 return -errno;
204 }
205 enabled = true;
206 return OK;
207}
208
209status_t EventHub::Device::disable() {
210 close();
211 enabled = false;
212 return OK;
213}
214
Chris Ye989bb932020-07-04 16:18:59 -0700215bool EventHub::Device::hasValidFd() const {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700216 return !isVirtual && enabled;
217}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800218
Chris Ye989bb932020-07-04 16:18:59 -0700219const sp<KeyCharacterMap>& EventHub::Device::getKeyCharacterMap() const {
220 if (combinedKeyMap != nullptr) {
221 return combinedKeyMap;
222 }
223 return keyMap.keyCharacterMap;
224}
225
226template <std::size_t N>
227status_t EventHub::Device::readDeviceBitMask(unsigned long ioctlCode, BitArray<N>& bitArray) {
228 if (!hasValidFd()) {
229 return BAD_VALUE;
230 }
231 if ((_IOC_SIZE(ioctlCode) == 0)) {
232 ioctlCode |= _IOC(0, 0, 0, bitArray.bytes());
233 }
234
235 typename BitArray<N>::Buffer buffer;
236 status_t ret = ioctl(fd, ioctlCode, buffer.data());
237 bitArray.loadFromBuffer(buffer);
238 return ret;
239}
240
241void EventHub::Device::configureFd() {
242 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
243 if (classes.test(InputDeviceClass::KEYBOARD)) {
244 // Disable kernel key repeat since we handle it ourselves
245 unsigned int repeatRate[] = {0, 0};
246 if (ioctl(fd, EVIOCSREP, repeatRate)) {
247 ALOGW("Unable to disable kernel key repeat for %s: %s", path.c_str(), strerror(errno));
248 }
249 }
250
251 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
252 // associated with input events. This is important because the input system
253 // uses the timestamps extensively and assumes they were recorded using the monotonic
254 // clock.
255 int clockId = CLOCK_MONOTONIC;
256 bool usingClockIoctl = !ioctl(fd, EVIOCSCLOCKID, &clockId);
257 ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
258}
259
260bool EventHub::Device::hasKeycodeLocked(int keycode) const {
261 if (!keyMap.haveKeyLayout()) {
262 return false;
263 }
264
265 std::vector<int32_t> scanCodes;
266 keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes);
267 const size_t N = scanCodes.size();
268 for (size_t i = 0; i < N && i <= KEY_MAX; i++) {
269 int32_t sc = scanCodes[i];
270 if (sc >= 0 && sc <= KEY_MAX && keyBitmask.test(sc)) {
271 return true;
272 }
273 }
274
275 return false;
276}
277
278void EventHub::Device::loadConfigurationLocked() {
279 configurationFile =
280 getInputDeviceConfigurationFilePathByDeviceIdentifier(identifier,
281 InputDeviceConfigurationFileType::
282 CONFIGURATION);
283 if (configurationFile.empty()) {
284 ALOGD("No input device configuration file found for device '%s'.", identifier.name.c_str());
285 } else {
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500286 PropertyMap* propertyMap;
287 status_t status = PropertyMap::load(String8(configurationFile.c_str()), &propertyMap);
Chris Ye989bb932020-07-04 16:18:59 -0700288 if (status) {
289 ALOGE("Error loading input device configuration file for device '%s'. "
290 "Using default configuration.",
291 identifier.name.c_str());
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500292 } else {
293 configuration = std::unique_ptr<PropertyMap>(propertyMap);
Chris Ye989bb932020-07-04 16:18:59 -0700294 }
295 }
296}
297
298bool EventHub::Device::loadVirtualKeyMapLocked() {
299 // The virtual key map is supplied by the kernel as a system board property file.
300 std::string propPath = "/sys/board_properties/virtualkeys.";
301 propPath += identifier.getCanonicalName();
302 if (access(propPath.c_str(), R_OK)) {
303 return false;
304 }
305 virtualKeyMap = VirtualKeyMap::load(propPath);
306 return virtualKeyMap != nullptr;
307}
308
309status_t EventHub::Device::loadKeyMapLocked() {
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500310 return keyMap.load(identifier, configuration.get());
Chris Ye989bb932020-07-04 16:18:59 -0700311}
312
313bool EventHub::Device::isExternalDeviceLocked() {
314 if (configuration) {
315 bool value;
316 if (configuration->tryGetProperty(String8("device.internal"), value)) {
317 return !value;
318 }
319 }
320 return identifier.bus == BUS_USB || identifier.bus == BUS_BLUETOOTH;
321}
322
323bool EventHub::Device::deviceHasMicLocked() {
324 if (configuration) {
325 bool value;
326 if (configuration->tryGetProperty(String8("audio.mic"), value)) {
327 return value;
328 }
329 }
330 return false;
331}
332
333void EventHub::Device::setLedStateLocked(int32_t led, bool on) {
334 int32_t sc;
335 if (hasValidFd() && mapLed(led, &sc) != NAME_NOT_FOUND) {
336 struct input_event ev;
337 ev.time.tv_sec = 0;
338 ev.time.tv_usec = 0;
339 ev.type = EV_LED;
340 ev.code = sc;
341 ev.value = on ? 1 : 0;
342
343 ssize_t nWrite;
344 do {
345 nWrite = write(fd, &ev, sizeof(struct input_event));
346 } while (nWrite == -1 && errno == EINTR);
347 }
348}
349
350void EventHub::Device::setLedForControllerLocked() {
351 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
352 setLedStateLocked(ALED_CONTROLLER_1 + i, controllerNumber == i + 1);
353 }
354}
355
356status_t EventHub::Device::mapLed(int32_t led, int32_t* outScanCode) const {
357 if (!keyMap.haveKeyLayout()) {
358 return NAME_NOT_FOUND;
359 }
360
361 int32_t scanCode;
362 if (keyMap.keyLayoutMap->findScanCodeForLed(led, &scanCode) != NAME_NOT_FOUND) {
363 if (scanCode >= 0 && scanCode <= LED_MAX && ledBitmask.test(scanCode)) {
364 *outScanCode = scanCode;
365 return NO_ERROR;
366 }
367 }
368 return NAME_NOT_FOUND;
369}
370
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100371/**
372 * Get the capabilities for the current process.
373 * Crashes the system if unable to create / check / destroy the capabilities object.
374 */
375class Capabilities final {
376public:
377 explicit Capabilities() {
378 mCaps = cap_get_proc();
379 LOG_ALWAYS_FATAL_IF(mCaps == nullptr, "Could not get capabilities of the current process");
380 }
381
382 /**
383 * Check whether the current process has a specific capability
384 * in the set of effective capabilities.
385 * Return CAP_SET if the process has the requested capability
386 * Return CAP_CLEAR otherwise.
387 */
388 cap_flag_value_t checkEffectiveCapability(cap_value_t capability) {
389 cap_flag_value_t value;
390 const int result = cap_get_flag(mCaps, capability, CAP_EFFECTIVE, &value);
391 LOG_ALWAYS_FATAL_IF(result == -1, "Could not obtain the requested capability");
392 return value;
393 }
394
395 ~Capabilities() {
396 const int result = cap_free(mCaps);
397 LOG_ALWAYS_FATAL_IF(result == -1, "Could not release the capabilities structure");
398 }
399
400private:
401 cap_t mCaps;
402};
403
404static void ensureProcessCanBlockSuspend() {
405 Capabilities capabilities;
406 const bool canBlockSuspend =
407 capabilities.checkEffectiveCapability(CAP_BLOCK_SUSPEND) == CAP_SET;
408 LOG_ALWAYS_FATAL_IF(!canBlockSuspend,
409 "Input must be able to block suspend to properly process events");
410}
411
Michael Wrightd02c5b62014-02-10 15:10:22 -0800412// --- EventHub ---
413
Michael Wrightd02c5b62014-02-10 15:10:22 -0800414const int EventHub::EPOLL_MAX_EVENTS;
415
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700416EventHub::EventHub(void)
417 : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
418 mNextDeviceId(1),
419 mControllerNumbers(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800420 mNeedToSendFinishedDeviceScan(false),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700421 mNeedToReopenDevices(false),
422 mNeedToScanDevices(true),
423 mPendingEventCount(0),
424 mPendingEventIndex(0),
425 mPendingINotify(false) {
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100426 ensureProcessCanBlockSuspend();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800427
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800428 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800429 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800430
431 mINotifyFd = inotify_init();
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800432 mInputWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700433 LOG_ALWAYS_FATAL_IF(mInputWd < 0, "Could not register INotify for %s: %s", DEVICE_PATH,
434 strerror(errno));
Philip Quinn39b81682019-01-09 22:20:39 -0800435 if (isV4lScanningEnabled()) {
436 mVideoWd = inotify_add_watch(mINotifyFd, VIDEO_DEVICE_PATH, IN_DELETE | IN_CREATE);
437 LOG_ALWAYS_FATAL_IF(mVideoWd < 0, "Could not register INotify for %s: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700438 VIDEO_DEVICE_PATH, strerror(errno));
Philip Quinn39b81682019-01-09 22:20:39 -0800439 } else {
440 mVideoWd = -1;
441 ALOGI("Video device scanning disabled");
442 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800443
Siarhei Vishniakou2d0e9482019-09-24 12:52:47 +0100444 struct epoll_event eventItem = {};
445 eventItem.events = EPOLLIN | EPOLLWAKEUP;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700446 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800447 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800448 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
449
450 int wakeFds[2];
451 result = pipe(wakeFds);
452 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
453
454 mWakeReadPipeFd = wakeFds[0];
455 mWakeWritePipeFd = wakeFds[1];
456
457 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
458 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700459 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800460
461 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
462 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700463 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800464
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700465 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800466 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
467 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700468 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800469}
470
471EventHub::~EventHub(void) {
472 closeAllDevicesLocked();
473
Michael Wrightd02c5b62014-02-10 15:10:22 -0800474 ::close(mEpollFd);
475 ::close(mINotifyFd);
476 ::close(mWakeReadPipeFd);
477 ::close(mWakeWritePipeFd);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800478}
479
480InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
481 AutoMutex _l(mLock);
482 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700483 return device != nullptr ? device->identifier : InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800484}
485
Chris Ye1b0c7342020-07-28 21:57:03 -0700486Flags<InputDeviceClass> EventHub::getDeviceClasses(int32_t deviceId) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800487 AutoMutex _l(mLock);
488 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700489 return device != nullptr ? device->classes : Flags<InputDeviceClass>(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800490}
491
492int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
493 AutoMutex _l(mLock);
494 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700495 return device != nullptr ? device->controllerNumber : 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800496}
497
498void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
499 AutoMutex _l(mLock);
500 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700501 if (device != nullptr && device->configuration) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800502 *outConfiguration = *device->configuration;
503 } else {
504 outConfiguration->clear();
505 }
506}
507
508status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700509 RawAbsoluteAxisInfo* outAxisInfo) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800510 outAxisInfo->clear();
511
512 if (axis >= 0 && axis <= ABS_MAX) {
513 AutoMutex _l(mLock);
514
515 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700516 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800517 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700518 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
519 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
520 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800521 return -errno;
522 }
523
524 if (info.minimum != info.maximum) {
525 outAxisInfo->valid = true;
526 outAxisInfo->minValue = info.minimum;
527 outAxisInfo->maxValue = info.maximum;
528 outAxisInfo->flat = info.flat;
529 outAxisInfo->fuzz = info.fuzz;
530 outAxisInfo->resolution = info.resolution;
531 }
532 return OK;
533 }
534 }
535 return -1;
536}
537
538bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
539 if (axis >= 0 && axis <= REL_MAX) {
540 AutoMutex _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800541 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700542 return device != nullptr ? device->relBitmask.test(axis) : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800543 }
544 return false;
545}
546
547bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
Chris Ye989bb932020-07-04 16:18:59 -0700548 AutoMutex _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800549
Chris Ye989bb932020-07-04 16:18:59 -0700550 Device* device = getDeviceLocked(deviceId);
551 return property >= 0 && property <= INPUT_PROP_MAX && device != nullptr
552 ? device->propBitmask.test(property)
553 : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800554}
555
556int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
557 if (scanCode >= 0 && scanCode <= KEY_MAX) {
558 AutoMutex _l(mLock);
559
560 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700561 if (device != nullptr && device->hasValidFd() && device->keyBitmask.test(scanCode)) {
562 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
563 return device->keyState.test(scanCode) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800564 }
565 }
566 }
567 return AKEY_STATE_UNKNOWN;
568}
569
570int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
571 AutoMutex _l(mLock);
572
573 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700574 if (device != nullptr && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800575 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800576 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode, &scanCodes);
577 if (scanCodes.size() != 0) {
Chris Ye66fbac32020-07-06 20:36:43 -0700578 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800579 for (size_t i = 0; i < scanCodes.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800580 int32_t sc = scanCodes[i];
Chris Ye66fbac32020-07-06 20:36:43 -0700581 if (sc >= 0 && sc <= KEY_MAX && device->keyState.test(sc)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800582 return AKEY_STATE_DOWN;
583 }
584 }
585 return AKEY_STATE_UP;
586 }
587 }
588 }
589 return AKEY_STATE_UNKNOWN;
590}
591
592int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
593 if (sw >= 0 && sw <= SW_MAX) {
594 AutoMutex _l(mLock);
595
596 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700597 if (device != nullptr && device->hasValidFd() && device->swBitmask.test(sw)) {
598 if (device->readDeviceBitMask(EVIOCGSW(0), device->swState) >= 0) {
599 return device->swState.test(sw) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800600 }
601 }
602 }
603 return AKEY_STATE_UNKNOWN;
604}
605
606status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
607 *outValue = 0;
608
609 if (axis >= 0 && axis <= ABS_MAX) {
610 AutoMutex _l(mLock);
611
612 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700613 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800614 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700615 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
616 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
617 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800618 return -errno;
619 }
620
621 *outValue = info.value;
622 return OK;
623 }
624 }
625 return -1;
626}
627
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700628bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes, const int32_t* keyCodes,
629 uint8_t* outFlags) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800630 AutoMutex _l(mLock);
631
632 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700633 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800634 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800635 for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) {
636 scanCodes.clear();
637
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700638 status_t err = device->keyMap.keyLayoutMap->findScanCodesForKey(keyCodes[codeIndex],
639 &scanCodes);
640 if (!err) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800641 // check the possible scan codes identified by the layout map against the
642 // map of codes actually emitted by the driver
643 for (size_t sc = 0; sc < scanCodes.size(); sc++) {
Chris Ye66fbac32020-07-06 20:36:43 -0700644 if (device->keyBitmask.test(scanCodes[sc])) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800645 outFlags[codeIndex] = 1;
646 break;
647 }
648 }
649 }
650 }
651 return true;
652 }
653 return false;
654}
655
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700656status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
657 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800658 AutoMutex _l(mLock);
659 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700660 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800661
Chris Ye66fbac32020-07-06 20:36:43 -0700662 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800663 // Check the key character map first.
664 sp<KeyCharacterMap> kcm = device->getKeyCharacterMap();
Yi Kong9b14ac62018-07-17 13:48:38 -0700665 if (kcm != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800666 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
667 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700668 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800669 }
670 }
671
672 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700673 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800674 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700675 status = NO_ERROR;
676 }
677 }
678
679 if (status == NO_ERROR) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700680 if (kcm != nullptr) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700681 kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState);
682 } else {
683 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800684 }
685 }
686 }
687
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700688 if (status != NO_ERROR) {
689 *outKeycode = 0;
690 *outFlags = 0;
691 *outMetaState = metaState;
692 }
693
694 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800695}
696
697status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
698 AutoMutex _l(mLock);
699 Device* device = getDeviceLocked(deviceId);
700
Chris Ye66fbac32020-07-06 20:36:43 -0700701 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800702 status_t err = device->keyMap.keyLayoutMap->mapAxis(scanCode, outAxisInfo);
703 if (err == NO_ERROR) {
704 return NO_ERROR;
705 }
706 }
707
708 return NAME_NOT_FOUND;
709}
710
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100711void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800712 AutoMutex _l(mLock);
713
714 mExcludedDevices = devices;
715}
716
717bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
718 AutoMutex _l(mLock);
719 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700720 if (device != nullptr && scanCode >= 0 && scanCode <= KEY_MAX) {
721 return device->keyBitmask.test(scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800722 }
723 return false;
724}
725
726bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
727 AutoMutex _l(mLock);
728 Device* device = getDeviceLocked(deviceId);
729 int32_t sc;
Chris Ye989bb932020-07-04 16:18:59 -0700730 if (device != nullptr && device->mapLed(led, &sc) == NO_ERROR) {
Chris Ye66fbac32020-07-06 20:36:43 -0700731 return device->ledBitmask.test(sc);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800732 }
733 return false;
734}
735
736void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
737 AutoMutex _l(mLock);
738 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700739 if (device != nullptr && device->hasValidFd()) {
740 device->setLedStateLocked(led, on);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800741 }
742}
743
744void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700745 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800746 outVirtualKeys.clear();
747
748 AutoMutex _l(mLock);
749 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700750 if (device != nullptr && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800751 const std::vector<VirtualKeyDefinition> virtualKeys =
752 device->virtualKeyMap->getVirtualKeys();
753 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800754 }
755}
756
757sp<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
758 AutoMutex _l(mLock);
759 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700760 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800761 return device->getKeyCharacterMap();
762 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700763 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800764}
765
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700766bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, const sp<KeyCharacterMap>& map) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800767 AutoMutex _l(mLock);
768 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700769 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800770 if (map != device->overlayKeyMap) {
771 device->overlayKeyMap = map;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700772 device->combinedKeyMap = KeyCharacterMap::combine(device->keyMap.keyCharacterMap, map);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800773 return true;
774 }
775 }
776 return false;
777}
778
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100779static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
780 std::string rawDescriptor;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700781 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800782 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100783 if (!identifier.uniqueId.empty()) {
784 rawDescriptor += "uniqueId:";
785 rawDescriptor += identifier.uniqueId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800786 } else if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100787 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788 }
789
790 if (identifier.vendor == 0 && identifier.product == 0) {
791 // If we don't know the vendor and product id, then the device is probably
792 // built-in so we need to rely on other information to uniquely identify
793 // the input device. Usually we try to avoid relying on the device name or
794 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100795 if (!identifier.name.empty()) {
796 rawDescriptor += "name:";
797 rawDescriptor += identifier.name;
798 } else if (!identifier.location.empty()) {
799 rawDescriptor += "location:";
800 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800801 }
802 }
803 identifier.descriptor = sha1(rawDescriptor);
804 return rawDescriptor;
805}
806
807void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
808 // Compute a device descriptor that uniquely identifies the device.
809 // The descriptor is assumed to be a stable identifier. Its value should not
810 // change between reboots, reconnections, firmware updates or new releases
811 // of Android. In practice we sometimes get devices that cannot be uniquely
812 // identified. In this case we enforce uniqueness between connected devices.
813 // Ideally, we also want the descriptor to be short and relatively opaque.
814
815 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100816 std::string rawDescriptor = generateDescriptor(identifier);
817 if (identifier.uniqueId.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800818 // If it didn't have a unique id check for conflicts and enforce
819 // uniqueness if necessary.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700820 while (getDeviceByDescriptorLocked(identifier.descriptor) != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800821 identifier.nonce++;
822 rawDescriptor = generateDescriptor(identifier);
823 }
824 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100825 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700826 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800827}
828
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +0000829void EventHub::vibrate(int32_t deviceId, const VibrationElement& element) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800830 AutoMutex _l(mLock);
831 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700832 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800833 ff_effect effect;
834 memset(&effect, 0, sizeof(effect));
835 effect.type = FF_RUMBLE;
836 effect.id = device->ffEffectId;
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +0000837 // evdev FF_RUMBLE effect only supports two channels of vibration.
Chris Ye6393a262020-08-04 19:41:36 -0700838 effect.u.rumble.strong_magnitude = element.getMagnitude(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
839 effect.u.rumble.weak_magnitude = element.getMagnitude(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +0000840 effect.replay.length = element.duration.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800841 effect.replay.delay = 0;
842 if (ioctl(device->fd, EVIOCSFF, &effect)) {
843 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700844 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800845 return;
846 }
847 device->ffEffectId = effect.id;
848
849 struct input_event ev;
850 ev.time.tv_sec = 0;
851 ev.time.tv_usec = 0;
852 ev.type = EV_FF;
853 ev.code = device->ffEffectId;
854 ev.value = 1;
855 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
856 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700857 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800858 return;
859 }
860 device->ffEffectPlaying = true;
861 }
862}
863
864void EventHub::cancelVibrate(int32_t deviceId) {
865 AutoMutex _l(mLock);
866 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700867 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800868 if (device->ffEffectPlaying) {
869 device->ffEffectPlaying = false;
870
871 struct input_event ev;
872 ev.time.tv_sec = 0;
873 ev.time.tv_usec = 0;
874 ev.type = EV_FF;
875 ev.code = device->ffEffectId;
876 ev.value = 0;
877 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
878 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700879 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800880 return;
881 }
882 }
883 }
884}
885
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100886EventHub::Device* EventHub::getDeviceByDescriptorLocked(const std::string& descriptor) const {
Chris Ye989bb932020-07-04 16:18:59 -0700887 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100888 if (descriptor == device->identifier.descriptor) {
Chris Ye989bb932020-07-04 16:18:59 -0700889 return device.get();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800890 }
891 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700892 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800893}
894
895EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -0800896 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800897 deviceId = mBuiltInKeyboardId;
898 }
Chris Ye989bb932020-07-04 16:18:59 -0700899 const auto& it = mDevices.find(deviceId);
900 return it != mDevices.end() ? it->second.get() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800901}
902
Chris Ye8594e192020-07-14 10:34:06 -0700903EventHub::Device* EventHub::getDeviceByPathLocked(const std::string& devicePath) const {
Chris Ye989bb932020-07-04 16:18:59 -0700904 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800905 if (device->path == devicePath) {
Chris Ye989bb932020-07-04 16:18:59 -0700906 return device.get();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800907 }
908 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700909 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800910}
911
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700912/**
913 * The file descriptor could be either input device, or a video device (associated with a
914 * specific input device). Check both cases here, and return the device that this event
915 * belongs to. Caller can compare the fd's once more to determine event type.
916 * Looks through all input devices, and only attached video devices. Unattached video
917 * devices are ignored.
918 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700919EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
Chris Ye989bb932020-07-04 16:18:59 -0700920 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700921 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700922 // This is an input device event
Chris Ye989bb932020-07-04 16:18:59 -0700923 return device.get();
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700924 }
925 if (device->videoDevice && device->videoDevice->getFd() == fd) {
926 // This is a video device event
Chris Ye989bb932020-07-04 16:18:59 -0700927 return device.get();
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700928 }
929 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700930 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
931 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700932 return nullptr;
933}
934
Michael Wrightd02c5b62014-02-10 15:10:22 -0800935size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
936 ALOG_ASSERT(bufferSize >= 1);
937
938 AutoMutex _l(mLock);
939
940 struct input_event readBuffer[bufferSize];
941
942 RawEvent* event = buffer;
943 size_t capacity = bufferSize;
944 bool awoken = false;
945 for (;;) {
946 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
947
948 // Reopen input devices if needed.
949 if (mNeedToReopenDevices) {
950 mNeedToReopenDevices = false;
951
952 ALOGI("Reopening all input devices due to a configuration change.");
953
954 closeAllDevicesLocked();
955 mNeedToScanDevices = true;
956 break; // return to the caller before we actually rescan
957 }
958
959 // Report any devices that had last been added/removed.
Chris Ye989bb932020-07-04 16:18:59 -0700960 for (auto it = mClosingDevices.begin(); it != mClosingDevices.end();) {
961 std::unique_ptr<Device> device = std::move(*it);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700962 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800963 event->when = now;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700964 event->deviceId = (device->id == mBuiltInKeyboardId)
965 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
966 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800967 event->type = DEVICE_REMOVED;
968 event += 1;
Chris Ye989bb932020-07-04 16:18:59 -0700969 it = mClosingDevices.erase(it);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800970 mNeedToSendFinishedDeviceScan = true;
971 if (--capacity == 0) {
972 break;
973 }
974 }
975
976 if (mNeedToScanDevices) {
977 mNeedToScanDevices = false;
978 scanDevicesLocked();
979 mNeedToSendFinishedDeviceScan = true;
980 }
981
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -0500982 while (!mOpeningDevices.empty()) {
983 std::unique_ptr<Device> device = std::move(*mOpeningDevices.rbegin());
984 mOpeningDevices.pop_back();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700985 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800986 event->when = now;
987 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
988 event->type = DEVICE_ADDED;
989 event += 1;
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -0500990
991 // Try to find a matching video device by comparing device names
992 for (auto it = mUnattachedVideoDevices.begin(); it != mUnattachedVideoDevices.end();
993 it++) {
994 std::unique_ptr<TouchVideoDevice>& videoDevice = *it;
995 if (tryAddVideoDevice(*device, videoDevice)) {
996 // videoDevice was transferred to 'device'
997 it = mUnattachedVideoDevices.erase(it);
998 break;
999 }
1000 }
1001
1002 auto [dev_it, inserted] = mDevices.insert_or_assign(device->id, std::move(device));
1003 if (!inserted) {
Chris Ye989bb932020-07-04 16:18:59 -07001004 ALOGW("Device id %d exists, replaced.", device->id);
1005 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001006 mNeedToSendFinishedDeviceScan = true;
1007 if (--capacity == 0) {
1008 break;
1009 }
1010 }
1011
1012 if (mNeedToSendFinishedDeviceScan) {
1013 mNeedToSendFinishedDeviceScan = false;
1014 event->when = now;
1015 event->type = FINISHED_DEVICE_SCAN;
1016 event += 1;
1017 if (--capacity == 0) {
1018 break;
1019 }
1020 }
1021
1022 // Grab the next input event.
1023 bool deviceChanged = false;
1024 while (mPendingEventIndex < mPendingEventCount) {
1025 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001026 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001027 if (eventItem.events & EPOLLIN) {
1028 mPendingINotify = true;
1029 } else {
1030 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
1031 }
1032 continue;
1033 }
1034
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001035 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001036 if (eventItem.events & EPOLLIN) {
1037 ALOGV("awoken after wake()");
1038 awoken = true;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001039 char wakeReadBuffer[16];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001040 ssize_t nRead;
1041 do {
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001042 nRead = read(mWakeReadPipeFd, wakeReadBuffer, sizeof(wakeReadBuffer));
1043 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(wakeReadBuffer));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001044 } else {
1045 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001046 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001047 }
1048 continue;
1049 }
1050
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001051 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Chris Ye989bb932020-07-04 16:18:59 -07001052 if (device == nullptr) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001053 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
1054 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001055 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001056 continue;
1057 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001058 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
1059 if (eventItem.events & EPOLLIN) {
1060 size_t numFrames = device->videoDevice->readAndQueueFrames();
1061 if (numFrames == 0) {
1062 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001063 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001064 }
1065 } else if (eventItem.events & EPOLLHUP) {
1066 // TODO(b/121395353) - consider adding EPOLLRDHUP
1067 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001068 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001069 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1070 device->videoDevice = nullptr;
1071 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001072 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1073 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001074 ALOG_ASSERT(!DEBUG);
1075 }
1076 continue;
1077 }
1078 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -08001079 if (eventItem.events & EPOLLIN) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001080 int32_t readSize =
1081 read(device->fd, readBuffer, sizeof(struct input_event) * capacity);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001082 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
1083 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -07001084 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001085 " bufferSize: %zu capacity: %zu errno: %d)\n",
1086 device->fd, readSize, bufferSize, capacity, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001087 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001088 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001089 } else if (readSize < 0) {
1090 if (errno != EAGAIN && errno != EINTR) {
1091 ALOGW("could not get event (errno=%d)", errno);
1092 }
1093 } else if ((readSize % sizeof(struct input_event)) != 0) {
1094 ALOGE("could not get event (wrong size: %d)", readSize);
1095 } else {
1096 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1097
1098 size_t count = size_t(readSize) / sizeof(struct input_event);
1099 for (size_t i = 0; i < count; i++) {
1100 struct input_event& iev = readBuffer[i];
Siarhei Vishniakou592bac22018-11-08 19:42:38 -08001101 event->when = processEventTimestamp(iev);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001102 event->deviceId = deviceId;
1103 event->type = iev.type;
1104 event->code = iev.code;
1105 event->value = iev.value;
1106 event += 1;
1107 capacity -= 1;
1108 }
1109 if (capacity == 0) {
1110 // The result buffer is full. Reset the pending event index
1111 // so we will try to read the device again on the next iteration.
1112 mPendingEventIndex -= 1;
1113 break;
1114 }
1115 }
1116 } else if (eventItem.events & EPOLLHUP) {
1117 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001118 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001119 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001120 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001121 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001122 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1123 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001124 }
1125 }
1126
1127 // readNotify() will modify the list of devices so this must be done after
1128 // processing all other events to ensure that we read all remaining events
1129 // before closing the devices.
1130 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
1131 mPendingINotify = false;
1132 readNotifyLocked();
1133 deviceChanged = true;
1134 }
1135
1136 // Report added or removed devices immediately.
1137 if (deviceChanged) {
1138 continue;
1139 }
1140
1141 // Return now if we have collected any events or if we were explicitly awoken.
1142 if (event != buffer || awoken) {
1143 break;
1144 }
1145
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001146 // Poll for events.
1147 // When a device driver has pending (unread) events, it acquires
1148 // a kernel wake lock. Once the last pending event has been read, the device
1149 // driver will release the kernel wake lock, but the epoll will hold the wakelock,
1150 // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
1151 // is called again for the same fd that produced the event.
1152 // Thus the system can only sleep if there are no events pending or
1153 // currently being processed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001154 //
1155 // The timeout is advisory only. If the device is asleep, it will not wake just to
1156 // service the timeout.
1157 mPendingEventIndex = 0;
1158
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001159 mLock.unlock(); // release lock before poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001160
1161 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1162
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001163 mLock.lock(); // reacquire lock after poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001164
1165 if (pollResult == 0) {
1166 // Timed out.
1167 mPendingEventCount = 0;
1168 break;
1169 }
1170
1171 if (pollResult < 0) {
1172 // An error occurred.
1173 mPendingEventCount = 0;
1174
1175 // Sleep after errors to avoid locking up the system.
1176 // Hopefully the error is transient.
1177 if (errno != EINTR) {
1178 ALOGW("poll failed (errno=%d)\n", errno);
1179 usleep(100000);
1180 }
1181 } else {
1182 // Some events occurred.
1183 mPendingEventCount = size_t(pollResult);
1184 }
1185 }
1186
1187 // All done, return the number of events we read.
1188 return event - buffer;
1189}
1190
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001191std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
1192 AutoMutex _l(mLock);
1193
1194 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001195 if (device == nullptr || !device->videoDevice) {
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001196 return {};
1197 }
1198 return device->videoDevice->consumeFrames();
1199}
1200
Michael Wrightd02c5b62014-02-10 15:10:22 -08001201void EventHub::wake() {
1202 ALOGV("wake() called");
1203
1204 ssize_t nWrite;
1205 do {
1206 nWrite = write(mWakeWritePipeFd, "W", 1);
1207 } while (nWrite == -1 && errno == EINTR);
1208
1209 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001210 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001211 }
1212}
1213
1214void EventHub::scanDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001215 status_t result = scanDirLocked(DEVICE_PATH);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001216 if (result < 0) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001217 ALOGE("scan dir failed for %s", DEVICE_PATH);
1218 }
Philip Quinn39b81682019-01-09 22:20:39 -08001219 if (isV4lScanningEnabled()) {
1220 result = scanVideoDirLocked(VIDEO_DEVICE_PATH);
1221 if (result != OK) {
1222 ALOGE("scan video dir failed for %s", VIDEO_DEVICE_PATH);
1223 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001224 }
Chris Ye989bb932020-07-04 16:18:59 -07001225 if (mDevices.find(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) == mDevices.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001226 createVirtualKeyboardLocked();
1227 }
1228}
1229
1230// ----------------------------------------------------------------------------
1231
Michael Wrightd02c5b62014-02-10 15:10:22 -08001232static const int32_t GAMEPAD_KEYCODES[] = {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001233 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C, //
1234 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z, //
1235 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1, //
1236 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2, //
1237 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR, //
1238 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE, //
Michael Wrightd02c5b62014-02-10 15:10:22 -08001239};
1240
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001241status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001242 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001243 struct epoll_event eventItem = {};
1244 eventItem.events = EPOLLIN | EPOLLWAKEUP;
1245 eventItem.data.fd = fd;
1246 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1247 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001248 return -errno;
1249 }
1250 return OK;
1251}
1252
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001253status_t EventHub::unregisterFdFromEpoll(int fd) {
1254 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
1255 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
1256 return -errno;
1257 }
1258 return OK;
1259}
1260
Chris Ye989bb932020-07-04 16:18:59 -07001261status_t EventHub::registerDeviceForEpollLocked(Device& device) {
1262 status_t result = registerFdForEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001263 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07001264 ALOGE("Could not add input device fd to epoll for device %" PRId32, device.id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001265 return result;
1266 }
Chris Ye989bb932020-07-04 16:18:59 -07001267 if (device.videoDevice) {
1268 registerVideoDeviceForEpollLocked(*device.videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001269 }
1270 return result;
1271}
1272
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001273void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
1274 status_t result = registerFdForEpoll(videoDevice.getFd());
1275 if (result != OK) {
1276 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
1277 }
1278}
1279
Chris Ye989bb932020-07-04 16:18:59 -07001280status_t EventHub::unregisterDeviceFromEpollLocked(Device& device) {
1281 if (device.hasValidFd()) {
1282 status_t result = unregisterFdFromEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001283 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07001284 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device.id);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001285 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001286 }
1287 }
Chris Ye989bb932020-07-04 16:18:59 -07001288 if (device.videoDevice) {
1289 unregisterVideoDeviceFromEpollLocked(*device.videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001290 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001291 return OK;
1292}
1293
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001294void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
1295 if (videoDevice.hasValidFd()) {
1296 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
1297 if (result != OK) {
1298 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001299 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001300 }
1301 }
1302}
1303
Chris Ye8594e192020-07-14 10:34:06 -07001304status_t EventHub::openDeviceLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001305 char buffer[80];
1306
Chris Ye8594e192020-07-14 10:34:06 -07001307 ALOGV("Opening device: %s", devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001308
Chris Ye8594e192020-07-14 10:34:06 -07001309 int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001310 if (fd < 0) {
Chris Ye8594e192020-07-14 10:34:06 -07001311 ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001312 return -1;
1313 }
1314
1315 InputDeviceIdentifier identifier;
1316
1317 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001318 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Chris Ye8594e192020-07-14 10:34:06 -07001319 ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001320 } else {
1321 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001322 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001323 }
1324
1325 // Check to see if the device is on our excluded list
1326 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001327 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001328 if (identifier.name == item) {
Chris Ye8594e192020-07-14 10:34:06 -07001329 ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001330 close(fd);
1331 return -1;
1332 }
1333 }
1334
1335 // Get device driver version.
1336 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001337 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Chris Ye8594e192020-07-14 10:34:06 -07001338 ALOGE("could not get driver version for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001339 close(fd);
1340 return -1;
1341 }
1342
1343 // Get device identifier.
1344 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001345 if (ioctl(fd, EVIOCGID, &inputId)) {
Chris Ye8594e192020-07-14 10:34:06 -07001346 ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001347 close(fd);
1348 return -1;
1349 }
1350 identifier.bus = inputId.bustype;
1351 identifier.product = inputId.product;
1352 identifier.vendor = inputId.vendor;
1353 identifier.version = inputId.version;
1354
1355 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001356 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
1357 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001358 } else {
1359 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001360 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001361 }
1362
1363 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001364 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
1365 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001366 } else {
1367 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001368 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001369 }
1370
1371 // Fill in the descriptor.
1372 assignDescriptorLocked(identifier);
1373
Michael Wrightd02c5b62014-02-10 15:10:22 -08001374 // Allocate device. (The device object takes ownership of the fd at this point.)
1375 int32_t deviceId = mNextDeviceId++;
Chris Ye989bb932020-07-04 16:18:59 -07001376 std::unique_ptr<Device> device = std::make_unique<Device>(fd, deviceId, devicePath, identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001377
Chris Ye8594e192020-07-14 10:34:06 -07001378 ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001379 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001380 " vendor %04x\n"
1381 " product %04x\n"
1382 " version %04x\n",
1383 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001384 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
1385 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
1386 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
1387 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001388 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
1389 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001390
1391 // Load the configuration file for the device.
Chris Ye989bb932020-07-04 16:18:59 -07001392 device->loadConfigurationLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001393
1394 // Figure out the kinds of events the device reports.
Chris Ye66fbac32020-07-06 20:36:43 -07001395 device->readDeviceBitMask(EVIOCGBIT(EV_KEY, 0), device->keyBitmask);
1396 device->readDeviceBitMask(EVIOCGBIT(EV_ABS, 0), device->absBitmask);
1397 device->readDeviceBitMask(EVIOCGBIT(EV_REL, 0), device->relBitmask);
1398 device->readDeviceBitMask(EVIOCGBIT(EV_SW, 0), device->swBitmask);
1399 device->readDeviceBitMask(EVIOCGBIT(EV_LED, 0), device->ledBitmask);
1400 device->readDeviceBitMask(EVIOCGBIT(EV_FF, 0), device->ffBitmask);
1401 device->readDeviceBitMask(EVIOCGPROP(0), device->propBitmask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001402
1403 // See if this is a keyboard. Ignore everything in the button range except for
1404 // joystick and gamepad buttons which are handled like keyboards for the most part.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001405 bool haveKeyboardKeys =
Chris Ye66fbac32020-07-06 20:36:43 -07001406 device->keyBitmask.any(0, BTN_MISC) || device->keyBitmask.any(BTN_WHEEL, KEY_MAX + 1);
1407 bool haveGamepadButtons = device->keyBitmask.any(BTN_MISC, BTN_MOUSE) ||
1408 device->keyBitmask.any(BTN_JOYSTICK, BTN_DIGI);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001409 if (haveKeyboardKeys || haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001410 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001411 }
1412
1413 // See if this is a cursor device such as a trackball or mouse.
Chris Ye66fbac32020-07-06 20:36:43 -07001414 if (device->keyBitmask.test(BTN_MOUSE) && device->relBitmask.test(REL_X) &&
1415 device->relBitmask.test(REL_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001416 device->classes |= InputDeviceClass::CURSOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001417 }
1418
Prashant Malani1941ff52015-08-11 18:29:28 -07001419 // See if this is a rotary encoder type device.
1420 String8 deviceType = String8();
1421 if (device->configuration &&
1422 device->configuration->tryGetProperty(String8("device.type"), deviceType)) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001423 if (!deviceType.compare(String8("rotaryEncoder"))) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001424 device->classes |= InputDeviceClass::ROTARY_ENCODER;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001425 }
Prashant Malani1941ff52015-08-11 18:29:28 -07001426 }
1427
Michael Wrightd02c5b62014-02-10 15:10:22 -08001428 // See if this is a touch pad.
1429 // Is this a new modern multi-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07001430 if (device->absBitmask.test(ABS_MT_POSITION_X) && device->absBitmask.test(ABS_MT_POSITION_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001431 // Some joysticks such as the PS3 controller report axes that conflict
1432 // with the ABS_MT range. Try to confirm that the device really is
1433 // a touch screen.
Chris Ye66fbac32020-07-06 20:36:43 -07001434 if (device->keyBitmask.test(BTN_TOUCH) || !haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001435 device->classes |= (InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001436 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001437 // Is this an old style single-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07001438 } else if (device->keyBitmask.test(BTN_TOUCH) && device->absBitmask.test(ABS_X) &&
1439 device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001440 device->classes |= InputDeviceClass::TOUCH;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001441 // Is this a BT stylus?
Chris Ye66fbac32020-07-06 20:36:43 -07001442 } else if ((device->absBitmask.test(ABS_PRESSURE) || device->keyBitmask.test(BTN_TOUCH)) &&
1443 !device->absBitmask.test(ABS_X) && !device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001444 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -07001445 // Keyboard will try to claim some of the buttons but we really want to reserve those so we
1446 // can fuse it with the touch screen data, so just take them back. Note this means an
1447 // external stylus cannot also be a keyboard device.
Chris Ye1b0c7342020-07-28 21:57:03 -07001448 device->classes &= ~InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001449 }
1450
1451 // See if this device is a joystick.
1452 // Assumes that joysticks always have gamepad buttons in order to distinguish them
1453 // from other devices such as accelerometers that also have absolute axes.
1454 if (haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001455 auto assumedClasses = device->classes | InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001456 for (int i = 0; i <= ABS_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07001457 if (device->absBitmask.test(i) &&
Chris Ye1b0c7342020-07-28 21:57:03 -07001458 (getAbsAxisUsage(i, assumedClasses).test(InputDeviceClass::JOYSTICK))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001459 device->classes = assumedClasses;
1460 break;
1461 }
1462 }
1463 }
1464
1465 // Check whether this device has switches.
1466 for (int i = 0; i <= SW_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07001467 if (device->swBitmask.test(i)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001468 device->classes |= InputDeviceClass::SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001469 break;
1470 }
1471 }
1472
1473 // Check whether this device supports the vibrator.
Chris Ye66fbac32020-07-06 20:36:43 -07001474 if (device->ffBitmask.test(FF_RUMBLE)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001475 device->classes |= InputDeviceClass::VIBRATOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001476 }
1477
1478 // Configure virtual keys.
Chris Ye1b0c7342020-07-28 21:57:03 -07001479 if ((device->classes.test(InputDeviceClass::TOUCH))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480 // Load the virtual keys for the touch screen, if any.
1481 // We do this now so that we can make sure to load the keymap if necessary.
Chris Ye989bb932020-07-04 16:18:59 -07001482 bool success = device->loadVirtualKeyMapLocked();
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001483 if (success) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001484 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001485 }
1486 }
1487
1488 // Load the key map.
1489 // We need to do this for joysticks too because the key layout may specify axes.
1490 status_t keyMapStatus = NAME_NOT_FOUND;
Chris Ye1b0c7342020-07-28 21:57:03 -07001491 if (device->classes.any(InputDeviceClass::KEYBOARD | InputDeviceClass::JOYSTICK)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001492 // Load the keymap for the device.
Chris Ye989bb932020-07-04 16:18:59 -07001493 keyMapStatus = device->loadKeyMapLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001494 }
1495
1496 // Configure the keyboard, gamepad or virtual keyboard.
Chris Ye1b0c7342020-07-28 21:57:03 -07001497 if (device->classes.test(InputDeviceClass::KEYBOARD)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001498 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001499 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05001500 isEligibleBuiltInKeyboard(device->identifier, device->configuration.get(),
1501 &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001502 mBuiltInKeyboardId = device->id;
1503 }
1504
1505 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
Chris Ye989bb932020-07-04 16:18:59 -07001506 if (device->hasKeycodeLocked(AKEYCODE_Q)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001507 device->classes |= InputDeviceClass::ALPHAKEY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001508 }
1509
1510 // See if this device has a DPAD.
Chris Ye989bb932020-07-04 16:18:59 -07001511 if (device->hasKeycodeLocked(AKEYCODE_DPAD_UP) &&
1512 device->hasKeycodeLocked(AKEYCODE_DPAD_DOWN) &&
1513 device->hasKeycodeLocked(AKEYCODE_DPAD_LEFT) &&
1514 device->hasKeycodeLocked(AKEYCODE_DPAD_RIGHT) &&
1515 device->hasKeycodeLocked(AKEYCODE_DPAD_CENTER)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001516 device->classes |= InputDeviceClass::DPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001517 }
1518
1519 // See if this device has a gamepad.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001520 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES) / sizeof(GAMEPAD_KEYCODES[0]); i++) {
Chris Ye989bb932020-07-04 16:18:59 -07001521 if (device->hasKeycodeLocked(GAMEPAD_KEYCODES[i])) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001522 device->classes |= InputDeviceClass::GAMEPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001523 break;
1524 }
1525 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001526 }
1527
1528 // If the device isn't recognized as something we handle, don't monitor it.
Chris Ye1b0c7342020-07-28 21:57:03 -07001529 if (device->classes == Flags<InputDeviceClass>(0)) {
Chris Ye8594e192020-07-14 10:34:06 -07001530 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001531 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001532 return -1;
1533 }
1534
Tim Kilbourn063ff532015-04-08 10:26:18 -07001535 // Determine whether the device has a mic.
Chris Ye989bb932020-07-04 16:18:59 -07001536 if (device->deviceHasMicLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001537 device->classes |= InputDeviceClass::MIC;
Tim Kilbourn063ff532015-04-08 10:26:18 -07001538 }
1539
Michael Wrightd02c5b62014-02-10 15:10:22 -08001540 // Determine whether the device is external or internal.
Chris Ye989bb932020-07-04 16:18:59 -07001541 if (device->isExternalDeviceLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001542 device->classes |= InputDeviceClass::EXTERNAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001543 }
1544
Chris Ye1b0c7342020-07-28 21:57:03 -07001545 if (device->classes.any(InputDeviceClass::JOYSTICK | InputDeviceClass::DPAD) &&
1546 device->classes.test(InputDeviceClass::GAMEPAD)) {
Chris Ye989bb932020-07-04 16:18:59 -07001547 device->controllerNumber = getNextControllerNumberLocked(device->identifier.name);
1548 device->setLedForControllerLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001549 }
1550
Chris Ye989bb932020-07-04 16:18:59 -07001551 if (registerDeviceForEpollLocked(*device) != OK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001552 return -1;
1553 }
1554
Chris Ye989bb932020-07-04 16:18:59 -07001555 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001556
Chris Ye1b0c7342020-07-28 21:57:03 -07001557 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=%s, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001558 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Chris Ye1b0c7342020-07-28 21:57:03 -07001559 deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(),
1560 device->classes.string().c_str(), device->configurationFile.c_str(),
1561 device->keyMap.keyLayoutFile.c_str(), device->keyMap.keyCharacterMapFile.c_str(),
1562 toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001563
Chris Ye989bb932020-07-04 16:18:59 -07001564 addDeviceLocked(std::move(device));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001565 return OK;
1566}
1567
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001568void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
1569 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
1570 if (!videoDevice) {
1571 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
1572 return;
1573 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001574 // Transfer ownership of this video device to a matching input device
Chris Ye989bb932020-07-04 16:18:59 -07001575 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001576 if (tryAddVideoDevice(*device, videoDevice)) {
1577 return; // 'device' now owns 'videoDevice'
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001578 }
1579 }
1580
1581 // Couldn't find a matching input device, so just add it to a temporary holding queue.
1582 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001583 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001584 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001585 mUnattachedVideoDevices.push_back(std::move(videoDevice));
1586}
1587
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001588bool EventHub::tryAddVideoDevice(EventHub::Device& device,
1589 std::unique_ptr<TouchVideoDevice>& videoDevice) {
1590 if (videoDevice->getName() != device.identifier.name) {
1591 return false;
1592 }
1593 device.videoDevice = std::move(videoDevice);
1594 if (device.enabled) {
1595 registerVideoDeviceForEpollLocked(*device.videoDevice);
1596 }
1597 return true;
1598}
1599
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001600bool EventHub::isDeviceEnabled(int32_t deviceId) {
1601 AutoMutex _l(mLock);
1602 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001603 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001604 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1605 return false;
1606 }
1607 return device->enabled;
1608}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001609
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001610status_t EventHub::enableDevice(int32_t deviceId) {
1611 AutoMutex _l(mLock);
1612 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001613 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001614 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1615 return BAD_VALUE;
1616 }
1617 if (device->enabled) {
1618 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
1619 return OK;
1620 }
1621 status_t result = device->enable();
1622 if (result != OK) {
1623 ALOGE("Failed to enable device %" PRId32, deviceId);
1624 return result;
1625 }
1626
Chris Ye989bb932020-07-04 16:18:59 -07001627 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001628
Chris Ye989bb932020-07-04 16:18:59 -07001629 return registerDeviceForEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001630}
1631
1632status_t EventHub::disableDevice(int32_t deviceId) {
1633 AutoMutex _l(mLock);
1634 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001635 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001636 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1637 return BAD_VALUE;
1638 }
1639 if (!device->enabled) {
1640 ALOGW("Duplicate call to %s, input device already disabled", __func__);
1641 return OK;
1642 }
Chris Ye989bb932020-07-04 16:18:59 -07001643 unregisterDeviceFromEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001644 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001645}
1646
1647void EventHub::createVirtualKeyboardLocked() {
1648 InputDeviceIdentifier identifier;
1649 identifier.name = "Virtual";
1650 identifier.uniqueId = "<virtual>";
1651 assignDescriptorLocked(identifier);
1652
Chris Ye989bb932020-07-04 16:18:59 -07001653 std::unique_ptr<Device> device =
1654 std::make_unique<Device>(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
1655 identifier);
Chris Ye1b0c7342020-07-28 21:57:03 -07001656 device->classes = InputDeviceClass::KEYBOARD | InputDeviceClass::ALPHAKEY |
1657 InputDeviceClass::DPAD | InputDeviceClass::VIRTUAL;
Chris Ye989bb932020-07-04 16:18:59 -07001658 device->loadKeyMapLocked();
1659 addDeviceLocked(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001660}
1661
Chris Ye989bb932020-07-04 16:18:59 -07001662void EventHub::addDeviceLocked(std::unique_ptr<Device> device) {
1663 mOpeningDevices.push_back(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001664}
1665
Chris Ye989bb932020-07-04 16:18:59 -07001666int32_t EventHub::getNextControllerNumberLocked(const std::string& name) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001667 if (mControllerNumbers.isFull()) {
1668 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Chris Ye989bb932020-07-04 16:18:59 -07001669 name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001670 return 0;
1671 }
1672 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
1673 // one
1674 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
1675}
1676
Chris Ye989bb932020-07-04 16:18:59 -07001677void EventHub::releaseControllerNumberLocked(int32_t num) {
1678 if (num > 0) {
1679 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001680 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001681}
1682
Chris Ye8594e192020-07-14 10:34:06 -07001683void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001684 Device* device = getDeviceByPathLocked(devicePath);
Chris Ye989bb932020-07-04 16:18:59 -07001685 if (device != nullptr) {
1686 closeDeviceLocked(*device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001687 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001688 }
Chris Ye8594e192020-07-14 10:34:06 -07001689 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001690}
1691
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001692/**
1693 * Find the video device by filename, and close it.
1694 * The video device is closed by path during an inotify event, where we don't have the
1695 * additional context about the video device fd, or the associated input device.
1696 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001697void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001698 // A video device may be owned by an existing input device, or it may be stored in
1699 // the mUnattachedVideoDevices queue. Check both locations.
Chris Ye989bb932020-07-04 16:18:59 -07001700 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001701 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001702 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001703 device->videoDevice = nullptr;
1704 return;
1705 }
1706 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001707 mUnattachedVideoDevices
1708 .erase(std::remove_if(mUnattachedVideoDevices.begin(), mUnattachedVideoDevices.end(),
1709 [&devicePath](
1710 const std::unique_ptr<TouchVideoDevice>& videoDevice) {
1711 return videoDevice->getPath() == devicePath;
1712 }),
1713 mUnattachedVideoDevices.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001714}
1715
1716void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001717 mUnattachedVideoDevices.clear();
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05001718 while (!mDevices.empty()) {
1719 closeDeviceLocked(*(mDevices.begin()->second));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001720 }
1721}
1722
Chris Ye989bb932020-07-04 16:18:59 -07001723void EventHub::closeDeviceLocked(Device& device) {
1724 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=%s", device.path.c_str(),
1725 device.identifier.name.c_str(), device.id, device.fd, device.classes.string().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001726
Chris Ye989bb932020-07-04 16:18:59 -07001727 if (device.id == mBuiltInKeyboardId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001728 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Chris Ye989bb932020-07-04 16:18:59 -07001729 device.path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001730 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
1731 }
1732
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001733 unregisterDeviceFromEpollLocked(device);
Chris Ye989bb932020-07-04 16:18:59 -07001734 if (device.videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001735 // This must be done after the video device is removed from epoll
Chris Ye989bb932020-07-04 16:18:59 -07001736 mUnattachedVideoDevices.push_back(std::move(device.videoDevice));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001737 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001738
Chris Ye989bb932020-07-04 16:18:59 -07001739 releaseControllerNumberLocked(device.controllerNumber);
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05001740 device.controllerNumber = 0;
Chris Ye989bb932020-07-04 16:18:59 -07001741 device.close();
Chris Ye989bb932020-07-04 16:18:59 -07001742 mClosingDevices.push_back(std::move(mDevices[device.id]));
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05001743
Chris Ye989bb932020-07-04 16:18:59 -07001744 mDevices.erase(device.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001745}
1746
1747status_t EventHub::readNotifyLocked() {
1748 int res;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001749 char event_buf[512];
1750 int event_size;
1751 int event_pos = 0;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001752 struct inotify_event* event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001753
1754 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
1755 res = read(mINotifyFd, event_buf, sizeof(event_buf));
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001756 if (res < (int)sizeof(*event)) {
1757 if (errno == EINTR) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001758 ALOGW("could not get event, %s\n", strerror(errno));
1759 return -1;
1760 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001761
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001762 while (res >= (int)sizeof(*event)) {
1763 event = (struct inotify_event*)(event_buf + event_pos);
1764 if (event->len) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001765 if (event->wd == mInputWd) {
Chris Ye8594e192020-07-14 10:34:06 -07001766 std::string filename = std::string(DEVICE_PATH) + "/" + event->name;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001767 if (event->mask & IN_CREATE) {
Chris Ye8594e192020-07-14 10:34:06 -07001768 openDeviceLocked(filename);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001769 } else {
1770 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
Chris Ye8594e192020-07-14 10:34:06 -07001771 closeDeviceByPathLocked(filename);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001772 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001773 } else if (event->wd == mVideoWd) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001774 if (isV4lTouchNode(event->name)) {
Chris Ye8594e192020-07-14 10:34:06 -07001775 std::string filename = std::string(VIDEO_DEVICE_PATH) + "/" + event->name;
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001776 if (event->mask & IN_CREATE) {
1777 openVideoDeviceLocked(filename);
1778 } else {
1779 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
1780 closeVideoDeviceByPathLocked(filename);
1781 }
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001782 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001783 } else {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001784 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event->wd);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001785 }
1786 }
1787 event_size = sizeof(*event) + event->len;
1788 res -= event_size;
1789 event_pos += event_size;
1790 }
1791 return 0;
1792}
1793
Chris Ye8594e192020-07-14 10:34:06 -07001794status_t EventHub::scanDirLocked(const std::string& dirname) {
1795 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
1796 openDeviceLocked(entry.path());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001797 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001798 return 0;
1799}
1800
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001801/**
1802 * Look for all dirname/v4l-touch* devices, and open them.
1803 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001804status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Chris Ye8594e192020-07-14 10:34:06 -07001805 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
1806 if (isV4lTouchNode(entry.path())) {
1807 ALOGI("Found touch video device %s", entry.path().c_str());
1808 openVideoDeviceLocked(entry.path());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001809 }
1810 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001811 return OK;
1812}
1813
Michael Wrightd02c5b62014-02-10 15:10:22 -08001814void EventHub::requestReopenDevices() {
1815 ALOGV("requestReopenDevices() called");
1816
1817 AutoMutex _l(mLock);
1818 mNeedToReopenDevices = true;
1819}
1820
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001821void EventHub::dump(std::string& dump) {
1822 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001823
1824 { // acquire lock
1825 AutoMutex _l(mLock);
1826
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001827 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001828
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001829 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001830
Chris Ye989bb932020-07-04 16:18:59 -07001831 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001832 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001833 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001834 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001835 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001836 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001837 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001838 }
Chris Ye1b0c7342020-07-28 21:57:03 -07001839 dump += StringPrintf(INDENT3 "Classes: %s\n", device->classes.string().c_str());
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001840 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001841 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001842 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
1843 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001844 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001845 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001846 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001847 "product=0x%04x, version=0x%04x\n",
1848 device->identifier.bus, device->identifier.vendor,
1849 device->identifier.product, device->identifier.version);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001850 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001851 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001852 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001853 device->keyMap.keyCharacterMapFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001854 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001855 device->configurationFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001856 dump += StringPrintf(INDENT3 "HaveKeyboardLayoutOverlay: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001857 toString(device->overlayKeyMap != nullptr));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001858 dump += INDENT3 "VideoDevice: ";
1859 if (device->videoDevice) {
1860 dump += device->videoDevice->dump() + "\n";
1861 } else {
1862 dump += "<none>\n";
1863 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001864 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001865
1866 dump += INDENT "Unattached video devices:\n";
1867 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
1868 dump += INDENT2 + videoDevice->dump() + "\n";
1869 }
1870 if (mUnattachedVideoDevices.empty()) {
1871 dump += INDENT2 "<none>\n";
1872 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001873 } // release lock
1874}
1875
1876void EventHub::monitor() {
1877 // Acquire and release the lock to ensure that the event hub has not deadlocked.
1878 mLock.lock();
1879 mLock.unlock();
1880}
1881
Michael Wrightd02c5b62014-02-10 15:10:22 -08001882}; // namespace android