blob: a92cb94db70d91e8add1dd9d0b4275615cca49eb [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>
Chris Yed3fef462021-03-07 17:10:08 -080041#include <android-base/strings.h>
Philip Quinn39b81682019-01-09 22:20:39 -080042#include <cutils/properties.h>
Chris Ye8594e192020-07-14 10:34:06 -070043#include <input/KeyCharacterMap.h>
44#include <input/KeyLayoutMap.h>
45#include <input/VirtualKeyMap.h>
Dan Albert677d87e2014-06-16 17:31:28 -070046#include <openssl/sha.h>
Chris Yed3fef462021-03-07 17:10:08 -080047#include <statslog.h>
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070048#include <utils/Errors.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080049#include <utils/Log.h>
50#include <utils/Timers.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080051
Chris Ye8594e192020-07-14 10:34:06 -070052#include <filesystem>
Chris Ye3fdbfef2021-01-06 18:45:18 -080053#include <regex>
Chris Ye8594e192020-07-14 10:34:06 -070054
55#include "EventHub.h"
Michael Wrightd02c5b62014-02-10 15:10:22 -080056
Michael Wrightd02c5b62014-02-10 15:10:22 -080057#define INDENT " "
58#define INDENT2 " "
59#define INDENT3 " "
60
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080061using android::base::StringPrintf;
Chris Ye1b0c7342020-07-28 21:57:03 -070062using namespace android::flag_operators;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080063
Michael Wrightd02c5b62014-02-10 15:10:22 -080064namespace android {
65
Usama Arif78eb9752021-06-03 16:44:09 +010066static const char* DEVICE_INPUT_PATH = "/dev/input";
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080067// v4l2 devices go directly into /dev
Usama Arif78eb9752021-06-03 16:44:09 +010068static const char* DEVICE_PATH = "/dev";
Michael Wrightd02c5b62014-02-10 15:10:22 -080069
Chris Ye657c2f02021-05-25 16:24:37 -070070static constexpr size_t OBFUSCATED_LENGTH = 8;
71
Chris Ye87143712020-11-10 05:05:58 +000072static constexpr int32_t FF_STRONG_MAGNITUDE_CHANNEL_IDX = 0;
73static constexpr int32_t FF_WEAK_MAGNITUDE_CHANNEL_IDX = 1;
Chris Ye6393a262020-08-04 19:41:36 -070074
Chris Yee2b1e5c2021-03-10 22:45:12 -080075// Mapping for input battery class node IDs lookup.
76// https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
77static const std::unordered_map<std::string, InputBatteryClass> BATTERY_CLASSES =
78 {{"capacity", InputBatteryClass::CAPACITY},
79 {"capacity_level", InputBatteryClass::CAPACITY_LEVEL},
80 {"status", InputBatteryClass::STATUS}};
81
82// Mapping for input battery class node names lookup.
83// https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
84static const std::unordered_map<InputBatteryClass, std::string> BATTERY_NODES =
85 {{InputBatteryClass::CAPACITY, "capacity"},
86 {InputBatteryClass::CAPACITY_LEVEL, "capacity_level"},
87 {InputBatteryClass::STATUS, "status"}};
88
Kim Low03ea0352020-11-06 12:45:07 -080089// must be kept in sync with definitions in kernel /drivers/power/supply/power_supply_sysfs.c
90static const std::unordered_map<std::string, int32_t> BATTERY_STATUS =
91 {{"Unknown", BATTERY_STATUS_UNKNOWN},
92 {"Charging", BATTERY_STATUS_CHARGING},
93 {"Discharging", BATTERY_STATUS_DISCHARGING},
94 {"Not charging", BATTERY_STATUS_NOT_CHARGING},
95 {"Full", BATTERY_STATUS_FULL}};
96
97// Mapping taken from
98// https://gitlab.freedesktop.org/upower/upower/-/blob/master/src/linux/up-device-supply.c#L484
99static const std::unordered_map<std::string, int32_t> BATTERY_LEVEL = {{"Critical", 5},
100 {"Low", 10},
101 {"Normal", 55},
102 {"High", 70},
103 {"Full", 100},
104 {"Unknown", 50}};
105
Chris Ye3fdbfef2021-01-06 18:45:18 -0800106// Mapping for input led class node names lookup.
107// https://www.kernel.org/doc/html/latest/leds/leds-class.html
108static const std::unordered_map<std::string, InputLightClass> LIGHT_CLASSES =
109 {{"red", InputLightClass::RED},
110 {"green", InputLightClass::GREEN},
111 {"blue", InputLightClass::BLUE},
112 {"global", InputLightClass::GLOBAL},
113 {"brightness", InputLightClass::BRIGHTNESS},
114 {"multi_index", InputLightClass::MULTI_INDEX},
115 {"multi_intensity", InputLightClass::MULTI_INTENSITY},
116 {"max_brightness", InputLightClass::MAX_BRIGHTNESS}};
117
118// Mapping for input multicolor led class node names.
119// https://www.kernel.org/doc/html/latest/leds/leds-class-multicolor.html
120static const std::unordered_map<InputLightClass, std::string> LIGHT_NODES =
121 {{InputLightClass::BRIGHTNESS, "brightness"},
122 {InputLightClass::MULTI_INDEX, "multi_index"},
123 {InputLightClass::MULTI_INTENSITY, "multi_intensity"}};
124
125// Mapping for light color name and the light color
126const std::unordered_map<std::string, LightColor> LIGHT_COLORS = {{"red", LightColor::RED},
127 {"green", LightColor::GREEN},
128 {"blue", LightColor::BLUE}};
129
Michael Wrightd02c5b62014-02-10 15:10:22 -0800130static inline const char* toString(bool value) {
131 return value ? "true" : "false";
132}
133
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100134static std::string sha1(const std::string& in) {
Dan Albert677d87e2014-06-16 17:31:28 -0700135 SHA_CTX ctx;
136 SHA1_Init(&ctx);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100137 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
Dan Albert677d87e2014-06-16 17:31:28 -0700138 u_char digest[SHA_DIGEST_LENGTH];
139 SHA1_Final(digest, &ctx);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800140
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100141 std::string out;
Dan Albert677d87e2014-06-16 17:31:28 -0700142 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100143 out += StringPrintf("%02x", digest[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800144 }
145 return out;
146}
147
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800148/**
149 * Return true if name matches "v4l-touch*"
150 */
Chris Ye8594e192020-07-14 10:34:06 -0700151static bool isV4lTouchNode(std::string name) {
152 return name.find("v4l-touch") != std::string::npos;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800153}
154
Philip Quinn39b81682019-01-09 22:20:39 -0800155/**
156 * Returns true if V4L devices should be scanned.
157 *
158 * The system property ro.input.video_enabled can be used to control whether
159 * EventHub scans and opens V4L devices. As V4L does not support multiple
160 * clients, EventHub effectively blocks access to these devices when it opens
Siarhei Vishniakou29f88492019-04-05 14:11:43 -0700161 * them.
162 *
163 * Setting this to "false" would prevent any video devices from being discovered and
164 * associated with input devices.
165 *
166 * This property can be used as follows:
167 * 1. To turn off features that are dependent on video device presence.
168 * 2. During testing and development, to allow other clients to read video devices
169 * directly from /dev.
Philip Quinn39b81682019-01-09 22:20:39 -0800170 */
171static bool isV4lScanningEnabled() {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700172 return property_get_bool("ro.input.video_enabled", true /* default_value */);
Philip Quinn39b81682019-01-09 22:20:39 -0800173}
174
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800175static nsecs_t processEventTimestamp(const struct input_event& event) {
176 // Use the time specified in the event instead of the current time
177 // so that downstream code can get more accurate estimates of
178 // event dispatch latency from the time the event is enqueued onto
179 // the evdev client buffer.
180 //
181 // The event's timestamp fortuitously uses the same monotonic clock
182 // time base as the rest of Android. The kernel event device driver
183 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
184 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
185 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
186 // system call that also queries ktime_get_ts().
187
188 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.time.tv_sec) +
189 microseconds_to_nanoseconds(event.time.tv_usec);
190 return inputEventTime;
191}
192
Kim Low03ea0352020-11-06 12:45:07 -0800193/**
194 * Returns the sysfs root path of the input device
195 *
196 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800197static std::optional<std::filesystem::path> getSysfsRootPath(const char* devicePath) {
Kim Low03ea0352020-11-06 12:45:07 -0800198 std::error_code errorCode;
199
200 // Stat the device path to get the major and minor number of the character file
201 struct stat statbuf;
202 if (stat(devicePath, &statbuf) == -1) {
203 ALOGE("Could not stat device %s due to error: %s.", devicePath, std::strerror(errno));
Chris Ye3fdbfef2021-01-06 18:45:18 -0800204 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800205 }
206
207 unsigned int major_num = major(statbuf.st_rdev);
208 unsigned int minor_num = minor(statbuf.st_rdev);
209
210 // Realpath "/sys/dev/char/{major}:{minor}" to get the sysfs path to the input event
211 auto sysfsPath = std::filesystem::path("/sys/dev/char/");
212 sysfsPath /= std::to_string(major_num) + ":" + std::to_string(minor_num);
213 sysfsPath = std::filesystem::canonical(sysfsPath, errorCode);
214
215 // Make sure nothing went wrong in call to canonical()
216 if (errorCode) {
217 ALOGW("Could not run filesystem::canonical() due to error %d : %s.", errorCode.value(),
218 errorCode.message().c_str());
Chris Ye3fdbfef2021-01-06 18:45:18 -0800219 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800220 }
221
222 // Continue to go up a directory until we reach a directory named "input"
223 while (sysfsPath != "/" && sysfsPath.filename() != "input") {
224 sysfsPath = sysfsPath.parent_path();
225 }
226
227 // Then go up one more and you will be at the sysfs root of the device
228 sysfsPath = sysfsPath.parent_path();
229
230 // Make sure we didn't reach root path and that directory actually exists
231 if (sysfsPath == "/" || !std::filesystem::exists(sysfsPath, errorCode)) {
232 if (errorCode) {
233 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
234 errorCode.message().c_str());
235 }
236
237 // Not found
Chris Ye3fdbfef2021-01-06 18:45:18 -0800238 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800239 }
240
241 return sysfsPath;
242}
243
244/**
Chris Ye3fdbfef2021-01-06 18:45:18 -0800245 * Returns the list of files under a specified path.
Kim Low03ea0352020-11-06 12:45:07 -0800246 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800247static std::vector<std::filesystem::path> allFilesInPath(const std::filesystem::path& path) {
248 std::vector<std::filesystem::path> nodes;
249 std::error_code errorCode;
250 auto iter = std::filesystem::directory_iterator(path, errorCode);
251 while (!errorCode && iter != std::filesystem::directory_iterator()) {
252 nodes.push_back(iter->path());
253 iter++;
254 }
255 return nodes;
256}
257
258/**
259 * Returns the list of files under a specified directory in a sysfs path.
260 * Example:
261 * findSysfsNodes(sysfsRootPath, SysfsClass::LEDS) will return all led nodes under "leds" directory
262 * in the sysfs path.
263 */
264static std::vector<std::filesystem::path> findSysfsNodes(const std::filesystem::path& sysfsRoot,
265 SysfsClass clazz) {
266 std::string nodeStr = NamedEnum::string(clazz);
267 std::for_each(nodeStr.begin(), nodeStr.end(),
268 [](char& c) { c = std::tolower(static_cast<unsigned char>(c)); });
269 std::vector<std::filesystem::path> nodes;
270 for (auto path = sysfsRoot; path != "/" && nodes.empty(); path = path.parent_path()) {
271 nodes = allFilesInPath(path / nodeStr);
272 }
273 return nodes;
274}
275
276static std::optional<std::array<LightColor, COLOR_NUM>> getColorIndexArray(
277 std::filesystem::path path) {
278 std::string indexStr;
279 if (!base::ReadFileToString(path, &indexStr)) {
280 return std::nullopt;
281 }
282
283 // Parse the multi color LED index file, refer to kernel docs
284 // leds/leds-class-multicolor.html
285 std::regex indexPattern("(red|green|blue)\\s(red|green|blue)\\s(red|green|blue)[\\n]");
286 std::smatch results;
287 std::array<LightColor, COLOR_NUM> colors;
288 if (!std::regex_match(indexStr, results, indexPattern)) {
289 return std::nullopt;
290 }
291
292 for (size_t i = 1; i < results.size(); i++) {
293 const auto it = LIGHT_COLORS.find(results[i].str());
294 if (it != LIGHT_COLORS.end()) {
295 // intensities.emplace(it->second, 0);
296 colors[i - 1] = it->second;
Kim Low03ea0352020-11-06 12:45:07 -0800297 }
298 }
Chris Ye3fdbfef2021-01-06 18:45:18 -0800299 return colors;
Kim Low03ea0352020-11-06 12:45:07 -0800300}
301
Michael Wrightd02c5b62014-02-10 15:10:22 -0800302// --- Global Functions ---
303
Chris Ye1b0c7342020-07-28 21:57:03 -0700304Flags<InputDeviceClass> getAbsAxisUsage(int32_t axis, Flags<InputDeviceClass> deviceClasses) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800305 // Touch devices get dibs on touch-related axes.
Chris Ye1b0c7342020-07-28 21:57:03 -0700306 if (deviceClasses.test(InputDeviceClass::TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800307 switch (axis) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700308 case ABS_X:
309 case ABS_Y:
310 case ABS_PRESSURE:
311 case ABS_TOOL_WIDTH:
312 case ABS_DISTANCE:
313 case ABS_TILT_X:
314 case ABS_TILT_Y:
315 case ABS_MT_SLOT:
316 case ABS_MT_TOUCH_MAJOR:
317 case ABS_MT_TOUCH_MINOR:
318 case ABS_MT_WIDTH_MAJOR:
319 case ABS_MT_WIDTH_MINOR:
320 case ABS_MT_ORIENTATION:
321 case ABS_MT_POSITION_X:
322 case ABS_MT_POSITION_Y:
323 case ABS_MT_TOOL_TYPE:
324 case ABS_MT_BLOB_ID:
325 case ABS_MT_TRACKING_ID:
326 case ABS_MT_PRESSURE:
327 case ABS_MT_DISTANCE:
Chris Ye1b0c7342020-07-28 21:57:03 -0700328 return InputDeviceClass::TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800329 }
330 }
331
Chris Yef59a2f42020-10-16 12:55:26 -0700332 if (deviceClasses.test(InputDeviceClass::SENSOR)) {
333 switch (axis) {
334 case ABS_X:
335 case ABS_Y:
336 case ABS_Z:
337 case ABS_RX:
338 case ABS_RY:
339 case ABS_RZ:
340 return InputDeviceClass::SENSOR;
341 }
342 }
343
Michael Wright842500e2015-03-13 17:32:02 -0700344 // External stylus gets the pressure axis
Chris Ye1b0c7342020-07-28 21:57:03 -0700345 if (deviceClasses.test(InputDeviceClass::EXTERNAL_STYLUS)) {
Michael Wright842500e2015-03-13 17:32:02 -0700346 if (axis == ABS_PRESSURE) {
Chris Ye1b0c7342020-07-28 21:57:03 -0700347 return InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -0700348 }
349 }
350
Michael Wrightd02c5b62014-02-10 15:10:22 -0800351 // Joystick devices get the rest.
Chris Ye1b0c7342020-07-28 21:57:03 -0700352 return deviceClasses & InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800353}
354
355// --- EventHub::Device ---
356
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100357EventHub::Device::Device(int fd, int32_t id, const std::string& path,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700358 const InputDeviceIdentifier& identifier)
Chris Ye989bb932020-07-04 16:18:59 -0700359 : fd(fd),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700360 id(id),
361 path(path),
362 identifier(identifier),
363 classes(0),
364 configuration(nullptr),
365 virtualKeyMap(nullptr),
366 ffEffectPlaying(false),
367 ffEffectId(-1),
Chris Ye1dd2e5c2021-04-04 23:12:41 -0700368 associatedDevice(nullptr),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700369 controllerNumber(0),
370 enabled(true),
Chris Ye66fbac32020-07-06 20:36:43 -0700371 isVirtual(fd < 0) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800372
373EventHub::Device::~Device() {
374 close();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800375}
376
377void EventHub::Device::close() {
378 if (fd >= 0) {
379 ::close(fd);
380 fd = -1;
381 }
382}
383
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700384status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100385 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700386 if (fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100387 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700388 return -errno;
389 }
390 enabled = true;
391 return OK;
392}
393
394status_t EventHub::Device::disable() {
395 close();
396 enabled = false;
397 return OK;
398}
399
Chris Ye989bb932020-07-04 16:18:59 -0700400bool EventHub::Device::hasValidFd() const {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700401 return !isVirtual && enabled;
402}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800403
Chris Ye3a1e4462020-08-12 10:13:15 -0700404const std::shared_ptr<KeyCharacterMap> EventHub::Device::getKeyCharacterMap() const {
Chris Ye989bb932020-07-04 16:18:59 -0700405 return keyMap.keyCharacterMap;
406}
407
408template <std::size_t N>
409status_t EventHub::Device::readDeviceBitMask(unsigned long ioctlCode, BitArray<N>& bitArray) {
410 if (!hasValidFd()) {
411 return BAD_VALUE;
412 }
413 if ((_IOC_SIZE(ioctlCode) == 0)) {
414 ioctlCode |= _IOC(0, 0, 0, bitArray.bytes());
415 }
416
417 typename BitArray<N>::Buffer buffer;
418 status_t ret = ioctl(fd, ioctlCode, buffer.data());
419 bitArray.loadFromBuffer(buffer);
420 return ret;
421}
422
423void EventHub::Device::configureFd() {
424 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
425 if (classes.test(InputDeviceClass::KEYBOARD)) {
426 // Disable kernel key repeat since we handle it ourselves
427 unsigned int repeatRate[] = {0, 0};
428 if (ioctl(fd, EVIOCSREP, repeatRate)) {
429 ALOGW("Unable to disable kernel key repeat for %s: %s", path.c_str(), strerror(errno));
430 }
431 }
432
433 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
434 // associated with input events. This is important because the input system
435 // uses the timestamps extensively and assumes they were recorded using the monotonic
436 // clock.
437 int clockId = CLOCK_MONOTONIC;
Chris Yef59a2f42020-10-16 12:55:26 -0700438 if (classes.test(InputDeviceClass::SENSOR)) {
439 // Each new sensor event should use the same time base as
440 // SystemClock.elapsedRealtimeNanos().
441 clockId = CLOCK_BOOTTIME;
442 }
Chris Ye989bb932020-07-04 16:18:59 -0700443 bool usingClockIoctl = !ioctl(fd, EVIOCSCLOCKID, &clockId);
444 ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
445}
446
447bool EventHub::Device::hasKeycodeLocked(int keycode) const {
448 if (!keyMap.haveKeyLayout()) {
449 return false;
450 }
451
Siarhei Vishniakou984f40b2022-05-18 09:45:54 -0700452 std::vector<int32_t> scanCodes = keyMap.keyLayoutMap->findScanCodesForKey(keycode);
Chris Ye989bb932020-07-04 16:18:59 -0700453 const size_t N = scanCodes.size();
454 for (size_t i = 0; i < N && i <= KEY_MAX; i++) {
455 int32_t sc = scanCodes[i];
456 if (sc >= 0 && sc <= KEY_MAX && keyBitmask.test(sc)) {
457 return true;
458 }
459 }
460
461 return false;
462}
463
464void EventHub::Device::loadConfigurationLocked() {
465 configurationFile =
466 getInputDeviceConfigurationFilePathByDeviceIdentifier(identifier,
467 InputDeviceConfigurationFileType::
468 CONFIGURATION);
469 if (configurationFile.empty()) {
470 ALOGD("No input device configuration file found for device '%s'.", identifier.name.c_str());
471 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500472 android::base::Result<std::unique_ptr<PropertyMap>> propertyMap =
473 PropertyMap::load(configurationFile.c_str());
474 if (!propertyMap.ok()) {
Chris Ye989bb932020-07-04 16:18:59 -0700475 ALOGE("Error loading input device configuration file for device '%s'. "
476 "Using default configuration.",
477 identifier.name.c_str());
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500478 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500479 configuration = std::move(*propertyMap);
Chris Ye989bb932020-07-04 16:18:59 -0700480 }
481 }
482}
483
484bool EventHub::Device::loadVirtualKeyMapLocked() {
485 // The virtual key map is supplied by the kernel as a system board property file.
486 std::string propPath = "/sys/board_properties/virtualkeys.";
487 propPath += identifier.getCanonicalName();
488 if (access(propPath.c_str(), R_OK)) {
489 return false;
490 }
491 virtualKeyMap = VirtualKeyMap::load(propPath);
492 return virtualKeyMap != nullptr;
493}
494
495status_t EventHub::Device::loadKeyMapLocked() {
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500496 return keyMap.load(identifier, configuration.get());
Chris Ye989bb932020-07-04 16:18:59 -0700497}
498
499bool EventHub::Device::isExternalDeviceLocked() {
500 if (configuration) {
501 bool value;
502 if (configuration->tryGetProperty(String8("device.internal"), value)) {
503 return !value;
504 }
505 }
506 return identifier.bus == BUS_USB || identifier.bus == BUS_BLUETOOTH;
507}
508
509bool EventHub::Device::deviceHasMicLocked() {
510 if (configuration) {
511 bool value;
512 if (configuration->tryGetProperty(String8("audio.mic"), value)) {
513 return value;
514 }
515 }
516 return false;
517}
518
519void EventHub::Device::setLedStateLocked(int32_t led, bool on) {
520 int32_t sc;
521 if (hasValidFd() && mapLed(led, &sc) != NAME_NOT_FOUND) {
522 struct input_event ev;
523 ev.time.tv_sec = 0;
524 ev.time.tv_usec = 0;
525 ev.type = EV_LED;
526 ev.code = sc;
527 ev.value = on ? 1 : 0;
528
529 ssize_t nWrite;
530 do {
531 nWrite = write(fd, &ev, sizeof(struct input_event));
532 } while (nWrite == -1 && errno == EINTR);
533 }
534}
535
536void EventHub::Device::setLedForControllerLocked() {
537 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
538 setLedStateLocked(ALED_CONTROLLER_1 + i, controllerNumber == i + 1);
539 }
540}
541
542status_t EventHub::Device::mapLed(int32_t led, int32_t* outScanCode) const {
543 if (!keyMap.haveKeyLayout()) {
544 return NAME_NOT_FOUND;
545 }
546
Siarhei Vishniakou984f40b2022-05-18 09:45:54 -0700547 std::optional<int32_t> scanCode = keyMap.keyLayoutMap->findScanCodeForLed(led);
548 if (scanCode.has_value()) {
549 if (*scanCode >= 0 && *scanCode <= LED_MAX && ledBitmask.test(*scanCode)) {
550 *outScanCode = *scanCode;
Chris Ye989bb932020-07-04 16:18:59 -0700551 return NO_ERROR;
552 }
553 }
554 return NAME_NOT_FOUND;
555}
556
Chris Ye3fdbfef2021-01-06 18:45:18 -0800557// Check the sysfs path for any input device batteries, returns true if battery found.
Chris Ye1dd2e5c2021-04-04 23:12:41 -0700558bool EventHub::AssociatedDevice::configureBatteryLocked() {
Chris Yee2b1e5c2021-03-10 22:45:12 -0800559 nextBatteryId = 0;
560 // Check if device has any battery.
561 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::POWER_SUPPLY);
562 for (const auto& nodePath : paths) {
563 RawBatteryInfo info;
564 info.id = ++nextBatteryId;
565 info.path = nodePath;
566 info.name = nodePath.filename();
567
568 // Scan the path for all the files
569 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
570 const auto& files = allFilesInPath(nodePath);
571 for (const auto& file : files) {
572 const auto it = BATTERY_CLASSES.find(file.filename().string());
573 if (it != BATTERY_CLASSES.end()) {
574 info.flags |= it->second;
575 }
576 }
577 batteryInfos.insert_or_assign(info.id, info);
578 ALOGD("configureBatteryLocked rawBatteryId %d name %s", info.id, info.name.c_str());
Chris Ye3fdbfef2021-01-06 18:45:18 -0800579 }
Chris Yee2b1e5c2021-03-10 22:45:12 -0800580 return !batteryInfos.empty();
Chris Ye3fdbfef2021-01-06 18:45:18 -0800581}
582
583// Check the sysfs path for any input device lights, returns true if lights found.
Chris Ye1dd2e5c2021-04-04 23:12:41 -0700584bool EventHub::AssociatedDevice::configureLightsLocked() {
Chris Yee2b1e5c2021-03-10 22:45:12 -0800585 nextLightId = 0;
Chris Ye3fdbfef2021-01-06 18:45:18 -0800586 // Check if device has any lights.
Chris Yee2b1e5c2021-03-10 22:45:12 -0800587 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::LEDS);
Chris Ye3fdbfef2021-01-06 18:45:18 -0800588 for (const auto& nodePath : paths) {
589 RawLightInfo info;
590 info.id = ++nextLightId;
591 info.path = nodePath;
592 info.name = nodePath.filename();
593 info.maxBrightness = std::nullopt;
594 size_t nameStart = info.name.rfind(":");
595 if (nameStart != std::string::npos) {
596 // Trim the name to color name
597 info.name = info.name.substr(nameStart + 1);
598 // Set InputLightClass flag for colors
599 const auto it = LIGHT_CLASSES.find(info.name);
600 if (it != LIGHT_CLASSES.end()) {
601 info.flags |= it->second;
602 }
603 }
604 // Scan the path for all the files
605 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
606 const auto& files = allFilesInPath(nodePath);
607 for (const auto& file : files) {
608 const auto it = LIGHT_CLASSES.find(file.filename().string());
609 if (it != LIGHT_CLASSES.end()) {
610 info.flags |= it->second;
611 // If the node has maximum brightness, read it
612 if (it->second == InputLightClass::MAX_BRIGHTNESS) {
613 std::string str;
614 if (base::ReadFileToString(file, &str)) {
615 info.maxBrightness = std::stoi(str);
616 }
617 }
618 }
619 }
620 lightInfos.insert_or_assign(info.id, info);
Chris Yee2b1e5c2021-03-10 22:45:12 -0800621 ALOGD("configureLightsLocked rawLightId %d name %s", info.id, info.name.c_str());
Chris Ye3fdbfef2021-01-06 18:45:18 -0800622 }
623 return !lightInfos.empty();
624}
625
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100626/**
627 * Get the capabilities for the current process.
628 * Crashes the system if unable to create / check / destroy the capabilities object.
629 */
630class Capabilities final {
631public:
632 explicit Capabilities() {
633 mCaps = cap_get_proc();
634 LOG_ALWAYS_FATAL_IF(mCaps == nullptr, "Could not get capabilities of the current process");
635 }
636
637 /**
638 * Check whether the current process has a specific capability
639 * in the set of effective capabilities.
640 * Return CAP_SET if the process has the requested capability
641 * Return CAP_CLEAR otherwise.
642 */
643 cap_flag_value_t checkEffectiveCapability(cap_value_t capability) {
644 cap_flag_value_t value;
645 const int result = cap_get_flag(mCaps, capability, CAP_EFFECTIVE, &value);
646 LOG_ALWAYS_FATAL_IF(result == -1, "Could not obtain the requested capability");
647 return value;
648 }
649
650 ~Capabilities() {
651 const int result = cap_free(mCaps);
652 LOG_ALWAYS_FATAL_IF(result == -1, "Could not release the capabilities structure");
653 }
654
655private:
656 cap_t mCaps;
657};
658
659static void ensureProcessCanBlockSuspend() {
660 Capabilities capabilities;
661 const bool canBlockSuspend =
662 capabilities.checkEffectiveCapability(CAP_BLOCK_SUSPEND) == CAP_SET;
663 LOG_ALWAYS_FATAL_IF(!canBlockSuspend,
664 "Input must be able to block suspend to properly process events");
665}
666
Michael Wrightd02c5b62014-02-10 15:10:22 -0800667// --- EventHub ---
668
Michael Wrightd02c5b62014-02-10 15:10:22 -0800669const int EventHub::EPOLL_MAX_EVENTS;
670
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700671EventHub::EventHub(void)
672 : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
673 mNextDeviceId(1),
674 mControllerNumbers(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800675 mNeedToSendFinishedDeviceScan(false),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700676 mNeedToReopenDevices(false),
677 mNeedToScanDevices(true),
678 mPendingEventCount(0),
679 mPendingEventIndex(0),
680 mPendingINotify(false) {
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100681 ensureProcessCanBlockSuspend();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800682
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800683 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800684 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800685
686 mINotifyFd = inotify_init();
Usama Arif78eb9752021-06-03 16:44:09 +0100687
688 std::error_code errorCode;
689 bool isDeviceInotifyAdded = false;
690 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
691 addDeviceInputInotify();
Philip Quinn39b81682019-01-09 22:20:39 -0800692 } else {
Usama Arif78eb9752021-06-03 16:44:09 +0100693 addDeviceInotify();
694 isDeviceInotifyAdded = true;
695 if (errorCode) {
696 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
697 errorCode.message().c_str());
698 }
699 }
700
701 if (isV4lScanningEnabled() && !isDeviceInotifyAdded) {
702 addDeviceInotify();
703 } else {
Philip Quinn39b81682019-01-09 22:20:39 -0800704 ALOGI("Video device scanning disabled");
705 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800706
Siarhei Vishniakou2d0e9482019-09-24 12:52:47 +0100707 struct epoll_event eventItem = {};
708 eventItem.events = EPOLLIN | EPOLLWAKEUP;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700709 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800710 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800711 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
712
713 int wakeFds[2];
714 result = pipe(wakeFds);
715 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
716
717 mWakeReadPipeFd = wakeFds[0];
718 mWakeWritePipeFd = wakeFds[1];
719
720 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
721 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700722 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800723
724 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
725 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700726 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800727
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700728 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800729 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
730 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700731 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800732}
733
734EventHub::~EventHub(void) {
735 closeAllDevicesLocked();
736
Michael Wrightd02c5b62014-02-10 15:10:22 -0800737 ::close(mEpollFd);
738 ::close(mINotifyFd);
739 ::close(mWakeReadPipeFd);
740 ::close(mWakeWritePipeFd);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800741}
742
Usama Arif78eb9752021-06-03 16:44:09 +0100743/**
744 * On devices that don't have any input devices (like some development boards), the /dev/input
745 * directory will be absent. However, the user may still plug in an input device at a later time.
746 * Add watch for contents of /dev/input only when /dev/input appears.
747 */
748void EventHub::addDeviceInputInotify() {
749 mDeviceInputWd = inotify_add_watch(mINotifyFd, DEVICE_INPUT_PATH, IN_DELETE | IN_CREATE);
750 LOG_ALWAYS_FATAL_IF(mDeviceInputWd < 0, "Could not register INotify for %s: %s",
751 DEVICE_INPUT_PATH, strerror(errno));
752}
753
754void EventHub::addDeviceInotify() {
755 mDeviceWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
756 LOG_ALWAYS_FATAL_IF(mDeviceWd < 0, "Could not register INotify for %s: %s", DEVICE_PATH,
757 strerror(errno));
758}
759
Michael Wrightd02c5b62014-02-10 15:10:22 -0800760InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000761 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800762 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700763 return device != nullptr ? device->identifier : InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800764}
765
Chris Ye1b0c7342020-07-28 21:57:03 -0700766Flags<InputDeviceClass> EventHub::getDeviceClasses(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000767 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800768 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700769 return device != nullptr ? device->classes : Flags<InputDeviceClass>(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800770}
771
772int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000773 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800774 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700775 return device != nullptr ? device->controllerNumber : 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800776}
777
778void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
Chris Ye87143712020-11-10 05:05:58 +0000779 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800780 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700781 if (device != nullptr && device->configuration) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800782 *outConfiguration = *device->configuration;
783 } else {
784 outConfiguration->clear();
785 }
786}
787
788status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700789 RawAbsoluteAxisInfo* outAxisInfo) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800790 outAxisInfo->clear();
791
792 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000793 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800794
795 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700796 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800797 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700798 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
799 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
800 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800801 return -errno;
802 }
803
804 if (info.minimum != info.maximum) {
805 outAxisInfo->valid = true;
806 outAxisInfo->minValue = info.minimum;
807 outAxisInfo->maxValue = info.maximum;
808 outAxisInfo->flat = info.flat;
809 outAxisInfo->fuzz = info.fuzz;
810 outAxisInfo->resolution = info.resolution;
811 }
812 return OK;
813 }
814 }
815 return -1;
816}
817
818bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
819 if (axis >= 0 && axis <= REL_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000820 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800821 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700822 return device != nullptr ? device->relBitmask.test(axis) : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800823 }
824 return false;
825}
826
827bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
Chris Ye87143712020-11-10 05:05:58 +0000828 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800829
Chris Ye989bb932020-07-04 16:18:59 -0700830 Device* device = getDeviceLocked(deviceId);
831 return property >= 0 && property <= INPUT_PROP_MAX && device != nullptr
832 ? device->propBitmask.test(property)
833 : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800834}
835
Chris Yef59a2f42020-10-16 12:55:26 -0700836bool EventHub::hasMscEvent(int32_t deviceId, int mscEvent) const {
837 std::scoped_lock _l(mLock);
838
839 Device* device = getDeviceLocked(deviceId);
840 return mscEvent >= 0 && mscEvent <= MSC_MAX && device != nullptr
841 ? device->mscBitmask.test(mscEvent)
842 : false;
843}
844
Michael Wrightd02c5b62014-02-10 15:10:22 -0800845int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
846 if (scanCode >= 0 && scanCode <= KEY_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000847 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800848
849 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700850 if (device != nullptr && device->hasValidFd() && device->keyBitmask.test(scanCode)) {
851 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
852 return device->keyState.test(scanCode) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800853 }
854 }
855 }
856 return AKEY_STATE_UNKNOWN;
857}
858
859int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
Chris Ye87143712020-11-10 05:05:58 +0000860 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800861
862 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700863 if (device != nullptr && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou984f40b2022-05-18 09:45:54 -0700864 std::vector<int32_t> scanCodes = device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800865 if (scanCodes.size() != 0) {
Chris Ye66fbac32020-07-06 20:36:43 -0700866 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800867 for (size_t i = 0; i < scanCodes.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800868 int32_t sc = scanCodes[i];
Chris Ye66fbac32020-07-06 20:36:43 -0700869 if (sc >= 0 && sc <= KEY_MAX && device->keyState.test(sc)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800870 return AKEY_STATE_DOWN;
871 }
872 }
873 return AKEY_STATE_UP;
874 }
875 }
876 }
877 return AKEY_STATE_UNKNOWN;
878}
879
880int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
881 if (sw >= 0 && sw <= SW_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000882 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800883
884 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700885 if (device != nullptr && device->hasValidFd() && device->swBitmask.test(sw)) {
886 if (device->readDeviceBitMask(EVIOCGSW(0), device->swState) >= 0) {
887 return device->swState.test(sw) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800888 }
889 }
890 }
891 return AKEY_STATE_UNKNOWN;
892}
893
894status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
895 *outValue = 0;
896
897 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000898 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800899
900 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700901 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800902 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700903 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
904 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
905 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800906 return -errno;
907 }
908
909 *outValue = info.value;
910 return OK;
911 }
912 }
913 return -1;
914}
915
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700916bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes, const int32_t* keyCodes,
917 uint8_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +0000918 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800919
920 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700921 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800922 for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) {
Siarhei Vishniakou984f40b2022-05-18 09:45:54 -0700923 std::vector<int32_t> scanCodes =
924 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCodes[codeIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800925
Siarhei Vishniakou984f40b2022-05-18 09:45:54 -0700926 // check the possible scan codes identified by the layout map against the
927 // map of codes actually emitted by the driver
928 for (size_t sc = 0; sc < scanCodes.size(); sc++) {
929 if (device->keyBitmask.test(scanCodes[sc])) {
930 outFlags[codeIndex] = 1;
931 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800932 }
933 }
934 }
935 return true;
936 }
937 return false;
938}
939
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700940status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
941 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +0000942 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800943 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700944 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800945
Chris Ye66fbac32020-07-06 20:36:43 -0700946 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800947 // Check the key character map first.
Chris Ye3a1e4462020-08-12 10:13:15 -0700948 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
949 if (kcm) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800950 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
951 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700952 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800953 }
954 }
955
956 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700957 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800958 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700959 status = NO_ERROR;
960 }
961 }
962
963 if (status == NO_ERROR) {
Chris Ye3a1e4462020-08-12 10:13:15 -0700964 if (kcm) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700965 kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState);
966 } else {
967 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800968 }
969 }
970 }
971
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700972 if (status != NO_ERROR) {
973 *outKeycode = 0;
974 *outFlags = 0;
975 *outMetaState = metaState;
976 }
977
978 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800979}
980
981status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
Chris Ye87143712020-11-10 05:05:58 +0000982 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800983 Device* device = getDeviceLocked(deviceId);
984
Siarhei Vishniakou984f40b2022-05-18 09:45:54 -0700985 if (device == nullptr || !device->keyMap.haveKeyLayout()) {
986 return NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800987 }
Siarhei Vishniakou984f40b2022-05-18 09:45:54 -0700988 std::optional<AxisInfo> info = device->keyMap.keyLayoutMap->mapAxis(scanCode);
989 if (!info.has_value()) {
990 return NAME_NOT_FOUND;
991 }
992 *outAxisInfo = *info;
993 return NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800994}
995
Chris Yef59a2f42020-10-16 12:55:26 -0700996base::Result<std::pair<InputDeviceSensorType, int32_t>> EventHub::mapSensor(int32_t deviceId,
997 int32_t absCode) {
998 std::scoped_lock _l(mLock);
999 Device* device = getDeviceLocked(deviceId);
1000
1001 if (device != nullptr && device->keyMap.haveKeyLayout()) {
1002 return device->keyMap.keyLayoutMap->mapSensor(absCode);
1003 }
1004 return Errorf("Device not found or device has no key layout.");
1005}
1006
Chris Yee2b1e5c2021-03-10 22:45:12 -08001007// Gets the battery info map from battery ID to RawBatteryInfo of the miscellaneous device
1008// associated with the device ID. Returns an empty map if no miscellaneous device found.
1009const std::unordered_map<int32_t, RawBatteryInfo>& EventHub::getBatteryInfoLocked(
1010 int32_t deviceId) const {
1011 static const std::unordered_map<int32_t, RawBatteryInfo> EMPTY_BATTERY_INFO = {};
1012 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001013 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001014 return EMPTY_BATTERY_INFO;
1015 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001016 return device->associatedDevice->batteryInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001017}
1018
1019const std::vector<int32_t> EventHub::getRawBatteryIds(int32_t deviceId) {
1020 std::scoped_lock _l(mLock);
1021 std::vector<int32_t> batteryIds;
1022
1023 for (const auto [id, info] : getBatteryInfoLocked(deviceId)) {
1024 batteryIds.push_back(id);
1025 }
1026
1027 return batteryIds;
1028}
1029
1030std::optional<RawBatteryInfo> EventHub::getRawBatteryInfo(int32_t deviceId, int32_t batteryId) {
1031 std::scoped_lock _l(mLock);
1032
1033 const auto infos = getBatteryInfoLocked(deviceId);
1034
1035 auto it = infos.find(batteryId);
1036 if (it != infos.end()) {
1037 return it->second;
1038 }
1039
1040 return std::nullopt;
1041}
1042
1043// Gets the light info map from light ID to RawLightInfo of the miscellaneous device associated
1044// with the deivice ID. Returns an empty map if no miscellaneous device found.
1045const std::unordered_map<int32_t, RawLightInfo>& EventHub::getLightInfoLocked(
1046 int32_t deviceId) const {
1047 static const std::unordered_map<int32_t, RawLightInfo> EMPTY_LIGHT_INFO = {};
1048 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001049 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001050 return EMPTY_LIGHT_INFO;
1051 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001052 return device->associatedDevice->lightInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001053}
1054
Chris Ye3fdbfef2021-01-06 18:45:18 -08001055const std::vector<int32_t> EventHub::getRawLightIds(int32_t deviceId) {
1056 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001057 std::vector<int32_t> lightIds;
1058
Chris Yee2b1e5c2021-03-10 22:45:12 -08001059 for (const auto [id, info] : getLightInfoLocked(deviceId)) {
1060 lightIds.push_back(id);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001061 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001062
Chris Ye3fdbfef2021-01-06 18:45:18 -08001063 return lightIds;
1064}
1065
1066std::optional<RawLightInfo> EventHub::getRawLightInfo(int32_t deviceId, int32_t lightId) {
1067 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001068
Chris Yee2b1e5c2021-03-10 22:45:12 -08001069 const auto infos = getLightInfoLocked(deviceId);
1070
1071 auto it = infos.find(lightId);
1072 if (it != infos.end()) {
1073 return it->second;
Chris Ye3fdbfef2021-01-06 18:45:18 -08001074 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001075
Chris Ye3fdbfef2021-01-06 18:45:18 -08001076 return std::nullopt;
1077}
1078
1079std::optional<int32_t> EventHub::getLightBrightness(int32_t deviceId, int32_t lightId) {
1080 std::scoped_lock _l(mLock);
1081
Chris Yee2b1e5c2021-03-10 22:45:12 -08001082 const auto infos = getLightInfoLocked(deviceId);
1083 auto it = infos.find(lightId);
1084 if (it == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001085 return std::nullopt;
1086 }
1087 std::string buffer;
1088 if (!base::ReadFileToString(it->second.path / LIGHT_NODES.at(InputLightClass::BRIGHTNESS),
1089 &buffer)) {
1090 return std::nullopt;
1091 }
1092 return std::stoi(buffer);
1093}
1094
1095std::optional<std::unordered_map<LightColor, int32_t>> EventHub::getLightIntensities(
1096 int32_t deviceId, int32_t lightId) {
1097 std::scoped_lock _l(mLock);
1098
Chris Yee2b1e5c2021-03-10 22:45:12 -08001099 const auto infos = getLightInfoLocked(deviceId);
1100 auto lightIt = infos.find(lightId);
1101 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001102 return std::nullopt;
1103 }
1104
1105 auto ret =
1106 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1107
1108 if (!ret.has_value()) {
1109 return std::nullopt;
1110 }
1111 std::array<LightColor, COLOR_NUM> colors = ret.value();
1112
1113 std::string intensityStr;
1114 if (!base::ReadFileToString(lightIt->second.path /
1115 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY),
1116 &intensityStr)) {
1117 return std::nullopt;
1118 }
1119
1120 // Intensity node outputs 3 color values
1121 std::regex intensityPattern("([0-9]+)\\s([0-9]+)\\s([0-9]+)[\\n]");
1122 std::smatch results;
1123
1124 if (!std::regex_match(intensityStr, results, intensityPattern)) {
1125 return std::nullopt;
1126 }
1127 std::unordered_map<LightColor, int32_t> intensities;
1128 for (size_t i = 1; i < results.size(); i++) {
1129 int value = std::stoi(results[i].str());
1130 intensities.emplace(colors[i - 1], value);
1131 }
1132 return intensities;
1133}
1134
1135void EventHub::setLightBrightness(int32_t deviceId, int32_t lightId, int32_t brightness) {
1136 std::scoped_lock _l(mLock);
1137
Chris Yee2b1e5c2021-03-10 22:45:12 -08001138 const auto infos = getLightInfoLocked(deviceId);
1139 auto lightIt = infos.find(lightId);
1140 if (lightIt == infos.end()) {
1141 ALOGE("%s lightId %d not found ", __func__, lightId);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001142 return;
1143 }
1144
1145 if (!base::WriteStringToFile(std::to_string(brightness),
1146 lightIt->second.path /
1147 LIGHT_NODES.at(InputLightClass::BRIGHTNESS))) {
1148 ALOGE("Can not write to file, error: %s", strerror(errno));
1149 }
1150}
1151
1152void EventHub::setLightIntensities(int32_t deviceId, int32_t lightId,
1153 std::unordered_map<LightColor, int32_t> intensities) {
1154 std::scoped_lock _l(mLock);
1155
Chris Yee2b1e5c2021-03-10 22:45:12 -08001156 const auto infos = getLightInfoLocked(deviceId);
1157 auto lightIt = infos.find(lightId);
1158 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001159 ALOGE("Light Id %d does not exist.", lightId);
1160 return;
1161 }
1162
1163 auto ret =
1164 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1165
1166 if (!ret.has_value()) {
1167 return;
1168 }
1169 std::array<LightColor, COLOR_NUM> colors = ret.value();
1170
1171 std::string rgbStr;
1172 for (size_t i = 0; i < COLOR_NUM; i++) {
1173 auto it = intensities.find(colors[i]);
1174 if (it != intensities.end()) {
1175 rgbStr += std::to_string(it->second);
1176 // Insert space between colors
1177 if (i < COLOR_NUM - 1) {
1178 rgbStr += " ";
1179 }
1180 }
1181 }
1182 // Append new line
1183 rgbStr += "\n";
1184
1185 if (!base::WriteStringToFile(rgbStr,
1186 lightIt->second.path /
1187 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY))) {
1188 ALOGE("Can not write to file, error: %s", strerror(errno));
1189 }
1190}
1191
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001192void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Chris Ye87143712020-11-10 05:05:58 +00001193 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194
1195 mExcludedDevices = devices;
1196}
1197
1198bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
Chris Ye87143712020-11-10 05:05:58 +00001199 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001200 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001201 if (device != nullptr && scanCode >= 0 && scanCode <= KEY_MAX) {
1202 return device->keyBitmask.test(scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001203 }
1204 return false;
1205}
1206
1207bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
Chris Ye87143712020-11-10 05:05:58 +00001208 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001209 Device* device = getDeviceLocked(deviceId);
1210 int32_t sc;
Chris Ye989bb932020-07-04 16:18:59 -07001211 if (device != nullptr && device->mapLed(led, &sc) == NO_ERROR) {
Chris Ye66fbac32020-07-06 20:36:43 -07001212 return device->ledBitmask.test(sc);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001213 }
1214 return false;
1215}
1216
1217void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
Chris Ye87143712020-11-10 05:05:58 +00001218 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001219 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -07001220 if (device != nullptr && device->hasValidFd()) {
1221 device->setLedStateLocked(led, on);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001222 }
1223}
1224
1225void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001226 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001227 outVirtualKeys.clear();
1228
Chris Ye87143712020-11-10 05:05:58 +00001229 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001230 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001231 if (device != nullptr && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001232 const std::vector<VirtualKeyDefinition> virtualKeys =
1233 device->virtualKeyMap->getVirtualKeys();
1234 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001235 }
1236}
1237
Chris Ye3a1e4462020-08-12 10:13:15 -07001238const std::shared_ptr<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001239 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001240 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001241 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001242 return device->getKeyCharacterMap();
1243 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001244 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001245}
1246
Chris Ye3a1e4462020-08-12 10:13:15 -07001247bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, std::shared_ptr<KeyCharacterMap> map) {
Chris Ye87143712020-11-10 05:05:58 +00001248 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001249 Device* device = getDeviceLocked(deviceId);
Philip Junkerb60596f2021-12-10 18:39:42 +01001250 if (device == nullptr || map == nullptr || device->keyMap.keyCharacterMap == nullptr) {
1251 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001252 }
Philip Junkerb60596f2021-12-10 18:39:42 +01001253 device->keyMap.keyCharacterMap->combine(*map);
1254 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001255}
1256
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001257static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
1258 std::string rawDescriptor;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001259 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001260 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001261 if (!identifier.uniqueId.empty()) {
1262 rawDescriptor += "uniqueId:";
1263 rawDescriptor += identifier.uniqueId;
Josh Bartel938632f2022-07-19 15:34:22 -05001264 }
1265 if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001266 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001267 }
1268
1269 if (identifier.vendor == 0 && identifier.product == 0) {
1270 // If we don't know the vendor and product id, then the device is probably
1271 // built-in so we need to rely on other information to uniquely identify
1272 // the input device. Usually we try to avoid relying on the device name or
1273 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001274 if (!identifier.name.empty()) {
1275 rawDescriptor += "name:";
1276 rawDescriptor += identifier.name;
1277 } else if (!identifier.location.empty()) {
1278 rawDescriptor += "location:";
1279 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001280 }
1281 }
1282 identifier.descriptor = sha1(rawDescriptor);
1283 return rawDescriptor;
1284}
1285
1286void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
1287 // Compute a device descriptor that uniquely identifies the device.
1288 // The descriptor is assumed to be a stable identifier. Its value should not
1289 // change between reboots, reconnections, firmware updates or new releases
1290 // of Android. In practice we sometimes get devices that cannot be uniquely
1291 // identified. In this case we enforce uniqueness between connected devices.
1292 // Ideally, we also want the descriptor to be short and relatively opaque.
Josh Bartel938632f2022-07-19 15:34:22 -05001293 // Note that we explicitly do not use the path or location for external devices
1294 // as their path or location will change as they are plugged/unplugged or moved
1295 // to different ports. We do fallback to using name and location in the case of
1296 // internal devices which are detected by the vendor and product being 0 in
1297 // generateDescriptor. If two identical descriptors are detected we will fallback
1298 // to using a 'nonce' and incrementing it until the new descriptor no longer has
1299 // a match with any existing descriptors.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001300
1301 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001302 std::string rawDescriptor = generateDescriptor(identifier);
Josh Bartel938632f2022-07-19 15:34:22 -05001303 // Enforce that the generated descriptor is unique.
1304 while (hasDeviceWithDescriptorLocked(identifier.descriptor)) {
1305 identifier.nonce++;
1306 rawDescriptor = generateDescriptor(identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001307 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001308 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001309 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001310}
1311
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001312void EventHub::vibrate(int32_t deviceId, const VibrationElement& element) {
Chris Ye87143712020-11-10 05:05:58 +00001313 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001314 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001315 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001316 ff_effect effect;
1317 memset(&effect, 0, sizeof(effect));
1318 effect.type = FF_RUMBLE;
1319 effect.id = device->ffEffectId;
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001320 // evdev FF_RUMBLE effect only supports two channels of vibration.
Chris Ye6393a262020-08-04 19:41:36 -07001321 effect.u.rumble.strong_magnitude = element.getMagnitude(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1322 effect.u.rumble.weak_magnitude = element.getMagnitude(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001323 effect.replay.length = element.duration.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001324 effect.replay.delay = 0;
1325 if (ioctl(device->fd, EVIOCSFF, &effect)) {
1326 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001327 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001328 return;
1329 }
1330 device->ffEffectId = effect.id;
1331
1332 struct input_event ev;
1333 ev.time.tv_sec = 0;
1334 ev.time.tv_usec = 0;
1335 ev.type = EV_FF;
1336 ev.code = device->ffEffectId;
1337 ev.value = 1;
1338 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1339 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001340 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001341 return;
1342 }
1343 device->ffEffectPlaying = true;
1344 }
1345}
1346
1347void EventHub::cancelVibrate(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001348 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001349 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001350 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001351 if (device->ffEffectPlaying) {
1352 device->ffEffectPlaying = false;
1353
1354 struct input_event ev;
1355 ev.time.tv_sec = 0;
1356 ev.time.tv_usec = 0;
1357 ev.type = EV_FF;
1358 ev.code = device->ffEffectId;
1359 ev.value = 0;
1360 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1361 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001362 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001363 return;
1364 }
1365 }
1366 }
1367}
1368
Chris Ye87143712020-11-10 05:05:58 +00001369std::vector<int32_t> EventHub::getVibratorIds(int32_t deviceId) {
1370 std::scoped_lock _l(mLock);
1371 std::vector<int32_t> vibrators;
1372 Device* device = getDeviceLocked(deviceId);
1373 if (device != nullptr && device->hasValidFd() &&
1374 device->classes.test(InputDeviceClass::VIBRATOR)) {
1375 vibrators.push_back(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1376 vibrators.push_back(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
1377 }
1378 return vibrators;
1379}
1380
Josh Bartel938632f2022-07-19 15:34:22 -05001381/**
1382 * Checks both mDevices and mOpeningDevices for a device with the descriptor passed.
1383 */
1384bool EventHub::hasDeviceWithDescriptorLocked(const std::string& descriptor) const {
1385 for (const auto& device : mOpeningDevices) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001386 if (descriptor == device->identifier.descriptor) {
Josh Bartel938632f2022-07-19 15:34:22 -05001387 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001388 }
1389 }
Josh Bartel938632f2022-07-19 15:34:22 -05001390
1391 for (const auto& [id, device] : mDevices) {
1392 if (descriptor == device->identifier.descriptor) {
1393 return true;
1394 }
1395 }
1396 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001397}
1398
1399EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001400 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001401 deviceId = mBuiltInKeyboardId;
1402 }
Chris Ye989bb932020-07-04 16:18:59 -07001403 const auto& it = mDevices.find(deviceId);
1404 return it != mDevices.end() ? it->second.get() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001405}
1406
Chris Ye8594e192020-07-14 10:34:06 -07001407EventHub::Device* EventHub::getDeviceByPathLocked(const std::string& devicePath) const {
Chris Ye989bb932020-07-04 16:18:59 -07001408 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001409 if (device->path == devicePath) {
Chris Ye989bb932020-07-04 16:18:59 -07001410 return device.get();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001411 }
1412 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001413 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001414}
1415
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001416/**
1417 * The file descriptor could be either input device, or a video device (associated with a
1418 * specific input device). Check both cases here, and return the device that this event
1419 * belongs to. Caller can compare the fd's once more to determine event type.
1420 * Looks through all input devices, and only attached video devices. Unattached video
1421 * devices are ignored.
1422 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001423EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
Chris Ye989bb932020-07-04 16:18:59 -07001424 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001425 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001426 // This is an input device event
Chris Ye989bb932020-07-04 16:18:59 -07001427 return device.get();
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001428 }
1429 if (device->videoDevice && device->videoDevice->getFd() == fd) {
1430 // This is a video device event
Chris Ye989bb932020-07-04 16:18:59 -07001431 return device.get();
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001432 }
1433 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001434 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
1435 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001436 return nullptr;
1437}
1438
Chris Yee2b1e5c2021-03-10 22:45:12 -08001439std::optional<int32_t> EventHub::getBatteryCapacity(int32_t deviceId, int32_t batteryId) const {
Kim Low03ea0352020-11-06 12:45:07 -08001440 std::scoped_lock _l(mLock);
Kim Low03ea0352020-11-06 12:45:07 -08001441
Chris Yee2b1e5c2021-03-10 22:45:12 -08001442 const auto infos = getBatteryInfoLocked(deviceId);
1443 auto it = infos.find(batteryId);
1444 if (it == infos.end()) {
Kim Low03ea0352020-11-06 12:45:07 -08001445 return std::nullopt;
1446 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001447 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001448
1449 // Some devices report battery capacity as an integer through the "capacity" file
Chris Yee2b1e5c2021-03-10 22:45:12 -08001450 if (base::ReadFileToString(it->second.path / BATTERY_NODES.at(InputBatteryClass::CAPACITY),
1451 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001452 return std::stoi(base::Trim(buffer));
Kim Low03ea0352020-11-06 12:45:07 -08001453 }
1454
1455 // Other devices report capacity as an enum value POWER_SUPPLY_CAPACITY_LEVEL_XXX
1456 // These values are taken from kernel source code include/linux/power_supply.h
Chris Yee2b1e5c2021-03-10 22:45:12 -08001457 if (base::ReadFileToString(it->second.path /
1458 BATTERY_NODES.at(InputBatteryClass::CAPACITY_LEVEL),
1459 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001460 // Remove any white space such as trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001461 const auto levelIt = BATTERY_LEVEL.find(base::Trim(buffer));
1462 if (levelIt != BATTERY_LEVEL.end()) {
1463 return levelIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001464 }
1465 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001466
Kim Low03ea0352020-11-06 12:45:07 -08001467 return std::nullopt;
1468}
1469
Chris Yee2b1e5c2021-03-10 22:45:12 -08001470std::optional<int32_t> EventHub::getBatteryStatus(int32_t deviceId, int32_t batteryId) const {
Kim Low03ea0352020-11-06 12:45:07 -08001471 std::scoped_lock _l(mLock);
Chris Yee2b1e5c2021-03-10 22:45:12 -08001472 const auto infos = getBatteryInfoLocked(deviceId);
1473 auto it = infos.find(batteryId);
1474 if (it == infos.end()) {
Kim Low03ea0352020-11-06 12:45:07 -08001475 return std::nullopt;
1476 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001477 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001478
Chris Yee2b1e5c2021-03-10 22:45:12 -08001479 if (!base::ReadFileToString(it->second.path / BATTERY_NODES.at(InputBatteryClass::STATUS),
1480 &buffer)) {
Kim Low03ea0352020-11-06 12:45:07 -08001481 ALOGE("Failed to read sysfs battery info: %s", strerror(errno));
1482 return std::nullopt;
1483 }
1484
Chris Yed1936772021-02-22 10:30:40 -08001485 // Remove white space like trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001486 const auto statusIt = BATTERY_STATUS.find(base::Trim(buffer));
1487 if (statusIt != BATTERY_STATUS.end()) {
1488 return statusIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001489 }
1490
1491 return std::nullopt;
1492}
1493
Michael Wrightd02c5b62014-02-10 15:10:22 -08001494size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
1495 ALOG_ASSERT(bufferSize >= 1);
1496
Chris Ye87143712020-11-10 05:05:58 +00001497 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001498
1499 struct input_event readBuffer[bufferSize];
1500
1501 RawEvent* event = buffer;
1502 size_t capacity = bufferSize;
1503 bool awoken = false;
1504 for (;;) {
1505 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
1506
1507 // Reopen input devices if needed.
1508 if (mNeedToReopenDevices) {
1509 mNeedToReopenDevices = false;
1510
1511 ALOGI("Reopening all input devices due to a configuration change.");
1512
1513 closeAllDevicesLocked();
1514 mNeedToScanDevices = true;
1515 break; // return to the caller before we actually rescan
1516 }
1517
1518 // Report any devices that had last been added/removed.
Chris Ye989bb932020-07-04 16:18:59 -07001519 for (auto it = mClosingDevices.begin(); it != mClosingDevices.end();) {
1520 std::unique_ptr<Device> device = std::move(*it);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001521 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001522 event->when = now;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001523 event->deviceId = (device->id == mBuiltInKeyboardId)
1524 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
1525 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001526 event->type = DEVICE_REMOVED;
1527 event += 1;
Chris Ye989bb932020-07-04 16:18:59 -07001528 it = mClosingDevices.erase(it);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001529 mNeedToSendFinishedDeviceScan = true;
1530 if (--capacity == 0) {
1531 break;
1532 }
1533 }
1534
1535 if (mNeedToScanDevices) {
1536 mNeedToScanDevices = false;
1537 scanDevicesLocked();
1538 mNeedToSendFinishedDeviceScan = true;
1539 }
1540
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001541 while (!mOpeningDevices.empty()) {
1542 std::unique_ptr<Device> device = std::move(*mOpeningDevices.rbegin());
1543 mOpeningDevices.pop_back();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001544 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001545 event->when = now;
1546 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1547 event->type = DEVICE_ADDED;
1548 event += 1;
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001549
1550 // Try to find a matching video device by comparing device names
1551 for (auto it = mUnattachedVideoDevices.begin(); it != mUnattachedVideoDevices.end();
1552 it++) {
1553 std::unique_ptr<TouchVideoDevice>& videoDevice = *it;
Chris Yed3fef462021-03-07 17:10:08 -08001554 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001555 // videoDevice was transferred to 'device'
1556 it = mUnattachedVideoDevices.erase(it);
1557 break;
1558 }
1559 }
1560
1561 auto [dev_it, inserted] = mDevices.insert_or_assign(device->id, std::move(device));
1562 if (!inserted) {
Chris Ye989bb932020-07-04 16:18:59 -07001563 ALOGW("Device id %d exists, replaced.", device->id);
1564 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001565 mNeedToSendFinishedDeviceScan = true;
1566 if (--capacity == 0) {
1567 break;
1568 }
1569 }
1570
1571 if (mNeedToSendFinishedDeviceScan) {
1572 mNeedToSendFinishedDeviceScan = false;
1573 event->when = now;
1574 event->type = FINISHED_DEVICE_SCAN;
1575 event += 1;
1576 if (--capacity == 0) {
1577 break;
1578 }
1579 }
1580
1581 // Grab the next input event.
1582 bool deviceChanged = false;
1583 while (mPendingEventIndex < mPendingEventCount) {
1584 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001585 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001586 if (eventItem.events & EPOLLIN) {
1587 mPendingINotify = true;
1588 } else {
1589 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
1590 }
1591 continue;
1592 }
1593
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001594 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001595 if (eventItem.events & EPOLLIN) {
1596 ALOGV("awoken after wake()");
1597 awoken = true;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001598 char wakeReadBuffer[16];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001599 ssize_t nRead;
1600 do {
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001601 nRead = read(mWakeReadPipeFd, wakeReadBuffer, sizeof(wakeReadBuffer));
1602 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(wakeReadBuffer));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001603 } else {
1604 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001605 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001606 }
1607 continue;
1608 }
1609
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001610 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Chris Ye989bb932020-07-04 16:18:59 -07001611 if (device == nullptr) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001612 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
1613 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001614 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001615 continue;
1616 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001617 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
1618 if (eventItem.events & EPOLLIN) {
1619 size_t numFrames = device->videoDevice->readAndQueueFrames();
1620 if (numFrames == 0) {
1621 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001622 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001623 }
1624 } else if (eventItem.events & EPOLLHUP) {
1625 // TODO(b/121395353) - consider adding EPOLLRDHUP
1626 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001627 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001628 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1629 device->videoDevice = nullptr;
1630 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001631 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1632 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001633 ALOG_ASSERT(!DEBUG);
1634 }
1635 continue;
1636 }
1637 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -08001638 if (eventItem.events & EPOLLIN) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001639 int32_t readSize =
1640 read(device->fd, readBuffer, sizeof(struct input_event) * capacity);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001641 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
1642 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -07001643 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001644 " bufferSize: %zu capacity: %zu errno: %d)\n",
1645 device->fd, readSize, bufferSize, capacity, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001646 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001647 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001648 } else if (readSize < 0) {
1649 if (errno != EAGAIN && errno != EINTR) {
1650 ALOGW("could not get event (errno=%d)", errno);
1651 }
1652 } else if ((readSize % sizeof(struct input_event)) != 0) {
1653 ALOGE("could not get event (wrong size: %d)", readSize);
1654 } else {
1655 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1656
1657 size_t count = size_t(readSize) / sizeof(struct input_event);
1658 for (size_t i = 0; i < count; i++) {
1659 struct input_event& iev = readBuffer[i];
Siarhei Vishniakou592bac22018-11-08 19:42:38 -08001660 event->when = processEventTimestamp(iev);
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001661 event->readTime = systemTime(SYSTEM_TIME_MONOTONIC);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001662 event->deviceId = deviceId;
1663 event->type = iev.type;
1664 event->code = iev.code;
1665 event->value = iev.value;
1666 event += 1;
1667 capacity -= 1;
1668 }
1669 if (capacity == 0) {
1670 // The result buffer is full. Reset the pending event index
1671 // so we will try to read the device again on the next iteration.
1672 mPendingEventIndex -= 1;
1673 break;
1674 }
1675 }
1676 } else if (eventItem.events & EPOLLHUP) {
1677 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001678 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001679 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001680 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001681 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001682 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1683 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001684 }
1685 }
1686
1687 // readNotify() will modify the list of devices so this must be done after
1688 // processing all other events to ensure that we read all remaining events
1689 // before closing the devices.
1690 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
1691 mPendingINotify = false;
1692 readNotifyLocked();
1693 deviceChanged = true;
1694 }
1695
1696 // Report added or removed devices immediately.
1697 if (deviceChanged) {
1698 continue;
1699 }
1700
1701 // Return now if we have collected any events or if we were explicitly awoken.
1702 if (event != buffer || awoken) {
1703 break;
1704 }
1705
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001706 // Poll for events.
1707 // When a device driver has pending (unread) events, it acquires
1708 // a kernel wake lock. Once the last pending event has been read, the device
1709 // driver will release the kernel wake lock, but the epoll will hold the wakelock,
1710 // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
1711 // is called again for the same fd that produced the event.
1712 // Thus the system can only sleep if there are no events pending or
1713 // currently being processed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001714 //
1715 // The timeout is advisory only. If the device is asleep, it will not wake just to
1716 // service the timeout.
1717 mPendingEventIndex = 0;
1718
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001719 mLock.unlock(); // release lock before poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001720
1721 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1722
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001723 mLock.lock(); // reacquire lock after poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001724
1725 if (pollResult == 0) {
1726 // Timed out.
1727 mPendingEventCount = 0;
1728 break;
1729 }
1730
1731 if (pollResult < 0) {
1732 // An error occurred.
1733 mPendingEventCount = 0;
1734
1735 // Sleep after errors to avoid locking up the system.
1736 // Hopefully the error is transient.
1737 if (errno != EINTR) {
1738 ALOGW("poll failed (errno=%d)\n", errno);
1739 usleep(100000);
1740 }
1741 } else {
1742 // Some events occurred.
1743 mPendingEventCount = size_t(pollResult);
1744 }
1745 }
1746
1747 // All done, return the number of events we read.
1748 return event - buffer;
1749}
1750
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001751std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001752 std::scoped_lock _l(mLock);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001753
1754 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001755 if (device == nullptr || !device->videoDevice) {
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001756 return {};
1757 }
1758 return device->videoDevice->consumeFrames();
1759}
1760
Michael Wrightd02c5b62014-02-10 15:10:22 -08001761void EventHub::wake() {
1762 ALOGV("wake() called");
1763
1764 ssize_t nWrite;
1765 do {
1766 nWrite = write(mWakeWritePipeFd, "W", 1);
1767 } while (nWrite == -1 && errno == EINTR);
1768
1769 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001770 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001771 }
1772}
1773
1774void EventHub::scanDevicesLocked() {
Usama Arif78eb9752021-06-03 16:44:09 +01001775 status_t result;
1776 std::error_code errorCode;
1777
1778 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
1779 result = scanDirLocked(DEVICE_INPUT_PATH);
1780 if (result < 0) {
1781 ALOGE("scan dir failed for %s", DEVICE_INPUT_PATH);
1782 }
1783 } else {
1784 if (errorCode) {
1785 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
1786 errorCode.message().c_str());
1787 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001788 }
Philip Quinn39b81682019-01-09 22:20:39 -08001789 if (isV4lScanningEnabled()) {
Usama Arif78eb9752021-06-03 16:44:09 +01001790 result = scanVideoDirLocked(DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08001791 if (result != OK) {
Usama Arif78eb9752021-06-03 16:44:09 +01001792 ALOGE("scan video dir failed for %s", DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08001793 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001794 }
Chris Ye989bb932020-07-04 16:18:59 -07001795 if (mDevices.find(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) == mDevices.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001796 createVirtualKeyboardLocked();
1797 }
1798}
1799
1800// ----------------------------------------------------------------------------
1801
Michael Wrightd02c5b62014-02-10 15:10:22 -08001802static const int32_t GAMEPAD_KEYCODES[] = {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001803 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C, //
1804 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z, //
1805 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1, //
1806 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2, //
1807 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR, //
1808 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE, //
Michael Wrightd02c5b62014-02-10 15:10:22 -08001809};
1810
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001811status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001812 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001813 struct epoll_event eventItem = {};
1814 eventItem.events = EPOLLIN | EPOLLWAKEUP;
1815 eventItem.data.fd = fd;
1816 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1817 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001818 return -errno;
1819 }
1820 return OK;
1821}
1822
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001823status_t EventHub::unregisterFdFromEpoll(int fd) {
1824 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
1825 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
1826 return -errno;
1827 }
1828 return OK;
1829}
1830
Chris Ye989bb932020-07-04 16:18:59 -07001831status_t EventHub::registerDeviceForEpollLocked(Device& device) {
1832 status_t result = registerFdForEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001833 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07001834 ALOGE("Could not add input device fd to epoll for device %" PRId32, device.id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001835 return result;
1836 }
Chris Ye989bb932020-07-04 16:18:59 -07001837 if (device.videoDevice) {
1838 registerVideoDeviceForEpollLocked(*device.videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001839 }
1840 return result;
1841}
1842
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001843void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
1844 status_t result = registerFdForEpoll(videoDevice.getFd());
1845 if (result != OK) {
1846 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
1847 }
1848}
1849
Chris Ye989bb932020-07-04 16:18:59 -07001850status_t EventHub::unregisterDeviceFromEpollLocked(Device& device) {
1851 if (device.hasValidFd()) {
1852 status_t result = unregisterFdFromEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001853 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07001854 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device.id);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001855 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001856 }
1857 }
Chris Ye989bb932020-07-04 16:18:59 -07001858 if (device.videoDevice) {
1859 unregisterVideoDeviceFromEpollLocked(*device.videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001860 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001861 return OK;
1862}
1863
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001864void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
1865 if (videoDevice.hasValidFd()) {
1866 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
1867 if (result != OK) {
1868 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001869 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001870 }
1871 }
1872}
1873
Chris Yed3fef462021-03-07 17:10:08 -08001874void EventHub::reportDeviceAddedForStatisticsLocked(const InputDeviceIdentifier& identifier,
1875 Flags<InputDeviceClass> classes) {
Chris Ye657c2f02021-05-25 16:24:37 -07001876 SHA256_CTX ctx;
1877 SHA256_Init(&ctx);
1878 SHA256_Update(&ctx, reinterpret_cast<const uint8_t*>(identifier.uniqueId.c_str()),
1879 identifier.uniqueId.size());
1880 std::array<uint8_t, SHA256_DIGEST_LENGTH> digest;
1881 SHA256_Final(digest.data(), &ctx);
1882
1883 std::string obfuscatedId;
1884 for (size_t i = 0; i < OBFUSCATED_LENGTH; i++) {
1885 obfuscatedId += StringPrintf("%02x", digest[i]);
1886 }
1887
Chris Yed3fef462021-03-07 17:10:08 -08001888 android::util::stats_write(android::util::INPUTDEVICE_REGISTERED, identifier.name.c_str(),
1889 identifier.vendor, identifier.product, identifier.version,
Chris Ye657c2f02021-05-25 16:24:37 -07001890 identifier.bus, obfuscatedId.c_str(), classes.get());
Chris Yed3fef462021-03-07 17:10:08 -08001891}
1892
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00001893void EventHub::openDeviceLocked(const std::string& devicePath) {
1894 // If an input device happens to register around the time when EventHub's constructor runs, it
1895 // is possible that the same input event node (for example, /dev/input/event3) will be noticed
1896 // in both 'inotify' callback and also in the 'scanDirLocked' pass. To prevent duplicate devices
1897 // from getting registered, ensure that this path is not already covered by an existing device.
1898 for (const auto& [deviceId, device] : mDevices) {
1899 if (device->path == devicePath) {
1900 return; // device was already registered
1901 }
1902 }
1903
Michael Wrightd02c5b62014-02-10 15:10:22 -08001904 char buffer[80];
1905
Chris Ye8594e192020-07-14 10:34:06 -07001906 ALOGV("Opening device: %s", devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001907
Chris Ye8594e192020-07-14 10:34:06 -07001908 int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001909 if (fd < 0) {
Chris Ye8594e192020-07-14 10:34:06 -07001910 ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00001911 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001912 }
1913
1914 InputDeviceIdentifier identifier;
1915
1916 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001917 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Chris Ye8594e192020-07-14 10:34:06 -07001918 ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001919 } else {
1920 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001921 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001922 }
1923
1924 // Check to see if the device is on our excluded list
1925 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001926 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001927 if (identifier.name == item) {
Chris Ye8594e192020-07-14 10:34:06 -07001928 ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001929 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00001930 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001931 }
1932 }
1933
1934 // Get device driver version.
1935 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001936 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Chris Ye8594e192020-07-14 10:34:06 -07001937 ALOGE("could not get driver version for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001938 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00001939 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001940 }
1941
1942 // Get device identifier.
1943 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001944 if (ioctl(fd, EVIOCGID, &inputId)) {
Chris Ye8594e192020-07-14 10:34:06 -07001945 ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001946 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00001947 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001948 }
1949 identifier.bus = inputId.bustype;
1950 identifier.product = inputId.product;
1951 identifier.vendor = inputId.vendor;
1952 identifier.version = inputId.version;
1953
1954 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001955 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
1956 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001957 } else {
1958 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001959 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001960 }
1961
1962 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001963 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
1964 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001965 } else {
1966 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001967 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001968 }
1969
1970 // Fill in the descriptor.
1971 assignDescriptorLocked(identifier);
1972
Michael Wrightd02c5b62014-02-10 15:10:22 -08001973 // Allocate device. (The device object takes ownership of the fd at this point.)
1974 int32_t deviceId = mNextDeviceId++;
Chris Ye989bb932020-07-04 16:18:59 -07001975 std::unique_ptr<Device> device = std::make_unique<Device>(fd, deviceId, devicePath, identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001976
Chris Ye8594e192020-07-14 10:34:06 -07001977 ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001978 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001979 " vendor %04x\n"
1980 " product %04x\n"
1981 " version %04x\n",
1982 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001983 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
1984 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
1985 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
1986 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001987 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
1988 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001989
1990 // Load the configuration file for the device.
Chris Ye989bb932020-07-04 16:18:59 -07001991 device->loadConfigurationLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001992
Chris Yee2b1e5c2021-03-10 22:45:12 -08001993 bool hasBattery = false;
1994 bool hasLights = false;
1995 // Check the sysfs root path
1996 std::optional<std::filesystem::path> sysfsRootPath = getSysfsRootPath(devicePath.c_str());
1997 if (sysfsRootPath.has_value()) {
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001998 std::shared_ptr<AssociatedDevice> associatedDevice;
1999 for (const auto& [id, dev] : mDevices) {
2000 if (device->identifier.descriptor == dev->identifier.descriptor &&
2001 !dev->associatedDevice) {
2002 associatedDevice = dev->associatedDevice;
2003 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08002004 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07002005 if (!associatedDevice) {
2006 associatedDevice = std::make_shared<AssociatedDevice>(sysfsRootPath.value());
2007 }
2008 hasBattery = associatedDevice->configureBatteryLocked();
2009 hasLights = associatedDevice->configureLightsLocked();
Chris Yee2b1e5c2021-03-10 22:45:12 -08002010
Chris Ye1dd2e5c2021-04-04 23:12:41 -07002011 device->associatedDevice = associatedDevice;
Chris Yee2b1e5c2021-03-10 22:45:12 -08002012 }
Chris Ye3fdbfef2021-01-06 18:45:18 -08002013
Michael Wrightd02c5b62014-02-10 15:10:22 -08002014 // Figure out the kinds of events the device reports.
Chris Ye66fbac32020-07-06 20:36:43 -07002015 device->readDeviceBitMask(EVIOCGBIT(EV_KEY, 0), device->keyBitmask);
2016 device->readDeviceBitMask(EVIOCGBIT(EV_ABS, 0), device->absBitmask);
2017 device->readDeviceBitMask(EVIOCGBIT(EV_REL, 0), device->relBitmask);
2018 device->readDeviceBitMask(EVIOCGBIT(EV_SW, 0), device->swBitmask);
2019 device->readDeviceBitMask(EVIOCGBIT(EV_LED, 0), device->ledBitmask);
2020 device->readDeviceBitMask(EVIOCGBIT(EV_FF, 0), device->ffBitmask);
Chris Yef59a2f42020-10-16 12:55:26 -07002021 device->readDeviceBitMask(EVIOCGBIT(EV_MSC, 0), device->mscBitmask);
Chris Ye66fbac32020-07-06 20:36:43 -07002022 device->readDeviceBitMask(EVIOCGPROP(0), device->propBitmask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002023
2024 // See if this is a keyboard. Ignore everything in the button range except for
2025 // joystick and gamepad buttons which are handled like keyboards for the most part.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002026 bool haveKeyboardKeys =
Chris Ye66fbac32020-07-06 20:36:43 -07002027 device->keyBitmask.any(0, BTN_MISC) || device->keyBitmask.any(BTN_WHEEL, KEY_MAX + 1);
2028 bool haveGamepadButtons = device->keyBitmask.any(BTN_MISC, BTN_MOUSE) ||
2029 device->keyBitmask.any(BTN_JOYSTICK, BTN_DIGI);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002030 if (haveKeyboardKeys || haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002031 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002032 }
2033
2034 // See if this is a cursor device such as a trackball or mouse.
Chris Ye66fbac32020-07-06 20:36:43 -07002035 if (device->keyBitmask.test(BTN_MOUSE) && device->relBitmask.test(REL_X) &&
2036 device->relBitmask.test(REL_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002037 device->classes |= InputDeviceClass::CURSOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002038 }
2039
Prashant Malani1941ff52015-08-11 18:29:28 -07002040 // See if this is a rotary encoder type device.
2041 String8 deviceType = String8();
2042 if (device->configuration &&
2043 device->configuration->tryGetProperty(String8("device.type"), deviceType)) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002044 if (!deviceType.compare(String8("rotaryEncoder"))) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002045 device->classes |= InputDeviceClass::ROTARY_ENCODER;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002046 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002047 }
2048
Michael Wrightd02c5b62014-02-10 15:10:22 -08002049 // See if this is a touch pad.
2050 // Is this a new modern multi-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002051 if (device->absBitmask.test(ABS_MT_POSITION_X) && device->absBitmask.test(ABS_MT_POSITION_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002052 // Some joysticks such as the PS3 controller report axes that conflict
2053 // with the ABS_MT range. Try to confirm that the device really is
2054 // a touch screen.
Chris Ye66fbac32020-07-06 20:36:43 -07002055 if (device->keyBitmask.test(BTN_TOUCH) || !haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002056 device->classes |= (InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002057 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002058 // Is this an old style single-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002059 } else if (device->keyBitmask.test(BTN_TOUCH) && device->absBitmask.test(ABS_X) &&
2060 device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002061 device->classes |= InputDeviceClass::TOUCH;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002062 // Is this a BT stylus?
Chris Ye66fbac32020-07-06 20:36:43 -07002063 } else if ((device->absBitmask.test(ABS_PRESSURE) || device->keyBitmask.test(BTN_TOUCH)) &&
2064 !device->absBitmask.test(ABS_X) && !device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002065 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -07002066 // Keyboard will try to claim some of the buttons but we really want to reserve those so we
2067 // can fuse it with the touch screen data, so just take them back. Note this means an
2068 // external stylus cannot also be a keyboard device.
Chris Ye1b0c7342020-07-28 21:57:03 -07002069 device->classes &= ~InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002070 }
2071
2072 // See if this device is a joystick.
2073 // Assumes that joysticks always have gamepad buttons in order to distinguish them
2074 // from other devices such as accelerometers that also have absolute axes.
2075 if (haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002076 auto assumedClasses = device->classes | InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002077 for (int i = 0; i <= ABS_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002078 if (device->absBitmask.test(i) &&
Chris Ye1b0c7342020-07-28 21:57:03 -07002079 (getAbsAxisUsage(i, assumedClasses).test(InputDeviceClass::JOYSTICK))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002080 device->classes = assumedClasses;
2081 break;
2082 }
2083 }
2084 }
2085
Chris Yef59a2f42020-10-16 12:55:26 -07002086 // Check whether this device is an accelerometer.
2087 if (device->propBitmask.test(INPUT_PROP_ACCELEROMETER)) {
2088 device->classes |= InputDeviceClass::SENSOR;
2089 }
2090
Michael Wrightd02c5b62014-02-10 15:10:22 -08002091 // Check whether this device has switches.
2092 for (int i = 0; i <= SW_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002093 if (device->swBitmask.test(i)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002094 device->classes |= InputDeviceClass::SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002095 break;
2096 }
2097 }
2098
2099 // Check whether this device supports the vibrator.
Chris Ye66fbac32020-07-06 20:36:43 -07002100 if (device->ffBitmask.test(FF_RUMBLE)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002101 device->classes |= InputDeviceClass::VIBRATOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002102 }
2103
2104 // Configure virtual keys.
Chris Ye1b0c7342020-07-28 21:57:03 -07002105 if ((device->classes.test(InputDeviceClass::TOUCH))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002106 // Load the virtual keys for the touch screen, if any.
2107 // We do this now so that we can make sure to load the keymap if necessary.
Chris Ye989bb932020-07-04 16:18:59 -07002108 bool success = device->loadVirtualKeyMapLocked();
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06002109 if (success) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002110 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002111 }
2112 }
2113
2114 // Load the key map.
Chris Yef59a2f42020-10-16 12:55:26 -07002115 // We need to do this for joysticks too because the key layout may specify axes, and for
2116 // sensor as well because the key layout may specify the axes to sensor data mapping.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002117 status_t keyMapStatus = NAME_NOT_FOUND;
Chris Yef59a2f42020-10-16 12:55:26 -07002118 if (device->classes.any(InputDeviceClass::KEYBOARD | InputDeviceClass::JOYSTICK |
2119 InputDeviceClass::SENSOR)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002120 // Load the keymap for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002121 keyMapStatus = device->loadKeyMapLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002122 }
2123
2124 // Configure the keyboard, gamepad or virtual keyboard.
Chris Ye1b0c7342020-07-28 21:57:03 -07002125 if (device->classes.test(InputDeviceClass::KEYBOARD)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002126 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002127 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002128 isEligibleBuiltInKeyboard(device->identifier, device->configuration.get(),
2129 &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002130 mBuiltInKeyboardId = device->id;
2131 }
2132
2133 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
Chris Ye989bb932020-07-04 16:18:59 -07002134 if (device->hasKeycodeLocked(AKEYCODE_Q)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002135 device->classes |= InputDeviceClass::ALPHAKEY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002136 }
2137
2138 // See if this device has a DPAD.
Chris Ye989bb932020-07-04 16:18:59 -07002139 if (device->hasKeycodeLocked(AKEYCODE_DPAD_UP) &&
2140 device->hasKeycodeLocked(AKEYCODE_DPAD_DOWN) &&
2141 device->hasKeycodeLocked(AKEYCODE_DPAD_LEFT) &&
2142 device->hasKeycodeLocked(AKEYCODE_DPAD_RIGHT) &&
2143 device->hasKeycodeLocked(AKEYCODE_DPAD_CENTER)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002144 device->classes |= InputDeviceClass::DPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002145 }
2146
2147 // See if this device has a gamepad.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002148 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES) / sizeof(GAMEPAD_KEYCODES[0]); i++) {
Chris Ye989bb932020-07-04 16:18:59 -07002149 if (device->hasKeycodeLocked(GAMEPAD_KEYCODES[i])) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002150 device->classes |= InputDeviceClass::GAMEPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002151 break;
2152 }
2153 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002154 }
2155
2156 // If the device isn't recognized as something we handle, don't monitor it.
Chris Ye1b0c7342020-07-28 21:57:03 -07002157 if (device->classes == Flags<InputDeviceClass>(0)) {
Chris Ye8594e192020-07-14 10:34:06 -07002158 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002159 device->identifier.name.c_str());
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002160 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002161 }
2162
Chris Ye3fdbfef2021-01-06 18:45:18 -08002163 // Classify InputDeviceClass::BATTERY.
2164 if (hasBattery) {
2165 device->classes |= InputDeviceClass::BATTERY;
2166 }
Kim Low03ea0352020-11-06 12:45:07 -08002167
Chris Ye3fdbfef2021-01-06 18:45:18 -08002168 // Classify InputDeviceClass::LIGHT.
2169 if (hasLights) {
2170 device->classes |= InputDeviceClass::LIGHT;
Kim Low03ea0352020-11-06 12:45:07 -08002171 }
2172
Tim Kilbourn063ff532015-04-08 10:26:18 -07002173 // Determine whether the device has a mic.
Chris Ye989bb932020-07-04 16:18:59 -07002174 if (device->deviceHasMicLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002175 device->classes |= InputDeviceClass::MIC;
Tim Kilbourn063ff532015-04-08 10:26:18 -07002176 }
2177
Michael Wrightd02c5b62014-02-10 15:10:22 -08002178 // Determine whether the device is external or internal.
Chris Ye989bb932020-07-04 16:18:59 -07002179 if (device->isExternalDeviceLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002180 device->classes |= InputDeviceClass::EXTERNAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002181 }
2182
Chris Ye1b0c7342020-07-28 21:57:03 -07002183 if (device->classes.any(InputDeviceClass::JOYSTICK | InputDeviceClass::DPAD) &&
2184 device->classes.test(InputDeviceClass::GAMEPAD)) {
Chris Ye989bb932020-07-04 16:18:59 -07002185 device->controllerNumber = getNextControllerNumberLocked(device->identifier.name);
2186 device->setLedForControllerLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002187 }
2188
Chris Ye989bb932020-07-04 16:18:59 -07002189 if (registerDeviceForEpollLocked(*device) != OK) {
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002190 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002191 }
2192
Chris Ye989bb932020-07-04 16:18:59 -07002193 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002194
Chris Ye1b0c7342020-07-28 21:57:03 -07002195 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=%s, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002196 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Chris Ye1b0c7342020-07-28 21:57:03 -07002197 deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(),
2198 device->classes.string().c_str(), device->configurationFile.c_str(),
2199 device->keyMap.keyLayoutFile.c_str(), device->keyMap.keyCharacterMapFile.c_str(),
2200 toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002201
Chris Ye989bb932020-07-04 16:18:59 -07002202 addDeviceLocked(std::move(device));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002203}
2204
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002205void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
2206 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
2207 if (!videoDevice) {
2208 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
2209 return;
2210 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002211 // Transfer ownership of this video device to a matching input device
Chris Ye989bb932020-07-04 16:18:59 -07002212 for (const auto& [id, device] : mDevices) {
Chris Yed3fef462021-03-07 17:10:08 -08002213 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002214 return; // 'device' now owns 'videoDevice'
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002215 }
2216 }
2217
2218 // Couldn't find a matching input device, so just add it to a temporary holding queue.
2219 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002220 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002221 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002222 mUnattachedVideoDevices.push_back(std::move(videoDevice));
2223}
2224
Chris Yed3fef462021-03-07 17:10:08 -08002225bool EventHub::tryAddVideoDeviceLocked(EventHub::Device& device,
2226 std::unique_ptr<TouchVideoDevice>& videoDevice) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002227 if (videoDevice->getName() != device.identifier.name) {
2228 return false;
2229 }
2230 device.videoDevice = std::move(videoDevice);
2231 if (device.enabled) {
2232 registerVideoDeviceForEpollLocked(*device.videoDevice);
2233 }
2234 return true;
2235}
2236
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002237bool EventHub::isDeviceEnabled(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002238 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002239 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002240 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002241 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2242 return false;
2243 }
2244 return device->enabled;
2245}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002246
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002247status_t EventHub::enableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002248 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002249 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002250 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002251 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2252 return BAD_VALUE;
2253 }
2254 if (device->enabled) {
2255 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
2256 return OK;
2257 }
2258 status_t result = device->enable();
2259 if (result != OK) {
2260 ALOGE("Failed to enable device %" PRId32, deviceId);
2261 return result;
2262 }
2263
Chris Ye989bb932020-07-04 16:18:59 -07002264 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002265
Chris Ye989bb932020-07-04 16:18:59 -07002266 return registerDeviceForEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002267}
2268
2269status_t EventHub::disableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002270 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002271 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002272 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002273 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2274 return BAD_VALUE;
2275 }
2276 if (!device->enabled) {
2277 ALOGW("Duplicate call to %s, input device already disabled", __func__);
2278 return OK;
2279 }
Chris Ye989bb932020-07-04 16:18:59 -07002280 unregisterDeviceFromEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002281 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002282}
2283
2284void EventHub::createVirtualKeyboardLocked() {
2285 InputDeviceIdentifier identifier;
2286 identifier.name = "Virtual";
2287 identifier.uniqueId = "<virtual>";
2288 assignDescriptorLocked(identifier);
2289
Chris Ye989bb932020-07-04 16:18:59 -07002290 std::unique_ptr<Device> device =
2291 std::make_unique<Device>(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
2292 identifier);
Chris Ye1b0c7342020-07-28 21:57:03 -07002293 device->classes = InputDeviceClass::KEYBOARD | InputDeviceClass::ALPHAKEY |
2294 InputDeviceClass::DPAD | InputDeviceClass::VIRTUAL;
Chris Ye989bb932020-07-04 16:18:59 -07002295 device->loadKeyMapLocked();
2296 addDeviceLocked(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002297}
2298
Chris Ye989bb932020-07-04 16:18:59 -07002299void EventHub::addDeviceLocked(std::unique_ptr<Device> device) {
Chris Yed3fef462021-03-07 17:10:08 -08002300 reportDeviceAddedForStatisticsLocked(device->identifier, device->classes);
Chris Ye989bb932020-07-04 16:18:59 -07002301 mOpeningDevices.push_back(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002302}
2303
Chris Ye989bb932020-07-04 16:18:59 -07002304int32_t EventHub::getNextControllerNumberLocked(const std::string& name) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002305 if (mControllerNumbers.isFull()) {
2306 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Chris Ye989bb932020-07-04 16:18:59 -07002307 name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002308 return 0;
2309 }
2310 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
2311 // one
2312 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
2313}
2314
Chris Ye989bb932020-07-04 16:18:59 -07002315void EventHub::releaseControllerNumberLocked(int32_t num) {
2316 if (num > 0) {
2317 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002318 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002319}
2320
Chris Ye8594e192020-07-14 10:34:06 -07002321void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002322 Device* device = getDeviceByPathLocked(devicePath);
Chris Ye989bb932020-07-04 16:18:59 -07002323 if (device != nullptr) {
2324 closeDeviceLocked(*device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002325 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002326 }
Chris Ye8594e192020-07-14 10:34:06 -07002327 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002328}
2329
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002330/**
2331 * Find the video device by filename, and close it.
2332 * The video device is closed by path during an inotify event, where we don't have the
2333 * additional context about the video device fd, or the associated input device.
2334 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002335void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002336 // A video device may be owned by an existing input device, or it may be stored in
2337 // the mUnattachedVideoDevices queue. Check both locations.
Chris Ye989bb932020-07-04 16:18:59 -07002338 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002339 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002340 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002341 device->videoDevice = nullptr;
2342 return;
2343 }
2344 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002345 mUnattachedVideoDevices
2346 .erase(std::remove_if(mUnattachedVideoDevices.begin(), mUnattachedVideoDevices.end(),
2347 [&devicePath](
2348 const std::unique_ptr<TouchVideoDevice>& videoDevice) {
2349 return videoDevice->getPath() == devicePath;
2350 }),
2351 mUnattachedVideoDevices.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002352}
2353
2354void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002355 mUnattachedVideoDevices.clear();
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002356 while (!mDevices.empty()) {
2357 closeDeviceLocked(*(mDevices.begin()->second));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002358 }
2359}
2360
Chris Ye989bb932020-07-04 16:18:59 -07002361void EventHub::closeDeviceLocked(Device& device) {
2362 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=%s", device.path.c_str(),
2363 device.identifier.name.c_str(), device.id, device.fd, device.classes.string().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002364
Chris Ye989bb932020-07-04 16:18:59 -07002365 if (device.id == mBuiltInKeyboardId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002366 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Chris Ye989bb932020-07-04 16:18:59 -07002367 device.path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002368 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
2369 }
2370
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002371 unregisterDeviceFromEpollLocked(device);
Chris Ye989bb932020-07-04 16:18:59 -07002372 if (device.videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002373 // This must be done after the video device is removed from epoll
Chris Ye989bb932020-07-04 16:18:59 -07002374 mUnattachedVideoDevices.push_back(std::move(device.videoDevice));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002375 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002376
Chris Ye989bb932020-07-04 16:18:59 -07002377 releaseControllerNumberLocked(device.controllerNumber);
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002378 device.controllerNumber = 0;
Chris Ye989bb932020-07-04 16:18:59 -07002379 device.close();
Chris Ye989bb932020-07-04 16:18:59 -07002380 mClosingDevices.push_back(std::move(mDevices[device.id]));
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002381
Chris Ye989bb932020-07-04 16:18:59 -07002382 mDevices.erase(device.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002383}
2384
2385status_t EventHub::readNotifyLocked() {
2386 int res;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002387 char event_buf[512];
2388 int event_size;
2389 int event_pos = 0;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002390 struct inotify_event* event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002391
2392 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
2393 res = read(mINotifyFd, event_buf, sizeof(event_buf));
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002394 if (res < (int)sizeof(*event)) {
2395 if (errno == EINTR) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002396 ALOGW("could not get event, %s\n", strerror(errno));
2397 return -1;
2398 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002399
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002400 while (res >= (int)sizeof(*event)) {
2401 event = (struct inotify_event*)(event_buf + event_pos);
2402 if (event->len) {
Usama Arif78eb9752021-06-03 16:44:09 +01002403 if (event->wd == mDeviceInputWd) {
2404 std::string filename = std::string(DEVICE_INPUT_PATH) + "/" + event->name;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002405 if (event->mask & IN_CREATE) {
Chris Ye8594e192020-07-14 10:34:06 -07002406 openDeviceLocked(filename);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08002407 } else {
2408 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
Chris Ye8594e192020-07-14 10:34:06 -07002409 closeDeviceByPathLocked(filename);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08002410 }
Usama Arif78eb9752021-06-03 16:44:09 +01002411 } else if (event->wd == mDeviceWd) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08002412 if (isV4lTouchNode(event->name)) {
Usama Arif78eb9752021-06-03 16:44:09 +01002413 std::string filename = std::string(DEVICE_PATH) + "/" + event->name;
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002414 if (event->mask & IN_CREATE) {
2415 openVideoDeviceLocked(filename);
2416 } else {
2417 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
2418 closeVideoDeviceByPathLocked(filename);
2419 }
Usama Arif78eb9752021-06-03 16:44:09 +01002420 } else if (strcmp(event->name, "input") == 0 && event->mask & IN_CREATE) {
2421 addDeviceInputInotify();
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08002422 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002423 } else {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08002424 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event->wd);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002425 }
2426 }
2427 event_size = sizeof(*event) + event->len;
2428 res -= event_size;
2429 event_pos += event_size;
2430 }
2431 return 0;
2432}
2433
Chris Ye8594e192020-07-14 10:34:06 -07002434status_t EventHub::scanDirLocked(const std::string& dirname) {
2435 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2436 openDeviceLocked(entry.path());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002437 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002438 return 0;
2439}
2440
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002441/**
2442 * Look for all dirname/v4l-touch* devices, and open them.
2443 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002444status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Chris Ye8594e192020-07-14 10:34:06 -07002445 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2446 if (isV4lTouchNode(entry.path())) {
2447 ALOGI("Found touch video device %s", entry.path().c_str());
2448 openVideoDeviceLocked(entry.path());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002449 }
2450 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002451 return OK;
2452}
2453
Michael Wrightd02c5b62014-02-10 15:10:22 -08002454void EventHub::requestReopenDevices() {
2455 ALOGV("requestReopenDevices() called");
2456
Chris Ye87143712020-11-10 05:05:58 +00002457 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002458 mNeedToReopenDevices = true;
2459}
2460
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002461void EventHub::dump(std::string& dump) {
2462 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002463
2464 { // acquire lock
Chris Ye87143712020-11-10 05:05:58 +00002465 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002466
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002467 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002468
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002469 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002470
Chris Ye989bb932020-07-04 16:18:59 -07002471 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002472 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002473 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002474 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002475 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002476 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002477 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002478 }
Chris Ye1b0c7342020-07-28 21:57:03 -07002479 dump += StringPrintf(INDENT3 "Classes: %s\n", device->classes.string().c_str());
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002480 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002481 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002482 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
2483 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002484 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002485 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002486 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002487 "product=0x%04x, version=0x%04x\n",
2488 device->identifier.bus, device->identifier.vendor,
2489 device->identifier.product, device->identifier.version);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002490 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002491 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002492 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002493 device->keyMap.keyCharacterMapFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002494 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002495 device->configurationFile.c_str());
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002496 dump += INDENT3 "VideoDevice: ";
2497 if (device->videoDevice) {
2498 dump += device->videoDevice->dump() + "\n";
2499 } else {
2500 dump += "<none>\n";
2501 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002502 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002503
2504 dump += INDENT "Unattached video devices:\n";
2505 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
2506 dump += INDENT2 + videoDevice->dump() + "\n";
2507 }
2508 if (mUnattachedVideoDevices.empty()) {
2509 dump += INDENT2 "<none>\n";
2510 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002511 } // release lock
2512}
2513
2514void EventHub::monitor() {
2515 // Acquire and release the lock to ensure that the event hub has not deadlocked.
Chris Ye1c2e0892020-11-30 21:41:44 -08002516 std::unique_lock<std::mutex> lock(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002517}
2518
Michael Wrightd02c5b62014-02-10 15:10:22 -08002519}; // namespace android