blob: 8f8c0513b267326fa354f5382ca705dfcb3281de [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>
Kim Low03ea0352020-11-06 12:45:07 -080032#include <sys/stat.h>
33#include <sys/sysmacros.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070034#include <unistd.h>
35
Michael Wrightd02c5b62014-02-10 15:10:22 -080036#define LOG_TAG "EventHub"
37
38// #define LOG_NDEBUG 0
Kim Low03ea0352020-11-06 12:45:07 -080039#include <android-base/file.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080040#include <android-base/stringprintf.h>
Philip Quinn39b81682019-01-09 22:20:39 -080041#include <cutils/properties.h>
Chris Ye8594e192020-07-14 10:34:06 -070042#include <input/KeyCharacterMap.h>
43#include <input/KeyLayoutMap.h>
44#include <input/VirtualKeyMap.h>
Dan Albert677d87e2014-06-16 17:31:28 -070045#include <openssl/sha.h>
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070046#include <utils/Errors.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080047#include <utils/Log.h>
48#include <utils/Timers.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080049
Chris Ye8594e192020-07-14 10:34:06 -070050#include <filesystem>
51
52#include "EventHub.h"
Michael Wrightd02c5b62014-02-10 15:10:22 -080053
Michael Wrightd02c5b62014-02-10 15:10:22 -080054#define INDENT " "
55#define INDENT2 " "
56#define INDENT3 " "
57
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080058using android::base::StringPrintf;
Chris Ye1b0c7342020-07-28 21:57:03 -070059using namespace android::flag_operators;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080060
Michael Wrightd02c5b62014-02-10 15:10:22 -080061namespace android {
62
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070063static const char* DEVICE_PATH = "/dev/input";
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080064// v4l2 devices go directly into /dev
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070065static const char* VIDEO_DEVICE_PATH = "/dev";
Michael Wrightd02c5b62014-02-10 15:10:22 -080066
Chris Ye87143712020-11-10 05:05:58 +000067static constexpr int32_t FF_STRONG_MAGNITUDE_CHANNEL_IDX = 0;
68static constexpr int32_t FF_WEAK_MAGNITUDE_CHANNEL_IDX = 1;
Chris Ye6393a262020-08-04 19:41:36 -070069
Kim Low03ea0352020-11-06 12:45:07 -080070// must be kept in sync with definitions in kernel /drivers/power/supply/power_supply_sysfs.c
71static const std::unordered_map<std::string, int32_t> BATTERY_STATUS =
72 {{"Unknown", BATTERY_STATUS_UNKNOWN},
73 {"Charging", BATTERY_STATUS_CHARGING},
74 {"Discharging", BATTERY_STATUS_DISCHARGING},
75 {"Not charging", BATTERY_STATUS_NOT_CHARGING},
76 {"Full", BATTERY_STATUS_FULL}};
77
78// Mapping taken from
79// https://gitlab.freedesktop.org/upower/upower/-/blob/master/src/linux/up-device-supply.c#L484
80static const std::unordered_map<std::string, int32_t> BATTERY_LEVEL = {{"Critical", 5},
81 {"Low", 10},
82 {"Normal", 55},
83 {"High", 70},
84 {"Full", 100},
85 {"Unknown", 50}};
86
Michael Wrightd02c5b62014-02-10 15:10:22 -080087static inline const char* toString(bool value) {
88 return value ? "true" : "false";
89}
90
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010091static std::string sha1(const std::string& in) {
Dan Albert677d87e2014-06-16 17:31:28 -070092 SHA_CTX ctx;
93 SHA1_Init(&ctx);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010094 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
Dan Albert677d87e2014-06-16 17:31:28 -070095 u_char digest[SHA_DIGEST_LENGTH];
96 SHA1_Final(digest, &ctx);
Michael Wrightd02c5b62014-02-10 15:10:22 -080097
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010098 std::string out;
Dan Albert677d87e2014-06-16 17:31:28 -070099 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100100 out += StringPrintf("%02x", digest[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800101 }
102 return out;
103}
104
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800105/**
106 * Return true if name matches "v4l-touch*"
107 */
Chris Ye8594e192020-07-14 10:34:06 -0700108static bool isV4lTouchNode(std::string name) {
109 return name.find("v4l-touch") != std::string::npos;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800110}
111
Philip Quinn39b81682019-01-09 22:20:39 -0800112/**
113 * Returns true if V4L devices should be scanned.
114 *
115 * The system property ro.input.video_enabled can be used to control whether
116 * EventHub scans and opens V4L devices. As V4L does not support multiple
117 * clients, EventHub effectively blocks access to these devices when it opens
Siarhei Vishniakou29f88492019-04-05 14:11:43 -0700118 * them.
119 *
120 * Setting this to "false" would prevent any video devices from being discovered and
121 * associated with input devices.
122 *
123 * This property can be used as follows:
124 * 1. To turn off features that are dependent on video device presence.
125 * 2. During testing and development, to allow other clients to read video devices
126 * directly from /dev.
Philip Quinn39b81682019-01-09 22:20:39 -0800127 */
128static bool isV4lScanningEnabled() {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700129 return property_get_bool("ro.input.video_enabled", true /* default_value */);
Philip Quinn39b81682019-01-09 22:20:39 -0800130}
131
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800132static nsecs_t processEventTimestamp(const struct input_event& event) {
133 // Use the time specified in the event instead of the current time
134 // so that downstream code can get more accurate estimates of
135 // event dispatch latency from the time the event is enqueued onto
136 // the evdev client buffer.
137 //
138 // The event's timestamp fortuitously uses the same monotonic clock
139 // time base as the rest of Android. The kernel event device driver
140 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
141 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
142 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
143 // system call that also queries ktime_get_ts().
144
145 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.time.tv_sec) +
146 microseconds_to_nanoseconds(event.time.tv_usec);
147 return inputEventTime;
148}
149
Kim Low03ea0352020-11-06 12:45:07 -0800150/**
151 * Returns the sysfs root path of the input device
152 *
153 */
154static std::filesystem::path getSysfsRootPath(const char* devicePath) {
155 std::error_code errorCode;
156
157 // Stat the device path to get the major and minor number of the character file
158 struct stat statbuf;
159 if (stat(devicePath, &statbuf) == -1) {
160 ALOGE("Could not stat device %s due to error: %s.", devicePath, std::strerror(errno));
161 return std::filesystem::path();
162 }
163
164 unsigned int major_num = major(statbuf.st_rdev);
165 unsigned int minor_num = minor(statbuf.st_rdev);
166
167 // Realpath "/sys/dev/char/{major}:{minor}" to get the sysfs path to the input event
168 auto sysfsPath = std::filesystem::path("/sys/dev/char/");
169 sysfsPath /= std::to_string(major_num) + ":" + std::to_string(minor_num);
170 sysfsPath = std::filesystem::canonical(sysfsPath, errorCode);
171
172 // Make sure nothing went wrong in call to canonical()
173 if (errorCode) {
174 ALOGW("Could not run filesystem::canonical() due to error %d : %s.", errorCode.value(),
175 errorCode.message().c_str());
176 return std::filesystem::path();
177 }
178
179 // Continue to go up a directory until we reach a directory named "input"
180 while (sysfsPath != "/" && sysfsPath.filename() != "input") {
181 sysfsPath = sysfsPath.parent_path();
182 }
183
184 // Then go up one more and you will be at the sysfs root of the device
185 sysfsPath = sysfsPath.parent_path();
186
187 // Make sure we didn't reach root path and that directory actually exists
188 if (sysfsPath == "/" || !std::filesystem::exists(sysfsPath, errorCode)) {
189 if (errorCode) {
190 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
191 errorCode.message().c_str());
192 }
193
194 // Not found
195 return std::filesystem::path();
196 }
197
198 return sysfsPath;
199}
200
201/**
202 * Returns the power supply node in sys fs
203 *
204 */
205static std::filesystem::path findPowerSupplyNode(const std::filesystem::path& sysfsRootPath) {
206 for (auto path = sysfsRootPath; path != "/"; path = path.parent_path()) {
207 std::error_code errorCode;
208 auto iter = std::filesystem::directory_iterator(path / "power_supply", errorCode);
209 if (!errorCode && iter != std::filesystem::directory_iterator()) {
210 return iter->path();
211 }
212 }
213 // Not found
214 return std::filesystem::path();
215}
216
Michael Wrightd02c5b62014-02-10 15:10:22 -0800217// --- Global Functions ---
218
Chris Ye1b0c7342020-07-28 21:57:03 -0700219Flags<InputDeviceClass> getAbsAxisUsage(int32_t axis, Flags<InputDeviceClass> deviceClasses) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800220 // Touch devices get dibs on touch-related axes.
Chris Ye1b0c7342020-07-28 21:57:03 -0700221 if (deviceClasses.test(InputDeviceClass::TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800222 switch (axis) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700223 case ABS_X:
224 case ABS_Y:
225 case ABS_PRESSURE:
226 case ABS_TOOL_WIDTH:
227 case ABS_DISTANCE:
228 case ABS_TILT_X:
229 case ABS_TILT_Y:
230 case ABS_MT_SLOT:
231 case ABS_MT_TOUCH_MAJOR:
232 case ABS_MT_TOUCH_MINOR:
233 case ABS_MT_WIDTH_MAJOR:
234 case ABS_MT_WIDTH_MINOR:
235 case ABS_MT_ORIENTATION:
236 case ABS_MT_POSITION_X:
237 case ABS_MT_POSITION_Y:
238 case ABS_MT_TOOL_TYPE:
239 case ABS_MT_BLOB_ID:
240 case ABS_MT_TRACKING_ID:
241 case ABS_MT_PRESSURE:
242 case ABS_MT_DISTANCE:
Chris Ye1b0c7342020-07-28 21:57:03 -0700243 return InputDeviceClass::TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800244 }
245 }
246
Chris Yef59a2f42020-10-16 12:55:26 -0700247 if (deviceClasses.test(InputDeviceClass::SENSOR)) {
248 switch (axis) {
249 case ABS_X:
250 case ABS_Y:
251 case ABS_Z:
252 case ABS_RX:
253 case ABS_RY:
254 case ABS_RZ:
255 return InputDeviceClass::SENSOR;
256 }
257 }
258
Michael Wright842500e2015-03-13 17:32:02 -0700259 // External stylus gets the pressure axis
Chris Ye1b0c7342020-07-28 21:57:03 -0700260 if (deviceClasses.test(InputDeviceClass::EXTERNAL_STYLUS)) {
Michael Wright842500e2015-03-13 17:32:02 -0700261 if (axis == ABS_PRESSURE) {
Chris Ye1b0c7342020-07-28 21:57:03 -0700262 return InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -0700263 }
264 }
265
Michael Wrightd02c5b62014-02-10 15:10:22 -0800266 // Joystick devices get the rest.
Chris Ye1b0c7342020-07-28 21:57:03 -0700267 return deviceClasses & InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800268}
269
270// --- EventHub::Device ---
271
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100272EventHub::Device::Device(int fd, int32_t id, const std::string& path,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700273 const InputDeviceIdentifier& identifier)
Chris Ye989bb932020-07-04 16:18:59 -0700274 : fd(fd),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700275 id(id),
276 path(path),
277 identifier(identifier),
278 classes(0),
279 configuration(nullptr),
280 virtualKeyMap(nullptr),
281 ffEffectPlaying(false),
282 ffEffectId(-1),
283 controllerNumber(0),
284 enabled(true),
Chris Ye66fbac32020-07-06 20:36:43 -0700285 isVirtual(fd < 0) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800286
287EventHub::Device::~Device() {
288 close();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800289}
290
291void EventHub::Device::close() {
292 if (fd >= 0) {
293 ::close(fd);
294 fd = -1;
295 }
296}
297
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700298status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100299 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700300 if (fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100301 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700302 return -errno;
303 }
304 enabled = true;
305 return OK;
306}
307
308status_t EventHub::Device::disable() {
309 close();
310 enabled = false;
311 return OK;
312}
313
Chris Ye989bb932020-07-04 16:18:59 -0700314bool EventHub::Device::hasValidFd() const {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700315 return !isVirtual && enabled;
316}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800317
Chris Ye3a1e4462020-08-12 10:13:15 -0700318const std::shared_ptr<KeyCharacterMap> EventHub::Device::getKeyCharacterMap() const {
Chris Ye989bb932020-07-04 16:18:59 -0700319 return keyMap.keyCharacterMap;
320}
321
322template <std::size_t N>
323status_t EventHub::Device::readDeviceBitMask(unsigned long ioctlCode, BitArray<N>& bitArray) {
324 if (!hasValidFd()) {
325 return BAD_VALUE;
326 }
327 if ((_IOC_SIZE(ioctlCode) == 0)) {
328 ioctlCode |= _IOC(0, 0, 0, bitArray.bytes());
329 }
330
331 typename BitArray<N>::Buffer buffer;
332 status_t ret = ioctl(fd, ioctlCode, buffer.data());
333 bitArray.loadFromBuffer(buffer);
334 return ret;
335}
336
337void EventHub::Device::configureFd() {
338 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
339 if (classes.test(InputDeviceClass::KEYBOARD)) {
340 // Disable kernel key repeat since we handle it ourselves
341 unsigned int repeatRate[] = {0, 0};
342 if (ioctl(fd, EVIOCSREP, repeatRate)) {
343 ALOGW("Unable to disable kernel key repeat for %s: %s", path.c_str(), strerror(errno));
344 }
345 }
346
347 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
348 // associated with input events. This is important because the input system
349 // uses the timestamps extensively and assumes they were recorded using the monotonic
350 // clock.
351 int clockId = CLOCK_MONOTONIC;
Chris Yef59a2f42020-10-16 12:55:26 -0700352 if (classes.test(InputDeviceClass::SENSOR)) {
353 // Each new sensor event should use the same time base as
354 // SystemClock.elapsedRealtimeNanos().
355 clockId = CLOCK_BOOTTIME;
356 }
Chris Ye989bb932020-07-04 16:18:59 -0700357 bool usingClockIoctl = !ioctl(fd, EVIOCSCLOCKID, &clockId);
358 ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
359}
360
361bool EventHub::Device::hasKeycodeLocked(int keycode) const {
362 if (!keyMap.haveKeyLayout()) {
363 return false;
364 }
365
366 std::vector<int32_t> scanCodes;
367 keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes);
368 const size_t N = scanCodes.size();
369 for (size_t i = 0; i < N && i <= KEY_MAX; i++) {
370 int32_t sc = scanCodes[i];
371 if (sc >= 0 && sc <= KEY_MAX && keyBitmask.test(sc)) {
372 return true;
373 }
374 }
375
376 return false;
377}
378
379void EventHub::Device::loadConfigurationLocked() {
380 configurationFile =
381 getInputDeviceConfigurationFilePathByDeviceIdentifier(identifier,
382 InputDeviceConfigurationFileType::
383 CONFIGURATION);
384 if (configurationFile.empty()) {
385 ALOGD("No input device configuration file found for device '%s'.", identifier.name.c_str());
386 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500387 android::base::Result<std::unique_ptr<PropertyMap>> propertyMap =
388 PropertyMap::load(configurationFile.c_str());
389 if (!propertyMap.ok()) {
Chris Ye989bb932020-07-04 16:18:59 -0700390 ALOGE("Error loading input device configuration file for device '%s'. "
391 "Using default configuration.",
392 identifier.name.c_str());
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500393 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500394 configuration = std::move(*propertyMap);
Chris Ye989bb932020-07-04 16:18:59 -0700395 }
396 }
397}
398
399bool EventHub::Device::loadVirtualKeyMapLocked() {
400 // The virtual key map is supplied by the kernel as a system board property file.
401 std::string propPath = "/sys/board_properties/virtualkeys.";
402 propPath += identifier.getCanonicalName();
403 if (access(propPath.c_str(), R_OK)) {
404 return false;
405 }
406 virtualKeyMap = VirtualKeyMap::load(propPath);
407 return virtualKeyMap != nullptr;
408}
409
410status_t EventHub::Device::loadKeyMapLocked() {
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500411 return keyMap.load(identifier, configuration.get());
Chris Ye989bb932020-07-04 16:18:59 -0700412}
413
414bool EventHub::Device::isExternalDeviceLocked() {
415 if (configuration) {
416 bool value;
417 if (configuration->tryGetProperty(String8("device.internal"), value)) {
418 return !value;
419 }
420 }
421 return identifier.bus == BUS_USB || identifier.bus == BUS_BLUETOOTH;
422}
423
424bool EventHub::Device::deviceHasMicLocked() {
425 if (configuration) {
426 bool value;
427 if (configuration->tryGetProperty(String8("audio.mic"), value)) {
428 return value;
429 }
430 }
431 return false;
432}
433
434void EventHub::Device::setLedStateLocked(int32_t led, bool on) {
435 int32_t sc;
436 if (hasValidFd() && mapLed(led, &sc) != NAME_NOT_FOUND) {
437 struct input_event ev;
438 ev.time.tv_sec = 0;
439 ev.time.tv_usec = 0;
440 ev.type = EV_LED;
441 ev.code = sc;
442 ev.value = on ? 1 : 0;
443
444 ssize_t nWrite;
445 do {
446 nWrite = write(fd, &ev, sizeof(struct input_event));
447 } while (nWrite == -1 && errno == EINTR);
448 }
449}
450
451void EventHub::Device::setLedForControllerLocked() {
452 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
453 setLedStateLocked(ALED_CONTROLLER_1 + i, controllerNumber == i + 1);
454 }
455}
456
457status_t EventHub::Device::mapLed(int32_t led, int32_t* outScanCode) const {
458 if (!keyMap.haveKeyLayout()) {
459 return NAME_NOT_FOUND;
460 }
461
462 int32_t scanCode;
463 if (keyMap.keyLayoutMap->findScanCodeForLed(led, &scanCode) != NAME_NOT_FOUND) {
464 if (scanCode >= 0 && scanCode <= LED_MAX && ledBitmask.test(scanCode)) {
465 *outScanCode = scanCode;
466 return NO_ERROR;
467 }
468 }
469 return NAME_NOT_FOUND;
470}
471
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100472/**
473 * Get the capabilities for the current process.
474 * Crashes the system if unable to create / check / destroy the capabilities object.
475 */
476class Capabilities final {
477public:
478 explicit Capabilities() {
479 mCaps = cap_get_proc();
480 LOG_ALWAYS_FATAL_IF(mCaps == nullptr, "Could not get capabilities of the current process");
481 }
482
483 /**
484 * Check whether the current process has a specific capability
485 * in the set of effective capabilities.
486 * Return CAP_SET if the process has the requested capability
487 * Return CAP_CLEAR otherwise.
488 */
489 cap_flag_value_t checkEffectiveCapability(cap_value_t capability) {
490 cap_flag_value_t value;
491 const int result = cap_get_flag(mCaps, capability, CAP_EFFECTIVE, &value);
492 LOG_ALWAYS_FATAL_IF(result == -1, "Could not obtain the requested capability");
493 return value;
494 }
495
496 ~Capabilities() {
497 const int result = cap_free(mCaps);
498 LOG_ALWAYS_FATAL_IF(result == -1, "Could not release the capabilities structure");
499 }
500
501private:
502 cap_t mCaps;
503};
504
505static void ensureProcessCanBlockSuspend() {
506 Capabilities capabilities;
507 const bool canBlockSuspend =
508 capabilities.checkEffectiveCapability(CAP_BLOCK_SUSPEND) == CAP_SET;
509 LOG_ALWAYS_FATAL_IF(!canBlockSuspend,
510 "Input must be able to block suspend to properly process events");
511}
512
Michael Wrightd02c5b62014-02-10 15:10:22 -0800513// --- EventHub ---
514
Michael Wrightd02c5b62014-02-10 15:10:22 -0800515const int EventHub::EPOLL_MAX_EVENTS;
516
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700517EventHub::EventHub(void)
518 : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
519 mNextDeviceId(1),
520 mControllerNumbers(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800521 mNeedToSendFinishedDeviceScan(false),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700522 mNeedToReopenDevices(false),
523 mNeedToScanDevices(true),
524 mPendingEventCount(0),
525 mPendingEventIndex(0),
526 mPendingINotify(false) {
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100527 ensureProcessCanBlockSuspend();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800528
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800529 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800530 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800531
532 mINotifyFd = inotify_init();
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800533 mInputWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700534 LOG_ALWAYS_FATAL_IF(mInputWd < 0, "Could not register INotify for %s: %s", DEVICE_PATH,
535 strerror(errno));
Philip Quinn39b81682019-01-09 22:20:39 -0800536 if (isV4lScanningEnabled()) {
537 mVideoWd = inotify_add_watch(mINotifyFd, VIDEO_DEVICE_PATH, IN_DELETE | IN_CREATE);
538 LOG_ALWAYS_FATAL_IF(mVideoWd < 0, "Could not register INotify for %s: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700539 VIDEO_DEVICE_PATH, strerror(errno));
Philip Quinn39b81682019-01-09 22:20:39 -0800540 } else {
541 mVideoWd = -1;
542 ALOGI("Video device scanning disabled");
543 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800544
Siarhei Vishniakou2d0e9482019-09-24 12:52:47 +0100545 struct epoll_event eventItem = {};
546 eventItem.events = EPOLLIN | EPOLLWAKEUP;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700547 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800548 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800549 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
550
551 int wakeFds[2];
552 result = pipe(wakeFds);
553 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
554
555 mWakeReadPipeFd = wakeFds[0];
556 mWakeWritePipeFd = wakeFds[1];
557
558 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
559 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700560 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800561
562 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
563 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700564 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800565
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700566 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800567 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
568 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700569 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800570}
571
572EventHub::~EventHub(void) {
573 closeAllDevicesLocked();
574
Michael Wrightd02c5b62014-02-10 15:10:22 -0800575 ::close(mEpollFd);
576 ::close(mINotifyFd);
577 ::close(mWakeReadPipeFd);
578 ::close(mWakeWritePipeFd);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800579}
580
581InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000582 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800583 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700584 return device != nullptr ? device->identifier : InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800585}
586
Chris Ye1b0c7342020-07-28 21:57:03 -0700587Flags<InputDeviceClass> EventHub::getDeviceClasses(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000588 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800589 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700590 return device != nullptr ? device->classes : Flags<InputDeviceClass>(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800591}
592
593int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000594 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800595 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700596 return device != nullptr ? device->controllerNumber : 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800597}
598
599void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
Chris Ye87143712020-11-10 05:05:58 +0000600 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800601 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700602 if (device != nullptr && device->configuration) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800603 *outConfiguration = *device->configuration;
604 } else {
605 outConfiguration->clear();
606 }
607}
608
609status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700610 RawAbsoluteAxisInfo* outAxisInfo) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800611 outAxisInfo->clear();
612
613 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000614 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800615
616 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700617 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800618 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700619 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
620 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
621 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800622 return -errno;
623 }
624
625 if (info.minimum != info.maximum) {
626 outAxisInfo->valid = true;
627 outAxisInfo->minValue = info.minimum;
628 outAxisInfo->maxValue = info.maximum;
629 outAxisInfo->flat = info.flat;
630 outAxisInfo->fuzz = info.fuzz;
631 outAxisInfo->resolution = info.resolution;
632 }
633 return OK;
634 }
635 }
636 return -1;
637}
638
639bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
640 if (axis >= 0 && axis <= REL_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000641 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800642 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700643 return device != nullptr ? device->relBitmask.test(axis) : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800644 }
645 return false;
646}
647
648bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
Chris Ye87143712020-11-10 05:05:58 +0000649 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800650
Chris Ye989bb932020-07-04 16:18:59 -0700651 Device* device = getDeviceLocked(deviceId);
652 return property >= 0 && property <= INPUT_PROP_MAX && device != nullptr
653 ? device->propBitmask.test(property)
654 : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800655}
656
Chris Yef59a2f42020-10-16 12:55:26 -0700657bool EventHub::hasMscEvent(int32_t deviceId, int mscEvent) const {
658 std::scoped_lock _l(mLock);
659
660 Device* device = getDeviceLocked(deviceId);
661 return mscEvent >= 0 && mscEvent <= MSC_MAX && device != nullptr
662 ? device->mscBitmask.test(mscEvent)
663 : false;
664}
665
Michael Wrightd02c5b62014-02-10 15:10:22 -0800666int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
667 if (scanCode >= 0 && scanCode <= KEY_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000668 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800669
670 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700671 if (device != nullptr && device->hasValidFd() && device->keyBitmask.test(scanCode)) {
672 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
673 return device->keyState.test(scanCode) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800674 }
675 }
676 }
677 return AKEY_STATE_UNKNOWN;
678}
679
680int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
Chris Ye87143712020-11-10 05:05:58 +0000681 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800682
683 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700684 if (device != nullptr && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800685 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800686 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode, &scanCodes);
687 if (scanCodes.size() != 0) {
Chris Ye66fbac32020-07-06 20:36:43 -0700688 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800689 for (size_t i = 0; i < scanCodes.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800690 int32_t sc = scanCodes[i];
Chris Ye66fbac32020-07-06 20:36:43 -0700691 if (sc >= 0 && sc <= KEY_MAX && device->keyState.test(sc)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800692 return AKEY_STATE_DOWN;
693 }
694 }
695 return AKEY_STATE_UP;
696 }
697 }
698 }
699 return AKEY_STATE_UNKNOWN;
700}
701
702int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
703 if (sw >= 0 && sw <= SW_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000704 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800705
706 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700707 if (device != nullptr && device->hasValidFd() && device->swBitmask.test(sw)) {
708 if (device->readDeviceBitMask(EVIOCGSW(0), device->swState) >= 0) {
709 return device->swState.test(sw) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800710 }
711 }
712 }
713 return AKEY_STATE_UNKNOWN;
714}
715
716status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
717 *outValue = 0;
718
719 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000720 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800721
722 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700723 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800724 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700725 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
726 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
727 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800728 return -errno;
729 }
730
731 *outValue = info.value;
732 return OK;
733 }
734 }
735 return -1;
736}
737
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700738bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes, const int32_t* keyCodes,
739 uint8_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +0000740 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800741
742 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700743 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800744 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800745 for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) {
746 scanCodes.clear();
747
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700748 status_t err = device->keyMap.keyLayoutMap->findScanCodesForKey(keyCodes[codeIndex],
749 &scanCodes);
750 if (!err) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800751 // check the possible scan codes identified by the layout map against the
752 // map of codes actually emitted by the driver
753 for (size_t sc = 0; sc < scanCodes.size(); sc++) {
Chris Ye66fbac32020-07-06 20:36:43 -0700754 if (device->keyBitmask.test(scanCodes[sc])) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800755 outFlags[codeIndex] = 1;
756 break;
757 }
758 }
759 }
760 }
761 return true;
762 }
763 return false;
764}
765
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700766status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
767 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +0000768 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800769 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700770 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800771
Chris Ye66fbac32020-07-06 20:36:43 -0700772 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800773 // Check the key character map first.
Chris Ye3a1e4462020-08-12 10:13:15 -0700774 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
775 if (kcm) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800776 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
777 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700778 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800779 }
780 }
781
782 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700783 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800784 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700785 status = NO_ERROR;
786 }
787 }
788
789 if (status == NO_ERROR) {
Chris Ye3a1e4462020-08-12 10:13:15 -0700790 if (kcm) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700791 kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState);
792 } else {
793 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800794 }
795 }
796 }
797
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700798 if (status != NO_ERROR) {
799 *outKeycode = 0;
800 *outFlags = 0;
801 *outMetaState = metaState;
802 }
803
804 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800805}
806
807status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
Chris Ye87143712020-11-10 05:05:58 +0000808 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800809 Device* device = getDeviceLocked(deviceId);
810
Chris Ye66fbac32020-07-06 20:36:43 -0700811 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800812 status_t err = device->keyMap.keyLayoutMap->mapAxis(scanCode, outAxisInfo);
813 if (err == NO_ERROR) {
814 return NO_ERROR;
815 }
816 }
817
818 return NAME_NOT_FOUND;
819}
820
Chris Yef59a2f42020-10-16 12:55:26 -0700821base::Result<std::pair<InputDeviceSensorType, int32_t>> EventHub::mapSensor(int32_t deviceId,
822 int32_t absCode) {
823 std::scoped_lock _l(mLock);
824 Device* device = getDeviceLocked(deviceId);
825
826 if (device != nullptr && device->keyMap.haveKeyLayout()) {
827 return device->keyMap.keyLayoutMap->mapSensor(absCode);
828 }
829 return Errorf("Device not found or device has no key layout.");
830}
831
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100832void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Chris Ye87143712020-11-10 05:05:58 +0000833 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800834
835 mExcludedDevices = devices;
836}
837
838bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
Chris Ye87143712020-11-10 05:05:58 +0000839 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800840 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700841 if (device != nullptr && scanCode >= 0 && scanCode <= KEY_MAX) {
842 return device->keyBitmask.test(scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800843 }
844 return false;
845}
846
847bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
Chris Ye87143712020-11-10 05:05:58 +0000848 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800849 Device* device = getDeviceLocked(deviceId);
850 int32_t sc;
Chris Ye989bb932020-07-04 16:18:59 -0700851 if (device != nullptr && device->mapLed(led, &sc) == NO_ERROR) {
Chris Ye66fbac32020-07-06 20:36:43 -0700852 return device->ledBitmask.test(sc);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800853 }
854 return false;
855}
856
857void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
Chris Ye87143712020-11-10 05:05:58 +0000858 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800859 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700860 if (device != nullptr && device->hasValidFd()) {
861 device->setLedStateLocked(led, on);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800862 }
863}
864
865void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700866 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800867 outVirtualKeys.clear();
868
Chris Ye87143712020-11-10 05:05:58 +0000869 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800870 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700871 if (device != nullptr && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800872 const std::vector<VirtualKeyDefinition> virtualKeys =
873 device->virtualKeyMap->getVirtualKeys();
874 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800875 }
876}
877
Chris Ye3a1e4462020-08-12 10:13:15 -0700878const std::shared_ptr<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000879 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800880 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700881 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800882 return device->getKeyCharacterMap();
883 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700884 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800885}
886
Chris Ye3a1e4462020-08-12 10:13:15 -0700887bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, std::shared_ptr<KeyCharacterMap> map) {
Chris Ye87143712020-11-10 05:05:58 +0000888 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800889 Device* device = getDeviceLocked(deviceId);
Chris Ye3a1e4462020-08-12 10:13:15 -0700890 if (device != nullptr && map != nullptr && device->keyMap.keyCharacterMap != nullptr) {
891 device->keyMap.keyCharacterMap->combine(*map);
892 device->keyMap.keyCharacterMapFile = device->keyMap.keyCharacterMap->getLoadFileName();
893 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800894 }
895 return false;
896}
897
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100898static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
899 std::string rawDescriptor;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700900 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800901 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100902 if (!identifier.uniqueId.empty()) {
903 rawDescriptor += "uniqueId:";
904 rawDescriptor += identifier.uniqueId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800905 } else if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100906 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800907 }
908
909 if (identifier.vendor == 0 && identifier.product == 0) {
910 // If we don't know the vendor and product id, then the device is probably
911 // built-in so we need to rely on other information to uniquely identify
912 // the input device. Usually we try to avoid relying on the device name or
913 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100914 if (!identifier.name.empty()) {
915 rawDescriptor += "name:";
916 rawDescriptor += identifier.name;
917 } else if (!identifier.location.empty()) {
918 rawDescriptor += "location:";
919 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800920 }
921 }
922 identifier.descriptor = sha1(rawDescriptor);
923 return rawDescriptor;
924}
925
926void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
927 // Compute a device descriptor that uniquely identifies the device.
928 // The descriptor is assumed to be a stable identifier. Its value should not
929 // change between reboots, reconnections, firmware updates or new releases
930 // of Android. In practice we sometimes get devices that cannot be uniquely
931 // identified. In this case we enforce uniqueness between connected devices.
932 // Ideally, we also want the descriptor to be short and relatively opaque.
933
934 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100935 std::string rawDescriptor = generateDescriptor(identifier);
936 if (identifier.uniqueId.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800937 // If it didn't have a unique id check for conflicts and enforce
938 // uniqueness if necessary.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700939 while (getDeviceByDescriptorLocked(identifier.descriptor) != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800940 identifier.nonce++;
941 rawDescriptor = generateDescriptor(identifier);
942 }
943 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100944 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700945 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800946}
947
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +0000948void EventHub::vibrate(int32_t deviceId, const VibrationElement& element) {
Chris Ye87143712020-11-10 05:05:58 +0000949 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800950 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700951 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800952 ff_effect effect;
953 memset(&effect, 0, sizeof(effect));
954 effect.type = FF_RUMBLE;
955 effect.id = device->ffEffectId;
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +0000956 // evdev FF_RUMBLE effect only supports two channels of vibration.
Chris Ye6393a262020-08-04 19:41:36 -0700957 effect.u.rumble.strong_magnitude = element.getMagnitude(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
958 effect.u.rumble.weak_magnitude = element.getMagnitude(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +0000959 effect.replay.length = element.duration.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800960 effect.replay.delay = 0;
961 if (ioctl(device->fd, EVIOCSFF, &effect)) {
962 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700963 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800964 return;
965 }
966 device->ffEffectId = effect.id;
967
968 struct input_event ev;
969 ev.time.tv_sec = 0;
970 ev.time.tv_usec = 0;
971 ev.type = EV_FF;
972 ev.code = device->ffEffectId;
973 ev.value = 1;
974 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
975 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700976 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800977 return;
978 }
979 device->ffEffectPlaying = true;
980 }
981}
982
983void EventHub::cancelVibrate(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +0000984 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800985 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700986 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800987 if (device->ffEffectPlaying) {
988 device->ffEffectPlaying = false;
989
990 struct input_event ev;
991 ev.time.tv_sec = 0;
992 ev.time.tv_usec = 0;
993 ev.type = EV_FF;
994 ev.code = device->ffEffectId;
995 ev.value = 0;
996 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
997 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700998 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800999 return;
1000 }
1001 }
1002 }
1003}
1004
Chris Ye87143712020-11-10 05:05:58 +00001005std::vector<int32_t> EventHub::getVibratorIds(int32_t deviceId) {
1006 std::scoped_lock _l(mLock);
1007 std::vector<int32_t> vibrators;
1008 Device* device = getDeviceLocked(deviceId);
1009 if (device != nullptr && device->hasValidFd() &&
1010 device->classes.test(InputDeviceClass::VIBRATOR)) {
1011 vibrators.push_back(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1012 vibrators.push_back(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
1013 }
1014 return vibrators;
1015}
1016
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001017EventHub::Device* EventHub::getDeviceByDescriptorLocked(const std::string& descriptor) const {
Chris Ye989bb932020-07-04 16:18:59 -07001018 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001019 if (descriptor == device->identifier.descriptor) {
Chris Ye989bb932020-07-04 16:18:59 -07001020 return device.get();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001021 }
1022 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001023 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001024}
1025
1026EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001027 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001028 deviceId = mBuiltInKeyboardId;
1029 }
Chris Ye989bb932020-07-04 16:18:59 -07001030 const auto& it = mDevices.find(deviceId);
1031 return it != mDevices.end() ? it->second.get() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001032}
1033
Chris Ye8594e192020-07-14 10:34:06 -07001034EventHub::Device* EventHub::getDeviceByPathLocked(const std::string& devicePath) const {
Chris Ye989bb932020-07-04 16:18:59 -07001035 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001036 if (device->path == devicePath) {
Chris Ye989bb932020-07-04 16:18:59 -07001037 return device.get();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001038 }
1039 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001040 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001041}
1042
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001043/**
1044 * The file descriptor could be either input device, or a video device (associated with a
1045 * specific input device). Check both cases here, and return the device that this event
1046 * belongs to. Caller can compare the fd's once more to determine event type.
1047 * Looks through all input devices, and only attached video devices. Unattached video
1048 * devices are ignored.
1049 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001050EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
Chris Ye989bb932020-07-04 16:18:59 -07001051 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001052 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001053 // This is an input device event
Chris Ye989bb932020-07-04 16:18:59 -07001054 return device.get();
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001055 }
1056 if (device->videoDevice && device->videoDevice->getFd() == fd) {
1057 // This is a video device event
Chris Ye989bb932020-07-04 16:18:59 -07001058 return device.get();
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001059 }
1060 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001061 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
1062 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001063 return nullptr;
1064}
1065
Kim Low03ea0352020-11-06 12:45:07 -08001066std::optional<int32_t> EventHub::getBatteryCapacity(int32_t deviceId) const {
1067 std::scoped_lock _l(mLock);
1068 Device* device = getDeviceLocked(deviceId);
1069 std::string buffer;
1070
1071 if (!device || (device->sysfsBatteryPath.empty())) {
1072 return std::nullopt;
1073 }
1074
1075 // Some devices report battery capacity as an integer through the "capacity" file
1076 if (base::ReadFileToString(device->sysfsBatteryPath / "capacity", &buffer)) {
1077 return std::stoi(buffer);
1078 }
1079
1080 // Other devices report capacity as an enum value POWER_SUPPLY_CAPACITY_LEVEL_XXX
1081 // These values are taken from kernel source code include/linux/power_supply.h
1082 if (base::ReadFileToString(device->sysfsBatteryPath / "capacity_level", &buffer)) {
1083 const auto it = BATTERY_LEVEL.find(buffer);
1084 if (it != BATTERY_LEVEL.end()) {
1085 return it->second;
1086 }
1087 }
1088 return std::nullopt;
1089}
1090
1091std::optional<int32_t> EventHub::getBatteryStatus(int32_t deviceId) const {
1092 std::scoped_lock _l(mLock);
1093 Device* device = getDeviceLocked(deviceId);
1094 std::string buffer;
1095
1096 if (!device || (device->sysfsBatteryPath.empty())) {
1097 return std::nullopt;
1098 }
1099
1100 if (!base::ReadFileToString(device->sysfsBatteryPath / "status", &buffer)) {
1101 ALOGE("Failed to read sysfs battery info: %s", strerror(errno));
1102 return std::nullopt;
1103 }
1104
1105 // Remove trailing new line
1106 buffer.erase(std::remove(buffer.begin(), buffer.end(), '\n'), buffer.end());
1107 const auto it = BATTERY_STATUS.find(buffer);
1108
1109 if (it != BATTERY_STATUS.end()) {
1110 return it->second;
1111 }
1112
1113 return std::nullopt;
1114}
1115
Michael Wrightd02c5b62014-02-10 15:10:22 -08001116size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
1117 ALOG_ASSERT(bufferSize >= 1);
1118
Chris Ye87143712020-11-10 05:05:58 +00001119 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001120
1121 struct input_event readBuffer[bufferSize];
1122
1123 RawEvent* event = buffer;
1124 size_t capacity = bufferSize;
1125 bool awoken = false;
1126 for (;;) {
1127 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
1128
1129 // Reopen input devices if needed.
1130 if (mNeedToReopenDevices) {
1131 mNeedToReopenDevices = false;
1132
1133 ALOGI("Reopening all input devices due to a configuration change.");
1134
1135 closeAllDevicesLocked();
1136 mNeedToScanDevices = true;
1137 break; // return to the caller before we actually rescan
1138 }
1139
1140 // Report any devices that had last been added/removed.
Chris Ye989bb932020-07-04 16:18:59 -07001141 for (auto it = mClosingDevices.begin(); it != mClosingDevices.end();) {
1142 std::unique_ptr<Device> device = std::move(*it);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001143 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001144 event->when = now;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001145 event->deviceId = (device->id == mBuiltInKeyboardId)
1146 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
1147 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001148 event->type = DEVICE_REMOVED;
1149 event += 1;
Chris Ye989bb932020-07-04 16:18:59 -07001150 it = mClosingDevices.erase(it);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001151 mNeedToSendFinishedDeviceScan = true;
1152 if (--capacity == 0) {
1153 break;
1154 }
1155 }
1156
1157 if (mNeedToScanDevices) {
1158 mNeedToScanDevices = false;
1159 scanDevicesLocked();
1160 mNeedToSendFinishedDeviceScan = true;
1161 }
1162
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001163 while (!mOpeningDevices.empty()) {
1164 std::unique_ptr<Device> device = std::move(*mOpeningDevices.rbegin());
1165 mOpeningDevices.pop_back();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001166 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001167 event->when = now;
1168 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1169 event->type = DEVICE_ADDED;
1170 event += 1;
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001171
1172 // Try to find a matching video device by comparing device names
1173 for (auto it = mUnattachedVideoDevices.begin(); it != mUnattachedVideoDevices.end();
1174 it++) {
1175 std::unique_ptr<TouchVideoDevice>& videoDevice = *it;
1176 if (tryAddVideoDevice(*device, videoDevice)) {
1177 // videoDevice was transferred to 'device'
1178 it = mUnattachedVideoDevices.erase(it);
1179 break;
1180 }
1181 }
1182
1183 auto [dev_it, inserted] = mDevices.insert_or_assign(device->id, std::move(device));
1184 if (!inserted) {
Chris Ye989bb932020-07-04 16:18:59 -07001185 ALOGW("Device id %d exists, replaced.", device->id);
1186 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001187 mNeedToSendFinishedDeviceScan = true;
1188 if (--capacity == 0) {
1189 break;
1190 }
1191 }
1192
1193 if (mNeedToSendFinishedDeviceScan) {
1194 mNeedToSendFinishedDeviceScan = false;
1195 event->when = now;
1196 event->type = FINISHED_DEVICE_SCAN;
1197 event += 1;
1198 if (--capacity == 0) {
1199 break;
1200 }
1201 }
1202
1203 // Grab the next input event.
1204 bool deviceChanged = false;
1205 while (mPendingEventIndex < mPendingEventCount) {
1206 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001207 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001208 if (eventItem.events & EPOLLIN) {
1209 mPendingINotify = true;
1210 } else {
1211 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
1212 }
1213 continue;
1214 }
1215
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001216 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001217 if (eventItem.events & EPOLLIN) {
1218 ALOGV("awoken after wake()");
1219 awoken = true;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001220 char wakeReadBuffer[16];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001221 ssize_t nRead;
1222 do {
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001223 nRead = read(mWakeReadPipeFd, wakeReadBuffer, sizeof(wakeReadBuffer));
1224 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(wakeReadBuffer));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001225 } else {
1226 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001227 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228 }
1229 continue;
1230 }
1231
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001232 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Chris Ye989bb932020-07-04 16:18:59 -07001233 if (device == nullptr) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001234 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
1235 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001236 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237 continue;
1238 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001239 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
1240 if (eventItem.events & EPOLLIN) {
1241 size_t numFrames = device->videoDevice->readAndQueueFrames();
1242 if (numFrames == 0) {
1243 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001244 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001245 }
1246 } else if (eventItem.events & EPOLLHUP) {
1247 // TODO(b/121395353) - consider adding EPOLLRDHUP
1248 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001249 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001250 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1251 device->videoDevice = nullptr;
1252 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001253 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1254 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001255 ALOG_ASSERT(!DEBUG);
1256 }
1257 continue;
1258 }
1259 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -08001260 if (eventItem.events & EPOLLIN) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001261 int32_t readSize =
1262 read(device->fd, readBuffer, sizeof(struct input_event) * capacity);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001263 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
1264 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -07001265 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001266 " bufferSize: %zu capacity: %zu errno: %d)\n",
1267 device->fd, readSize, bufferSize, capacity, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001268 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001269 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001270 } else if (readSize < 0) {
1271 if (errno != EAGAIN && errno != EINTR) {
1272 ALOGW("could not get event (errno=%d)", errno);
1273 }
1274 } else if ((readSize % sizeof(struct input_event)) != 0) {
1275 ALOGE("could not get event (wrong size: %d)", readSize);
1276 } else {
1277 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1278
1279 size_t count = size_t(readSize) / sizeof(struct input_event);
1280 for (size_t i = 0; i < count; i++) {
1281 struct input_event& iev = readBuffer[i];
Siarhei Vishniakou592bac22018-11-08 19:42:38 -08001282 event->when = processEventTimestamp(iev);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001283 event->deviceId = deviceId;
1284 event->type = iev.type;
1285 event->code = iev.code;
1286 event->value = iev.value;
1287 event += 1;
1288 capacity -= 1;
1289 }
1290 if (capacity == 0) {
1291 // The result buffer is full. Reset the pending event index
1292 // so we will try to read the device again on the next iteration.
1293 mPendingEventIndex -= 1;
1294 break;
1295 }
1296 }
1297 } else if (eventItem.events & EPOLLHUP) {
1298 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001299 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001300 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001301 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001302 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001303 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1304 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001305 }
1306 }
1307
1308 // readNotify() will modify the list of devices so this must be done after
1309 // processing all other events to ensure that we read all remaining events
1310 // before closing the devices.
1311 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
1312 mPendingINotify = false;
1313 readNotifyLocked();
1314 deviceChanged = true;
1315 }
1316
1317 // Report added or removed devices immediately.
1318 if (deviceChanged) {
1319 continue;
1320 }
1321
1322 // Return now if we have collected any events or if we were explicitly awoken.
1323 if (event != buffer || awoken) {
1324 break;
1325 }
1326
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001327 // Poll for events.
1328 // When a device driver has pending (unread) events, it acquires
1329 // a kernel wake lock. Once the last pending event has been read, the device
1330 // driver will release the kernel wake lock, but the epoll will hold the wakelock,
1331 // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
1332 // is called again for the same fd that produced the event.
1333 // Thus the system can only sleep if there are no events pending or
1334 // currently being processed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001335 //
1336 // The timeout is advisory only. If the device is asleep, it will not wake just to
1337 // service the timeout.
1338 mPendingEventIndex = 0;
1339
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001340 mLock.unlock(); // release lock before poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001341
1342 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1343
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001344 mLock.lock(); // reacquire lock after poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001345
1346 if (pollResult == 0) {
1347 // Timed out.
1348 mPendingEventCount = 0;
1349 break;
1350 }
1351
1352 if (pollResult < 0) {
1353 // An error occurred.
1354 mPendingEventCount = 0;
1355
1356 // Sleep after errors to avoid locking up the system.
1357 // Hopefully the error is transient.
1358 if (errno != EINTR) {
1359 ALOGW("poll failed (errno=%d)\n", errno);
1360 usleep(100000);
1361 }
1362 } else {
1363 // Some events occurred.
1364 mPendingEventCount = size_t(pollResult);
1365 }
1366 }
1367
1368 // All done, return the number of events we read.
1369 return event - buffer;
1370}
1371
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001372std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001373 std::scoped_lock _l(mLock);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001374
1375 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001376 if (device == nullptr || !device->videoDevice) {
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001377 return {};
1378 }
1379 return device->videoDevice->consumeFrames();
1380}
1381
Michael Wrightd02c5b62014-02-10 15:10:22 -08001382void EventHub::wake() {
1383 ALOGV("wake() called");
1384
1385 ssize_t nWrite;
1386 do {
1387 nWrite = write(mWakeWritePipeFd, "W", 1);
1388 } while (nWrite == -1 && errno == EINTR);
1389
1390 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001391 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001392 }
1393}
1394
1395void EventHub::scanDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001396 status_t result = scanDirLocked(DEVICE_PATH);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001397 if (result < 0) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001398 ALOGE("scan dir failed for %s", DEVICE_PATH);
1399 }
Philip Quinn39b81682019-01-09 22:20:39 -08001400 if (isV4lScanningEnabled()) {
1401 result = scanVideoDirLocked(VIDEO_DEVICE_PATH);
1402 if (result != OK) {
1403 ALOGE("scan video dir failed for %s", VIDEO_DEVICE_PATH);
1404 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001405 }
Chris Ye989bb932020-07-04 16:18:59 -07001406 if (mDevices.find(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) == mDevices.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001407 createVirtualKeyboardLocked();
1408 }
1409}
1410
1411// ----------------------------------------------------------------------------
1412
Michael Wrightd02c5b62014-02-10 15:10:22 -08001413static const int32_t GAMEPAD_KEYCODES[] = {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001414 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C, //
1415 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z, //
1416 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1, //
1417 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2, //
1418 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR, //
1419 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE, //
Michael Wrightd02c5b62014-02-10 15:10:22 -08001420};
1421
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001422status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001423 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001424 struct epoll_event eventItem = {};
1425 eventItem.events = EPOLLIN | EPOLLWAKEUP;
1426 eventItem.data.fd = fd;
1427 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1428 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001429 return -errno;
1430 }
1431 return OK;
1432}
1433
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001434status_t EventHub::unregisterFdFromEpoll(int fd) {
1435 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
1436 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
1437 return -errno;
1438 }
1439 return OK;
1440}
1441
Chris Ye989bb932020-07-04 16:18:59 -07001442status_t EventHub::registerDeviceForEpollLocked(Device& device) {
1443 status_t result = registerFdForEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001444 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07001445 ALOGE("Could not add input device fd to epoll for device %" PRId32, device.id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001446 return result;
1447 }
Chris Ye989bb932020-07-04 16:18:59 -07001448 if (device.videoDevice) {
1449 registerVideoDeviceForEpollLocked(*device.videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001450 }
1451 return result;
1452}
1453
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001454void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
1455 status_t result = registerFdForEpoll(videoDevice.getFd());
1456 if (result != OK) {
1457 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
1458 }
1459}
1460
Chris Ye989bb932020-07-04 16:18:59 -07001461status_t EventHub::unregisterDeviceFromEpollLocked(Device& device) {
1462 if (device.hasValidFd()) {
1463 status_t result = unregisterFdFromEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001464 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07001465 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device.id);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001466 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001467 }
1468 }
Chris Ye989bb932020-07-04 16:18:59 -07001469 if (device.videoDevice) {
1470 unregisterVideoDeviceFromEpollLocked(*device.videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001471 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001472 return OK;
1473}
1474
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001475void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
1476 if (videoDevice.hasValidFd()) {
1477 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
1478 if (result != OK) {
1479 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001480 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001481 }
1482 }
1483}
1484
Chris Ye8594e192020-07-14 10:34:06 -07001485status_t EventHub::openDeviceLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001486 char buffer[80];
1487
Chris Ye8594e192020-07-14 10:34:06 -07001488 ALOGV("Opening device: %s", devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001489
Chris Ye8594e192020-07-14 10:34:06 -07001490 int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001491 if (fd < 0) {
Chris Ye8594e192020-07-14 10:34:06 -07001492 ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001493 return -1;
1494 }
1495
1496 InputDeviceIdentifier identifier;
1497
1498 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001499 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Chris Ye8594e192020-07-14 10:34:06 -07001500 ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001501 } else {
1502 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001503 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001504 }
1505
1506 // Check to see if the device is on our excluded list
1507 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001508 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001509 if (identifier.name == item) {
Chris Ye8594e192020-07-14 10:34:06 -07001510 ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001511 close(fd);
1512 return -1;
1513 }
1514 }
1515
1516 // Get device driver version.
1517 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001518 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Chris Ye8594e192020-07-14 10:34:06 -07001519 ALOGE("could not get driver version for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001520 close(fd);
1521 return -1;
1522 }
1523
1524 // Get device identifier.
1525 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001526 if (ioctl(fd, EVIOCGID, &inputId)) {
Chris Ye8594e192020-07-14 10:34:06 -07001527 ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001528 close(fd);
1529 return -1;
1530 }
1531 identifier.bus = inputId.bustype;
1532 identifier.product = inputId.product;
1533 identifier.vendor = inputId.vendor;
1534 identifier.version = inputId.version;
1535
1536 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001537 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
1538 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001539 } else {
1540 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001541 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001542 }
1543
1544 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001545 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
1546 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001547 } else {
1548 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001549 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001550 }
1551
1552 // Fill in the descriptor.
1553 assignDescriptorLocked(identifier);
1554
Michael Wrightd02c5b62014-02-10 15:10:22 -08001555 // Allocate device. (The device object takes ownership of the fd at this point.)
1556 int32_t deviceId = mNextDeviceId++;
Chris Ye989bb932020-07-04 16:18:59 -07001557 std::unique_ptr<Device> device = std::make_unique<Device>(fd, deviceId, devicePath, identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001558
Chris Ye8594e192020-07-14 10:34:06 -07001559 ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001560 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001561 " vendor %04x\n"
1562 " product %04x\n"
1563 " version %04x\n",
1564 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001565 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
1566 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
1567 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
1568 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001569 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
1570 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001571
1572 // Load the configuration file for the device.
Chris Ye989bb932020-07-04 16:18:59 -07001573 device->loadConfigurationLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001574
1575 // Figure out the kinds of events the device reports.
Chris Ye66fbac32020-07-06 20:36:43 -07001576 device->readDeviceBitMask(EVIOCGBIT(EV_KEY, 0), device->keyBitmask);
1577 device->readDeviceBitMask(EVIOCGBIT(EV_ABS, 0), device->absBitmask);
1578 device->readDeviceBitMask(EVIOCGBIT(EV_REL, 0), device->relBitmask);
1579 device->readDeviceBitMask(EVIOCGBIT(EV_SW, 0), device->swBitmask);
1580 device->readDeviceBitMask(EVIOCGBIT(EV_LED, 0), device->ledBitmask);
1581 device->readDeviceBitMask(EVIOCGBIT(EV_FF, 0), device->ffBitmask);
Chris Yef59a2f42020-10-16 12:55:26 -07001582 device->readDeviceBitMask(EVIOCGBIT(EV_MSC, 0), device->mscBitmask);
Chris Ye66fbac32020-07-06 20:36:43 -07001583 device->readDeviceBitMask(EVIOCGPROP(0), device->propBitmask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001584
1585 // See if this is a keyboard. Ignore everything in the button range except for
1586 // joystick and gamepad buttons which are handled like keyboards for the most part.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001587 bool haveKeyboardKeys =
Chris Ye66fbac32020-07-06 20:36:43 -07001588 device->keyBitmask.any(0, BTN_MISC) || device->keyBitmask.any(BTN_WHEEL, KEY_MAX + 1);
1589 bool haveGamepadButtons = device->keyBitmask.any(BTN_MISC, BTN_MOUSE) ||
1590 device->keyBitmask.any(BTN_JOYSTICK, BTN_DIGI);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001591 if (haveKeyboardKeys || haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001592 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001593 }
1594
1595 // See if this is a cursor device such as a trackball or mouse.
Chris Ye66fbac32020-07-06 20:36:43 -07001596 if (device->keyBitmask.test(BTN_MOUSE) && device->relBitmask.test(REL_X) &&
1597 device->relBitmask.test(REL_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001598 device->classes |= InputDeviceClass::CURSOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001599 }
1600
Prashant Malani1941ff52015-08-11 18:29:28 -07001601 // See if this is a rotary encoder type device.
1602 String8 deviceType = String8();
1603 if (device->configuration &&
1604 device->configuration->tryGetProperty(String8("device.type"), deviceType)) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001605 if (!deviceType.compare(String8("rotaryEncoder"))) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001606 device->classes |= InputDeviceClass::ROTARY_ENCODER;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001607 }
Prashant Malani1941ff52015-08-11 18:29:28 -07001608 }
1609
Michael Wrightd02c5b62014-02-10 15:10:22 -08001610 // See if this is a touch pad.
1611 // Is this a new modern multi-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07001612 if (device->absBitmask.test(ABS_MT_POSITION_X) && device->absBitmask.test(ABS_MT_POSITION_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001613 // Some joysticks such as the PS3 controller report axes that conflict
1614 // with the ABS_MT range. Try to confirm that the device really is
1615 // a touch screen.
Chris Ye66fbac32020-07-06 20:36:43 -07001616 if (device->keyBitmask.test(BTN_TOUCH) || !haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001617 device->classes |= (InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001618 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001619 // Is this an old style single-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07001620 } else if (device->keyBitmask.test(BTN_TOUCH) && device->absBitmask.test(ABS_X) &&
1621 device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001622 device->classes |= InputDeviceClass::TOUCH;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001623 // Is this a BT stylus?
Chris Ye66fbac32020-07-06 20:36:43 -07001624 } else if ((device->absBitmask.test(ABS_PRESSURE) || device->keyBitmask.test(BTN_TOUCH)) &&
1625 !device->absBitmask.test(ABS_X) && !device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001626 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -07001627 // Keyboard will try to claim some of the buttons but we really want to reserve those so we
1628 // can fuse it with the touch screen data, so just take them back. Note this means an
1629 // external stylus cannot also be a keyboard device.
Chris Ye1b0c7342020-07-28 21:57:03 -07001630 device->classes &= ~InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001631 }
1632
1633 // See if this device is a joystick.
1634 // Assumes that joysticks always have gamepad buttons in order to distinguish them
1635 // from other devices such as accelerometers that also have absolute axes.
1636 if (haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001637 auto assumedClasses = device->classes | InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001638 for (int i = 0; i <= ABS_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07001639 if (device->absBitmask.test(i) &&
Chris Ye1b0c7342020-07-28 21:57:03 -07001640 (getAbsAxisUsage(i, assumedClasses).test(InputDeviceClass::JOYSTICK))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001641 device->classes = assumedClasses;
1642 break;
1643 }
1644 }
1645 }
1646
Chris Yef59a2f42020-10-16 12:55:26 -07001647 // Check whether this device is an accelerometer.
1648 if (device->propBitmask.test(INPUT_PROP_ACCELEROMETER)) {
1649 device->classes |= InputDeviceClass::SENSOR;
1650 }
1651
Michael Wrightd02c5b62014-02-10 15:10:22 -08001652 // Check whether this device has switches.
1653 for (int i = 0; i <= SW_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07001654 if (device->swBitmask.test(i)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001655 device->classes |= InputDeviceClass::SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001656 break;
1657 }
1658 }
1659
1660 // Check whether this device supports the vibrator.
Chris Ye66fbac32020-07-06 20:36:43 -07001661 if (device->ffBitmask.test(FF_RUMBLE)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001662 device->classes |= InputDeviceClass::VIBRATOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001663 }
1664
1665 // Configure virtual keys.
Chris Ye1b0c7342020-07-28 21:57:03 -07001666 if ((device->classes.test(InputDeviceClass::TOUCH))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001667 // Load the virtual keys for the touch screen, if any.
1668 // We do this now so that we can make sure to load the keymap if necessary.
Chris Ye989bb932020-07-04 16:18:59 -07001669 bool success = device->loadVirtualKeyMapLocked();
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001670 if (success) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001671 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001672 }
1673 }
1674
1675 // Load the key map.
Chris Yef59a2f42020-10-16 12:55:26 -07001676 // We need to do this for joysticks too because the key layout may specify axes, and for
1677 // sensor as well because the key layout may specify the axes to sensor data mapping.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001678 status_t keyMapStatus = NAME_NOT_FOUND;
Chris Yef59a2f42020-10-16 12:55:26 -07001679 if (device->classes.any(InputDeviceClass::KEYBOARD | InputDeviceClass::JOYSTICK |
1680 InputDeviceClass::SENSOR)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001681 // Load the keymap for the device.
Chris Ye989bb932020-07-04 16:18:59 -07001682 keyMapStatus = device->loadKeyMapLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001683 }
1684
1685 // Configure the keyboard, gamepad or virtual keyboard.
Chris Ye1b0c7342020-07-28 21:57:03 -07001686 if (device->classes.test(InputDeviceClass::KEYBOARD)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001687 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001688 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05001689 isEligibleBuiltInKeyboard(device->identifier, device->configuration.get(),
1690 &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001691 mBuiltInKeyboardId = device->id;
1692 }
1693
1694 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
Chris Ye989bb932020-07-04 16:18:59 -07001695 if (device->hasKeycodeLocked(AKEYCODE_Q)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001696 device->classes |= InputDeviceClass::ALPHAKEY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001697 }
1698
1699 // See if this device has a DPAD.
Chris Ye989bb932020-07-04 16:18:59 -07001700 if (device->hasKeycodeLocked(AKEYCODE_DPAD_UP) &&
1701 device->hasKeycodeLocked(AKEYCODE_DPAD_DOWN) &&
1702 device->hasKeycodeLocked(AKEYCODE_DPAD_LEFT) &&
1703 device->hasKeycodeLocked(AKEYCODE_DPAD_RIGHT) &&
1704 device->hasKeycodeLocked(AKEYCODE_DPAD_CENTER)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001705 device->classes |= InputDeviceClass::DPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001706 }
1707
1708 // See if this device has a gamepad.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001709 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES) / sizeof(GAMEPAD_KEYCODES[0]); i++) {
Chris Ye989bb932020-07-04 16:18:59 -07001710 if (device->hasKeycodeLocked(GAMEPAD_KEYCODES[i])) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001711 device->classes |= InputDeviceClass::GAMEPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001712 break;
1713 }
1714 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001715 }
1716
1717 // If the device isn't recognized as something we handle, don't monitor it.
Chris Ye1b0c7342020-07-28 21:57:03 -07001718 if (device->classes == Flags<InputDeviceClass>(0)) {
Chris Ye8594e192020-07-14 10:34:06 -07001719 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001720 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001721 return -1;
1722 }
1723
Kim Low03ea0352020-11-06 12:45:07 -08001724 // Grab the device's sysfs path
1725 device->sysfsRootPath = getSysfsRootPath(devicePath.c_str());
1726
1727 if (!device->sysfsRootPath.empty()) {
1728 device->sysfsBatteryPath = findPowerSupplyNode(device->sysfsRootPath);
1729
1730 // Check if a battery exists
1731 if (!device->sysfsBatteryPath.empty()) {
1732 device->classes |= InputDeviceClass::BATTERY;
1733 }
1734 }
1735
Tim Kilbourn063ff532015-04-08 10:26:18 -07001736 // Determine whether the device has a mic.
Chris Ye989bb932020-07-04 16:18:59 -07001737 if (device->deviceHasMicLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001738 device->classes |= InputDeviceClass::MIC;
Tim Kilbourn063ff532015-04-08 10:26:18 -07001739 }
1740
Michael Wrightd02c5b62014-02-10 15:10:22 -08001741 // Determine whether the device is external or internal.
Chris Ye989bb932020-07-04 16:18:59 -07001742 if (device->isExternalDeviceLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001743 device->classes |= InputDeviceClass::EXTERNAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001744 }
1745
Chris Ye1b0c7342020-07-28 21:57:03 -07001746 if (device->classes.any(InputDeviceClass::JOYSTICK | InputDeviceClass::DPAD) &&
1747 device->classes.test(InputDeviceClass::GAMEPAD)) {
Chris Ye989bb932020-07-04 16:18:59 -07001748 device->controllerNumber = getNextControllerNumberLocked(device->identifier.name);
1749 device->setLedForControllerLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001750 }
1751
Chris Ye989bb932020-07-04 16:18:59 -07001752 if (registerDeviceForEpollLocked(*device) != OK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001753 return -1;
1754 }
1755
Chris Ye989bb932020-07-04 16:18:59 -07001756 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001757
Chris Ye1b0c7342020-07-28 21:57:03 -07001758 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=%s, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001759 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Chris Ye1b0c7342020-07-28 21:57:03 -07001760 deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(),
1761 device->classes.string().c_str(), device->configurationFile.c_str(),
1762 device->keyMap.keyLayoutFile.c_str(), device->keyMap.keyCharacterMapFile.c_str(),
1763 toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001764
Chris Ye989bb932020-07-04 16:18:59 -07001765 addDeviceLocked(std::move(device));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001766 return OK;
1767}
1768
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001769void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
1770 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
1771 if (!videoDevice) {
1772 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
1773 return;
1774 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001775 // Transfer ownership of this video device to a matching input device
Chris Ye989bb932020-07-04 16:18:59 -07001776 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001777 if (tryAddVideoDevice(*device, videoDevice)) {
1778 return; // 'device' now owns 'videoDevice'
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001779 }
1780 }
1781
1782 // Couldn't find a matching input device, so just add it to a temporary holding queue.
1783 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001784 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001785 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001786 mUnattachedVideoDevices.push_back(std::move(videoDevice));
1787}
1788
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001789bool EventHub::tryAddVideoDevice(EventHub::Device& device,
1790 std::unique_ptr<TouchVideoDevice>& videoDevice) {
1791 if (videoDevice->getName() != device.identifier.name) {
1792 return false;
1793 }
1794 device.videoDevice = std::move(videoDevice);
1795 if (device.enabled) {
1796 registerVideoDeviceForEpollLocked(*device.videoDevice);
1797 }
1798 return true;
1799}
1800
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001801bool EventHub::isDeviceEnabled(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001802 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001803 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001804 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001805 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1806 return false;
1807 }
1808 return device->enabled;
1809}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001810
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001811status_t EventHub::enableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001812 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001813 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001814 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001815 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1816 return BAD_VALUE;
1817 }
1818 if (device->enabled) {
1819 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
1820 return OK;
1821 }
1822 status_t result = device->enable();
1823 if (result != OK) {
1824 ALOGE("Failed to enable device %" PRId32, deviceId);
1825 return result;
1826 }
1827
Chris Ye989bb932020-07-04 16:18:59 -07001828 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001829
Chris Ye989bb932020-07-04 16:18:59 -07001830 return registerDeviceForEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001831}
1832
1833status_t EventHub::disableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001834 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001835 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001836 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001837 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1838 return BAD_VALUE;
1839 }
1840 if (!device->enabled) {
1841 ALOGW("Duplicate call to %s, input device already disabled", __func__);
1842 return OK;
1843 }
Chris Ye989bb932020-07-04 16:18:59 -07001844 unregisterDeviceFromEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001845 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001846}
1847
1848void EventHub::createVirtualKeyboardLocked() {
1849 InputDeviceIdentifier identifier;
1850 identifier.name = "Virtual";
1851 identifier.uniqueId = "<virtual>";
1852 assignDescriptorLocked(identifier);
1853
Chris Ye989bb932020-07-04 16:18:59 -07001854 std::unique_ptr<Device> device =
1855 std::make_unique<Device>(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
1856 identifier);
Chris Ye1b0c7342020-07-28 21:57:03 -07001857 device->classes = InputDeviceClass::KEYBOARD | InputDeviceClass::ALPHAKEY |
1858 InputDeviceClass::DPAD | InputDeviceClass::VIRTUAL;
Chris Ye989bb932020-07-04 16:18:59 -07001859 device->loadKeyMapLocked();
1860 addDeviceLocked(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001861}
1862
Chris Ye989bb932020-07-04 16:18:59 -07001863void EventHub::addDeviceLocked(std::unique_ptr<Device> device) {
1864 mOpeningDevices.push_back(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001865}
1866
Chris Ye989bb932020-07-04 16:18:59 -07001867int32_t EventHub::getNextControllerNumberLocked(const std::string& name) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001868 if (mControllerNumbers.isFull()) {
1869 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Chris Ye989bb932020-07-04 16:18:59 -07001870 name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001871 return 0;
1872 }
1873 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
1874 // one
1875 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
1876}
1877
Chris Ye989bb932020-07-04 16:18:59 -07001878void EventHub::releaseControllerNumberLocked(int32_t num) {
1879 if (num > 0) {
1880 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001881 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001882}
1883
Chris Ye8594e192020-07-14 10:34:06 -07001884void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001885 Device* device = getDeviceByPathLocked(devicePath);
Chris Ye989bb932020-07-04 16:18:59 -07001886 if (device != nullptr) {
1887 closeDeviceLocked(*device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001888 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001889 }
Chris Ye8594e192020-07-14 10:34:06 -07001890 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001891}
1892
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001893/**
1894 * Find the video device by filename, and close it.
1895 * The video device is closed by path during an inotify event, where we don't have the
1896 * additional context about the video device fd, or the associated input device.
1897 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001898void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001899 // A video device may be owned by an existing input device, or it may be stored in
1900 // the mUnattachedVideoDevices queue. Check both locations.
Chris Ye989bb932020-07-04 16:18:59 -07001901 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001902 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001903 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001904 device->videoDevice = nullptr;
1905 return;
1906 }
1907 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001908 mUnattachedVideoDevices
1909 .erase(std::remove_if(mUnattachedVideoDevices.begin(), mUnattachedVideoDevices.end(),
1910 [&devicePath](
1911 const std::unique_ptr<TouchVideoDevice>& videoDevice) {
1912 return videoDevice->getPath() == devicePath;
1913 }),
1914 mUnattachedVideoDevices.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001915}
1916
1917void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001918 mUnattachedVideoDevices.clear();
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05001919 while (!mDevices.empty()) {
1920 closeDeviceLocked(*(mDevices.begin()->second));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001921 }
1922}
1923
Chris Ye989bb932020-07-04 16:18:59 -07001924void EventHub::closeDeviceLocked(Device& device) {
1925 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=%s", device.path.c_str(),
1926 device.identifier.name.c_str(), device.id, device.fd, device.classes.string().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001927
Chris Ye989bb932020-07-04 16:18:59 -07001928 if (device.id == mBuiltInKeyboardId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001929 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Chris Ye989bb932020-07-04 16:18:59 -07001930 device.path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001931 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
1932 }
1933
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001934 unregisterDeviceFromEpollLocked(device);
Chris Ye989bb932020-07-04 16:18:59 -07001935 if (device.videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001936 // This must be done after the video device is removed from epoll
Chris Ye989bb932020-07-04 16:18:59 -07001937 mUnattachedVideoDevices.push_back(std::move(device.videoDevice));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001938 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001939
Chris Ye989bb932020-07-04 16:18:59 -07001940 releaseControllerNumberLocked(device.controllerNumber);
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05001941 device.controllerNumber = 0;
Chris Ye989bb932020-07-04 16:18:59 -07001942 device.close();
Chris Ye989bb932020-07-04 16:18:59 -07001943 mClosingDevices.push_back(std::move(mDevices[device.id]));
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05001944
Chris Ye989bb932020-07-04 16:18:59 -07001945 mDevices.erase(device.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001946}
1947
1948status_t EventHub::readNotifyLocked() {
1949 int res;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001950 char event_buf[512];
1951 int event_size;
1952 int event_pos = 0;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001953 struct inotify_event* event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001954
1955 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
1956 res = read(mINotifyFd, event_buf, sizeof(event_buf));
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001957 if (res < (int)sizeof(*event)) {
1958 if (errno == EINTR) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001959 ALOGW("could not get event, %s\n", strerror(errno));
1960 return -1;
1961 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001962
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001963 while (res >= (int)sizeof(*event)) {
1964 event = (struct inotify_event*)(event_buf + event_pos);
1965 if (event->len) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001966 if (event->wd == mInputWd) {
Chris Ye8594e192020-07-14 10:34:06 -07001967 std::string filename = std::string(DEVICE_PATH) + "/" + event->name;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001968 if (event->mask & IN_CREATE) {
Chris Ye8594e192020-07-14 10:34:06 -07001969 openDeviceLocked(filename);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001970 } else {
1971 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
Chris Ye8594e192020-07-14 10:34:06 -07001972 closeDeviceByPathLocked(filename);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001973 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001974 } else if (event->wd == mVideoWd) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001975 if (isV4lTouchNode(event->name)) {
Chris Ye8594e192020-07-14 10:34:06 -07001976 std::string filename = std::string(VIDEO_DEVICE_PATH) + "/" + event->name;
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001977 if (event->mask & IN_CREATE) {
1978 openVideoDeviceLocked(filename);
1979 } else {
1980 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
1981 closeVideoDeviceByPathLocked(filename);
1982 }
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001983 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001984 } else {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001985 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event->wd);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001986 }
1987 }
1988 event_size = sizeof(*event) + event->len;
1989 res -= event_size;
1990 event_pos += event_size;
1991 }
1992 return 0;
1993}
1994
Chris Ye8594e192020-07-14 10:34:06 -07001995status_t EventHub::scanDirLocked(const std::string& dirname) {
1996 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
1997 openDeviceLocked(entry.path());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001998 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001999 return 0;
2000}
2001
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002002/**
2003 * Look for all dirname/v4l-touch* devices, and open them.
2004 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002005status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Chris Ye8594e192020-07-14 10:34:06 -07002006 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2007 if (isV4lTouchNode(entry.path())) {
2008 ALOGI("Found touch video device %s", entry.path().c_str());
2009 openVideoDeviceLocked(entry.path());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002010 }
2011 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002012 return OK;
2013}
2014
Michael Wrightd02c5b62014-02-10 15:10:22 -08002015void EventHub::requestReopenDevices() {
2016 ALOGV("requestReopenDevices() called");
2017
Chris Ye87143712020-11-10 05:05:58 +00002018 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002019 mNeedToReopenDevices = true;
2020}
2021
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002022void EventHub::dump(std::string& dump) {
2023 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002024
2025 { // acquire lock
Chris Ye87143712020-11-10 05:05:58 +00002026 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002027
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002028 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002029
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002030 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002031
Chris Ye989bb932020-07-04 16:18:59 -07002032 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002033 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002034 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002035 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002036 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002037 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002038 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002039 }
Chris Ye1b0c7342020-07-28 21:57:03 -07002040 dump += StringPrintf(INDENT3 "Classes: %s\n", device->classes.string().c_str());
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002041 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002042 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002043 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
2044 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002045 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002046 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002047 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002048 "product=0x%04x, version=0x%04x\n",
2049 device->identifier.bus, device->identifier.vendor,
2050 device->identifier.product, device->identifier.version);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002051 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002052 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002053 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002054 device->keyMap.keyCharacterMapFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002055 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002056 device->configurationFile.c_str());
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002057 dump += INDENT3 "VideoDevice: ";
2058 if (device->videoDevice) {
2059 dump += device->videoDevice->dump() + "\n";
2060 } else {
2061 dump += "<none>\n";
2062 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002063 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002064
2065 dump += INDENT "Unattached video devices:\n";
2066 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
2067 dump += INDENT2 + videoDevice->dump() + "\n";
2068 }
2069 if (mUnattachedVideoDevices.empty()) {
2070 dump += INDENT2 "<none>\n";
2071 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002072 } // release lock
2073}
2074
2075void EventHub::monitor() {
2076 // Acquire and release the lock to ensure that the event hub has not deadlocked.
Chris Ye1c2e0892020-11-30 21:41:44 -08002077 std::unique_lock<std::mutex> lock(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002078}
2079
Michael Wrightd02c5b62014-02-10 15:10:22 -08002080}; // namespace android