blob: ee8dde1d3248108e9b3eef57a0993c9a1f0aa400 [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>
Colin Cross5b799302022-10-18 21:52:41 -070022#include <linux/ioctl.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070023#include <memory.h>
24#include <stdint.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +010028#include <sys/capability.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070029#include <sys/epoll.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070030#include <sys/inotify.h>
31#include <sys/ioctl.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>
Dominik Laskowski75788452021-02-09 18:51:25 -080043#include <ftl/enum.h>
Chris Ye8594e192020-07-14 10:34:06 -070044#include <input/KeyCharacterMap.h>
45#include <input/KeyLayoutMap.h>
Prabir Pradhan07525ef2022-10-03 21:51:26 +000046#include <input/PrintTools.h>
Chris Ye8594e192020-07-14 10:34:06 -070047#include <input/VirtualKeyMap.h>
Dan Albert677d87e2014-06-16 17:31:28 -070048#include <openssl/sha.h>
Chris Yed3fef462021-03-07 17:10:08 -080049#include <statslog.h>
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070050#include <utils/Errors.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080051#include <utils/Log.h>
52#include <utils/Timers.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080053
Chris Ye8594e192020-07-14 10:34:06 -070054#include <filesystem>
Harry Cuttsf13161a2023-03-08 14:15:49 +000055#include <optional>
Chris Ye3fdbfef2021-01-06 18:45:18 -080056#include <regex>
Prabir Pradhancb42b472022-08-23 16:01:19 +000057#include <utility>
Chris Ye8594e192020-07-14 10:34:06 -070058
59#include "EventHub.h"
Michael Wrightd02c5b62014-02-10 15:10:22 -080060
Michael Wrightd02c5b62014-02-10 15:10:22 -080061#define INDENT " "
62#define INDENT2 " "
63#define INDENT3 " "
64
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080065using android::base::StringPrintf;
66
Michael Wrightd02c5b62014-02-10 15:10:22 -080067namespace android {
68
Dominik Laskowski2f01d772022-03-23 16:01:29 -070069using namespace ftl::flag_operators;
70
Usama Arifb27c8e62021-06-03 16:44:09 +010071static const char* DEVICE_INPUT_PATH = "/dev/input";
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080072// v4l2 devices go directly into /dev
Usama Arifb27c8e62021-06-03 16:44:09 +010073static const char* DEVICE_PATH = "/dev";
Michael Wrightd02c5b62014-02-10 15:10:22 -080074
Chris Ye657c2f02021-05-25 16:24:37 -070075static constexpr size_t OBFUSCATED_LENGTH = 8;
76
Chris Ye87143712020-11-10 05:05:58 +000077static constexpr int32_t FF_STRONG_MAGNITUDE_CHANNEL_IDX = 0;
78static constexpr int32_t FF_WEAK_MAGNITUDE_CHANNEL_IDX = 1;
Chris Ye6393a262020-08-04 19:41:36 -070079
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -070080static constexpr size_t EVENT_BUFFER_SIZE = 256;
81
Chris Yee2b1e5c2021-03-10 22:45:12 -080082// Mapping for input battery class node IDs lookup.
83// https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
84static const std::unordered_map<std::string, InputBatteryClass> BATTERY_CLASSES =
85 {{"capacity", InputBatteryClass::CAPACITY},
86 {"capacity_level", InputBatteryClass::CAPACITY_LEVEL},
87 {"status", InputBatteryClass::STATUS}};
88
89// Mapping for input battery class node names lookup.
90// https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
91static const std::unordered_map<InputBatteryClass, std::string> BATTERY_NODES =
92 {{InputBatteryClass::CAPACITY, "capacity"},
93 {InputBatteryClass::CAPACITY_LEVEL, "capacity_level"},
94 {InputBatteryClass::STATUS, "status"}};
95
Kim Low03ea0352020-11-06 12:45:07 -080096// must be kept in sync with definitions in kernel /drivers/power/supply/power_supply_sysfs.c
97static const std::unordered_map<std::string, int32_t> BATTERY_STATUS =
98 {{"Unknown", BATTERY_STATUS_UNKNOWN},
99 {"Charging", BATTERY_STATUS_CHARGING},
100 {"Discharging", BATTERY_STATUS_DISCHARGING},
101 {"Not charging", BATTERY_STATUS_NOT_CHARGING},
102 {"Full", BATTERY_STATUS_FULL}};
103
104// Mapping taken from
105// https://gitlab.freedesktop.org/upower/upower/-/blob/master/src/linux/up-device-supply.c#L484
106static const std::unordered_map<std::string, int32_t> BATTERY_LEVEL = {{"Critical", 5},
107 {"Low", 10},
108 {"Normal", 55},
109 {"High", 70},
110 {"Full", 100},
111 {"Unknown", 50}};
112
Chris Ye3fdbfef2021-01-06 18:45:18 -0800113// Mapping for input led class node names lookup.
114// https://www.kernel.org/doc/html/latest/leds/leds-class.html
115static const std::unordered_map<std::string, InputLightClass> LIGHT_CLASSES =
116 {{"red", InputLightClass::RED},
117 {"green", InputLightClass::GREEN},
118 {"blue", InputLightClass::BLUE},
119 {"global", InputLightClass::GLOBAL},
120 {"brightness", InputLightClass::BRIGHTNESS},
121 {"multi_index", InputLightClass::MULTI_INDEX},
122 {"multi_intensity", InputLightClass::MULTI_INTENSITY},
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000123 {"max_brightness", InputLightClass::MAX_BRIGHTNESS},
124 {"kbd_backlight", InputLightClass::KEYBOARD_BACKLIGHT}};
Chris Ye3fdbfef2021-01-06 18:45:18 -0800125
126// Mapping for input multicolor led class node names.
127// https://www.kernel.org/doc/html/latest/leds/leds-class-multicolor.html
128static const std::unordered_map<InputLightClass, std::string> LIGHT_NODES =
129 {{InputLightClass::BRIGHTNESS, "brightness"},
130 {InputLightClass::MULTI_INDEX, "multi_index"},
131 {InputLightClass::MULTI_INTENSITY, "multi_intensity"}};
132
133// Mapping for light color name and the light color
134const std::unordered_map<std::string, LightColor> LIGHT_COLORS = {{"red", LightColor::RED},
135 {"green", LightColor::GREEN},
136 {"blue", LightColor::BLUE}};
137
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000138// Mapping for country code to Layout info.
139// See bCountryCode in 6.2.1 of https://usb.org/sites/default/files/hid1_11.pdf.
140const std::unordered_map<std::int32_t, RawLayoutInfo> LAYOUT_INFOS =
141 {{0, RawLayoutInfo{.languageTag = "", .layoutType = ""}}, // NOT_SUPPORTED
142 {1, RawLayoutInfo{.languageTag = "ar-Arab", .layoutType = ""}}, // ARABIC
143 {2, RawLayoutInfo{.languageTag = "fr-BE", .layoutType = ""}}, // BELGIAN
144 {3, RawLayoutInfo{.languageTag = "fr-CA", .layoutType = ""}}, // CANADIAN_BILINGUAL
145 {4, RawLayoutInfo{.languageTag = "fr-CA", .layoutType = ""}}, // CANADIAN_FRENCH
146 {5, RawLayoutInfo{.languageTag = "cs", .layoutType = ""}}, // CZECH_REPUBLIC
147 {6, RawLayoutInfo{.languageTag = "da", .layoutType = ""}}, // DANISH
148 {7, RawLayoutInfo{.languageTag = "fi", .layoutType = ""}}, // FINNISH
149 {8, RawLayoutInfo{.languageTag = "fr-FR", .layoutType = ""}}, // FRENCH
150 {9, RawLayoutInfo{.languageTag = "de", .layoutType = ""}}, // GERMAN
151 {10, RawLayoutInfo{.languageTag = "el", .layoutType = ""}}, // GREEK
152 {11, RawLayoutInfo{.languageTag = "iw", .layoutType = ""}}, // HEBREW
153 {12, RawLayoutInfo{.languageTag = "hu", .layoutType = ""}}, // HUNGARY
154 {13, RawLayoutInfo{.languageTag = "en", .layoutType = "extended"}}, // INTERNATIONAL (ISO)
155 {14, RawLayoutInfo{.languageTag = "it", .layoutType = ""}}, // ITALIAN
156 {15, RawLayoutInfo{.languageTag = "ja", .layoutType = ""}}, // JAPAN
157 {16, RawLayoutInfo{.languageTag = "ko", .layoutType = ""}}, // KOREAN
158 {17, RawLayoutInfo{.languageTag = "es-419", .layoutType = ""}}, // LATIN_AMERICA
159 {18, RawLayoutInfo{.languageTag = "nl", .layoutType = ""}}, // DUTCH
160 {19, RawLayoutInfo{.languageTag = "nb", .layoutType = ""}}, // NORWEGIAN
161 {20, RawLayoutInfo{.languageTag = "fa", .layoutType = ""}}, // PERSIAN
162 {21, RawLayoutInfo{.languageTag = "pl", .layoutType = ""}}, // POLAND
163 {22, RawLayoutInfo{.languageTag = "pt", .layoutType = ""}}, // PORTUGUESE
164 {23, RawLayoutInfo{.languageTag = "ru", .layoutType = ""}}, // RUSSIA
165 {24, RawLayoutInfo{.languageTag = "sk", .layoutType = ""}}, // SLOVAKIA
166 {25, RawLayoutInfo{.languageTag = "es-ES", .layoutType = ""}}, // SPANISH
167 {26, RawLayoutInfo{.languageTag = "sv", .layoutType = ""}}, // SWEDISH
168 {27, RawLayoutInfo{.languageTag = "fr-CH", .layoutType = ""}}, // SWISS_FRENCH
169 {28, RawLayoutInfo{.languageTag = "de-CH", .layoutType = ""}}, // SWISS_GERMAN
170 {29, RawLayoutInfo{.languageTag = "de-CH", .layoutType = ""}}, // SWITZERLAND
171 {30, RawLayoutInfo{.languageTag = "zh-TW", .layoutType = ""}}, // TAIWAN
172 {31, RawLayoutInfo{.languageTag = "tr", .layoutType = "turkish_q"}}, // TURKISH_Q
173 {32, RawLayoutInfo{.languageTag = "en-GB", .layoutType = ""}}, // UK
174 {33, RawLayoutInfo{.languageTag = "en-US", .layoutType = ""}}, // US
175 {34, RawLayoutInfo{.languageTag = "", .layoutType = ""}}, // YUGOSLAVIA
176 {35, RawLayoutInfo{.languageTag = "tr", .layoutType = "turkish_f"}}}; // TURKISH_F
177
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100178static std::string sha1(const std::string& in) {
Dan Albert677d87e2014-06-16 17:31:28 -0700179 SHA_CTX ctx;
180 SHA1_Init(&ctx);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100181 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
Dan Albert677d87e2014-06-16 17:31:28 -0700182 u_char digest[SHA_DIGEST_LENGTH];
183 SHA1_Final(digest, &ctx);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800184
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100185 std::string out;
Dan Albert677d87e2014-06-16 17:31:28 -0700186 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100187 out += StringPrintf("%02x", digest[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800188 }
189 return out;
190}
191
Prabir Pradhana3621852022-10-14 18:57:23 +0000192/* The set of all Android key codes that correspond to buttons (bit-switches) on a stylus. */
193static constexpr std::array<int32_t, 4> STYLUS_BUTTON_KEYCODES = {
194 AKEYCODE_STYLUS_BUTTON_PRIMARY,
195 AKEYCODE_STYLUS_BUTTON_SECONDARY,
196 AKEYCODE_STYLUS_BUTTON_TERTIARY,
197 AKEYCODE_STYLUS_BUTTON_TAIL,
198};
199
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800200/**
201 * Return true if name matches "v4l-touch*"
202 */
Chris Ye8594e192020-07-14 10:34:06 -0700203static bool isV4lTouchNode(std::string name) {
204 return name.find("v4l-touch") != std::string::npos;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800205}
206
Philip Quinn39b81682019-01-09 22:20:39 -0800207/**
208 * Returns true if V4L devices should be scanned.
209 *
210 * The system property ro.input.video_enabled can be used to control whether
211 * EventHub scans and opens V4L devices. As V4L does not support multiple
212 * clients, EventHub effectively blocks access to these devices when it opens
Siarhei Vishniakou29f88492019-04-05 14:11:43 -0700213 * them.
214 *
215 * Setting this to "false" would prevent any video devices from being discovered and
216 * associated with input devices.
217 *
218 * This property can be used as follows:
219 * 1. To turn off features that are dependent on video device presence.
220 * 2. During testing and development, to allow other clients to read video devices
221 * directly from /dev.
Philip Quinn39b81682019-01-09 22:20:39 -0800222 */
223static bool isV4lScanningEnabled() {
Harry Cutts33476232023-01-30 19:57:29 +0000224 return property_get_bool("ro.input.video_enabled", /*default_value=*/true);
Philip Quinn39b81682019-01-09 22:20:39 -0800225}
226
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800227static nsecs_t processEventTimestamp(const struct input_event& event) {
228 // Use the time specified in the event instead of the current time
229 // so that downstream code can get more accurate estimates of
230 // event dispatch latency from the time the event is enqueued onto
231 // the evdev client buffer.
232 //
233 // The event's timestamp fortuitously uses the same monotonic clock
234 // time base as the rest of Android. The kernel event device driver
235 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
236 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
237 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
238 // system call that also queries ktime_get_ts().
239
Colin Cross5b799302022-10-18 21:52:41 -0700240 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.input_event_sec) +
241 microseconds_to_nanoseconds(event.input_event_usec);
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800242 return inputEventTime;
243}
244
Kim Low03ea0352020-11-06 12:45:07 -0800245/**
Prabir Pradhancb42b472022-08-23 16:01:19 +0000246 * Returns the sysfs root path of the input device.
Kim Low03ea0352020-11-06 12:45:07 -0800247 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800248static std::optional<std::filesystem::path> getSysfsRootPath(const char* devicePath) {
Kim Low03ea0352020-11-06 12:45:07 -0800249 std::error_code errorCode;
250
251 // Stat the device path to get the major and minor number of the character file
252 struct stat statbuf;
253 if (stat(devicePath, &statbuf) == -1) {
254 ALOGE("Could not stat device %s due to error: %s.", devicePath, std::strerror(errno));
Chris Ye3fdbfef2021-01-06 18:45:18 -0800255 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800256 }
257
258 unsigned int major_num = major(statbuf.st_rdev);
259 unsigned int minor_num = minor(statbuf.st_rdev);
260
261 // Realpath "/sys/dev/char/{major}:{minor}" to get the sysfs path to the input event
262 auto sysfsPath = std::filesystem::path("/sys/dev/char/");
263 sysfsPath /= std::to_string(major_num) + ":" + std::to_string(minor_num);
264 sysfsPath = std::filesystem::canonical(sysfsPath, errorCode);
265
266 // Make sure nothing went wrong in call to canonical()
267 if (errorCode) {
268 ALOGW("Could not run filesystem::canonical() due to error %d : %s.", errorCode.value(),
269 errorCode.message().c_str());
Chris Ye3fdbfef2021-01-06 18:45:18 -0800270 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800271 }
272
273 // Continue to go up a directory until we reach a directory named "input"
274 while (sysfsPath != "/" && sysfsPath.filename() != "input") {
275 sysfsPath = sysfsPath.parent_path();
276 }
277
278 // Then go up one more and you will be at the sysfs root of the device
279 sysfsPath = sysfsPath.parent_path();
280
281 // Make sure we didn't reach root path and that directory actually exists
282 if (sysfsPath == "/" || !std::filesystem::exists(sysfsPath, errorCode)) {
283 if (errorCode) {
284 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
285 errorCode.message().c_str());
286 }
287
288 // Not found
Chris Ye3fdbfef2021-01-06 18:45:18 -0800289 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800290 }
291
292 return sysfsPath;
293}
294
295/**
Chris Ye3fdbfef2021-01-06 18:45:18 -0800296 * Returns the list of files under a specified path.
Kim Low03ea0352020-11-06 12:45:07 -0800297 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800298static std::vector<std::filesystem::path> allFilesInPath(const std::filesystem::path& path) {
299 std::vector<std::filesystem::path> nodes;
300 std::error_code errorCode;
301 auto iter = std::filesystem::directory_iterator(path, errorCode);
302 while (!errorCode && iter != std::filesystem::directory_iterator()) {
303 nodes.push_back(iter->path());
304 iter++;
305 }
306 return nodes;
307}
308
309/**
310 * Returns the list of files under a specified directory in a sysfs path.
311 * Example:
312 * findSysfsNodes(sysfsRootPath, SysfsClass::LEDS) will return all led nodes under "leds" directory
313 * in the sysfs path.
314 */
315static std::vector<std::filesystem::path> findSysfsNodes(const std::filesystem::path& sysfsRoot,
316 SysfsClass clazz) {
Dominik Laskowski75788452021-02-09 18:51:25 -0800317 std::string nodeStr = ftl::enum_string(clazz);
Chris Ye3fdbfef2021-01-06 18:45:18 -0800318 std::for_each(nodeStr.begin(), nodeStr.end(),
319 [](char& c) { c = std::tolower(static_cast<unsigned char>(c)); });
320 std::vector<std::filesystem::path> nodes;
321 for (auto path = sysfsRoot; path != "/" && nodes.empty(); path = path.parent_path()) {
322 nodes = allFilesInPath(path / nodeStr);
323 }
324 return nodes;
325}
326
327static std::optional<std::array<LightColor, COLOR_NUM>> getColorIndexArray(
328 std::filesystem::path path) {
329 std::string indexStr;
330 if (!base::ReadFileToString(path, &indexStr)) {
331 return std::nullopt;
332 }
333
334 // Parse the multi color LED index file, refer to kernel docs
335 // leds/leds-class-multicolor.html
336 std::regex indexPattern("(red|green|blue)\\s(red|green|blue)\\s(red|green|blue)[\\n]");
337 std::smatch results;
338 std::array<LightColor, COLOR_NUM> colors;
339 if (!std::regex_match(indexStr, results, indexPattern)) {
340 return std::nullopt;
341 }
342
343 for (size_t i = 1; i < results.size(); i++) {
344 const auto it = LIGHT_COLORS.find(results[i].str());
345 if (it != LIGHT_COLORS.end()) {
346 // intensities.emplace(it->second, 0);
347 colors[i - 1] = it->second;
Kim Low03ea0352020-11-06 12:45:07 -0800348 }
349 }
Chris Ye3fdbfef2021-01-06 18:45:18 -0800350 return colors;
Kim Low03ea0352020-11-06 12:45:07 -0800351}
352
Prabir Pradhancb42b472022-08-23 16:01:19 +0000353/**
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000354 * Read country code information exposed through the sysfs path and convert it to Layout info.
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000355 */
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000356static std::optional<RawLayoutInfo> readLayoutConfiguration(
357 const std::filesystem::path& sysfsRootPath) {
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000358 // Check the sysfs root path
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000359 int32_t hidCountryCode = -1;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000360 std::string str;
361 if (base::ReadFileToString(sysfsRootPath / "country", &str)) {
362 hidCountryCode = std::stoi(str, nullptr, 16);
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000363 // Update this condition if new supported country codes are added to HID spec.
Vaibhav Devmurari990ff7b2022-12-22 18:23:21 +0000364 if (hidCountryCode > 35 || hidCountryCode < 0) {
365 ALOGE("HID country code should be in range [0, 35], but for sysfs path %s it was %d",
366 sysfsRootPath.c_str(), hidCountryCode);
Vaibhav Devmurari990ff7b2022-12-22 18:23:21 +0000367 }
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000368 }
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000369 const auto it = LAYOUT_INFOS.find(hidCountryCode);
370 if (it != LAYOUT_INFOS.end()) {
371 return it->second;
372 }
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000373
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000374 return std::nullopt;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000375}
376
377/**
Prabir Pradhancb42b472022-08-23 16:01:19 +0000378 * Read information about batteries exposed through the sysfs path.
379 */
380static std::unordered_map<int32_t /*batteryId*/, RawBatteryInfo> readBatteryConfiguration(
381 const std::filesystem::path& sysfsRootPath) {
382 std::unordered_map<int32_t, RawBatteryInfo> batteryInfos;
383 int32_t nextBatteryId = 0;
384 // Check if device has any battery.
385 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::POWER_SUPPLY);
386 for (const auto& nodePath : paths) {
387 RawBatteryInfo info;
388 info.id = ++nextBatteryId;
389 info.path = nodePath;
390 info.name = nodePath.filename();
391
392 // Scan the path for all the files
393 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
394 const auto& files = allFilesInPath(nodePath);
395 for (const auto& file : files) {
396 const auto it = BATTERY_CLASSES.find(file.filename().string());
397 if (it != BATTERY_CLASSES.end()) {
398 info.flags |= it->second;
399 }
400 }
401 batteryInfos.insert_or_assign(info.id, info);
402 ALOGD("configureBatteryLocked rawBatteryId %d name %s", info.id, info.name.c_str());
403 }
404 return batteryInfos;
405}
406
407/**
408 * Read information about lights exposed through the sysfs path.
409 */
410static std::unordered_map<int32_t /*lightId*/, RawLightInfo> readLightsConfiguration(
411 const std::filesystem::path& sysfsRootPath) {
412 std::unordered_map<int32_t, RawLightInfo> lightInfos;
413 int32_t nextLightId = 0;
414 // Check if device has any lights.
415 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::LEDS);
416 for (const auto& nodePath : paths) {
417 RawLightInfo info;
418 info.id = ++nextLightId;
419 info.path = nodePath;
420 info.name = nodePath.filename();
421 info.maxBrightness = std::nullopt;
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000422
423 // Light name should follow the naming pattern <name>:<color>:<function>
424 // Refer kernel docs /leds/leds-class.html for valid supported LED names.
425 std::regex indexPattern("([a-zA-Z0-9_.:]*:)?([a-zA-Z0-9_.]*):([a-zA-Z0-9_.]*)");
426 std::smatch results;
427
428 if (std::regex_match(info.name, results, indexPattern)) {
429 // regex_match will return full match at index 0 and <name> at index 1. For RawLightInfo
430 // we only care about sections <color> and <function> which will be at index 2 and 3.
431 for (int i = 2; i <= 3; i++) {
432 const auto it = LIGHT_CLASSES.find(results.str(i));
433 if (it != LIGHT_CLASSES.end()) {
434 info.flags |= it->second;
435 }
Prabir Pradhancb42b472022-08-23 16:01:19 +0000436 }
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000437
438 // Set name of the raw light to <function> which represents playerIDs for LEDs that
439 // turn on/off based on the current player ID (Refer to PeripheralController.cpp for
440 // player ID logic)
441 info.name = results.str(3);
Prabir Pradhancb42b472022-08-23 16:01:19 +0000442 }
443 // Scan the path for all the files
444 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
445 const auto& files = allFilesInPath(nodePath);
446 for (const auto& file : files) {
447 const auto it = LIGHT_CLASSES.find(file.filename().string());
448 if (it != LIGHT_CLASSES.end()) {
449 info.flags |= it->second;
450 // If the node has maximum brightness, read it
451 if (it->second == InputLightClass::MAX_BRIGHTNESS) {
452 std::string str;
453 if (base::ReadFileToString(file, &str)) {
454 info.maxBrightness = std::stoi(str);
455 }
456 }
457 }
458 }
459 lightInfos.insert_or_assign(info.id, info);
460 ALOGD("configureLightsLocked rawLightId %d name %s", info.id, info.name.c_str());
461 }
462 return lightInfos;
463}
464
Michael Wrightd02c5b62014-02-10 15:10:22 -0800465// --- Global Functions ---
466
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700467ftl::Flags<InputDeviceClass> getAbsAxisUsage(int32_t axis,
468 ftl::Flags<InputDeviceClass> deviceClasses) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800469 // Touch devices get dibs on touch-related axes.
Chris Ye1b0c7342020-07-28 21:57:03 -0700470 if (deviceClasses.test(InputDeviceClass::TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800471 switch (axis) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700472 case ABS_X:
473 case ABS_Y:
474 case ABS_PRESSURE:
475 case ABS_TOOL_WIDTH:
476 case ABS_DISTANCE:
477 case ABS_TILT_X:
478 case ABS_TILT_Y:
479 case ABS_MT_SLOT:
480 case ABS_MT_TOUCH_MAJOR:
481 case ABS_MT_TOUCH_MINOR:
482 case ABS_MT_WIDTH_MAJOR:
483 case ABS_MT_WIDTH_MINOR:
484 case ABS_MT_ORIENTATION:
485 case ABS_MT_POSITION_X:
486 case ABS_MT_POSITION_Y:
487 case ABS_MT_TOOL_TYPE:
488 case ABS_MT_BLOB_ID:
489 case ABS_MT_TRACKING_ID:
490 case ABS_MT_PRESSURE:
491 case ABS_MT_DISTANCE:
Chris Ye1b0c7342020-07-28 21:57:03 -0700492 return InputDeviceClass::TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800493 }
494 }
495
Chris Yef59a2f42020-10-16 12:55:26 -0700496 if (deviceClasses.test(InputDeviceClass::SENSOR)) {
497 switch (axis) {
498 case ABS_X:
499 case ABS_Y:
500 case ABS_Z:
501 case ABS_RX:
502 case ABS_RY:
503 case ABS_RZ:
504 return InputDeviceClass::SENSOR;
505 }
506 }
507
Michael Wright842500e2015-03-13 17:32:02 -0700508 // External stylus gets the pressure axis
Chris Ye1b0c7342020-07-28 21:57:03 -0700509 if (deviceClasses.test(InputDeviceClass::EXTERNAL_STYLUS)) {
Michael Wright842500e2015-03-13 17:32:02 -0700510 if (axis == ABS_PRESSURE) {
Chris Ye1b0c7342020-07-28 21:57:03 -0700511 return InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -0700512 }
513 }
514
Michael Wrightd02c5b62014-02-10 15:10:22 -0800515 // Joystick devices get the rest.
Chris Ye1b0c7342020-07-28 21:57:03 -0700516 return deviceClasses & InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800517}
518
Harry Cuttsea73eaa2023-01-16 17:55:46 +0000519// --- RawAbsoluteAxisInfo ---
520
521std::ostream& operator<<(std::ostream& out, const RawAbsoluteAxisInfo& info) {
522 if (info.valid) {
523 out << "min=" << info.minValue << ", max=" << info.maxValue << ", flat=" << info.flat
524 << ", fuzz=" << info.fuzz << ", resolution=" << info.resolution;
525 } else {
526 out << "unknown range";
527 }
528 return out;
529}
530
Michael Wrightd02c5b62014-02-10 15:10:22 -0800531// --- EventHub::Device ---
532
Prabir Pradhancb42b472022-08-23 16:01:19 +0000533EventHub::Device::Device(int fd, int32_t id, std::string path, InputDeviceIdentifier identifier,
534 std::shared_ptr<const AssociatedDevice> assocDev)
Chris Ye989bb932020-07-04 16:18:59 -0700535 : fd(fd),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700536 id(id),
Prabir Pradhancb42b472022-08-23 16:01:19 +0000537 path(std::move(path)),
538 identifier(std::move(identifier)),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700539 classes(0),
540 configuration(nullptr),
541 virtualKeyMap(nullptr),
542 ffEffectPlaying(false),
543 ffEffectId(-1),
Prabir Pradhancb42b472022-08-23 16:01:19 +0000544 associatedDevice(std::move(assocDev)),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700545 controllerNumber(0),
546 enabled(true),
Chris Ye66fbac32020-07-06 20:36:43 -0700547 isVirtual(fd < 0) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800548
549EventHub::Device::~Device() {
550 close();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800551}
552
553void EventHub::Device::close() {
554 if (fd >= 0) {
555 ::close(fd);
556 fd = -1;
557 }
558}
559
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700560status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100561 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700562 if (fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100563 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700564 return -errno;
565 }
566 enabled = true;
567 return OK;
568}
569
570status_t EventHub::Device::disable() {
571 close();
572 enabled = false;
573 return OK;
574}
575
Chris Ye989bb932020-07-04 16:18:59 -0700576bool EventHub::Device::hasValidFd() const {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700577 return !isVirtual && enabled;
578}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800579
Chris Ye3a1e4462020-08-12 10:13:15 -0700580const std::shared_ptr<KeyCharacterMap> EventHub::Device::getKeyCharacterMap() const {
Chris Ye989bb932020-07-04 16:18:59 -0700581 return keyMap.keyCharacterMap;
582}
583
584template <std::size_t N>
585status_t EventHub::Device::readDeviceBitMask(unsigned long ioctlCode, BitArray<N>& bitArray) {
586 if (!hasValidFd()) {
587 return BAD_VALUE;
588 }
589 if ((_IOC_SIZE(ioctlCode) == 0)) {
590 ioctlCode |= _IOC(0, 0, 0, bitArray.bytes());
591 }
592
593 typename BitArray<N>::Buffer buffer;
594 status_t ret = ioctl(fd, ioctlCode, buffer.data());
595 bitArray.loadFromBuffer(buffer);
596 return ret;
597}
598
599void EventHub::Device::configureFd() {
600 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
601 if (classes.test(InputDeviceClass::KEYBOARD)) {
602 // Disable kernel key repeat since we handle it ourselves
603 unsigned int repeatRate[] = {0, 0};
604 if (ioctl(fd, EVIOCSREP, repeatRate)) {
605 ALOGW("Unable to disable kernel key repeat for %s: %s", path.c_str(), strerror(errno));
606 }
607 }
608
609 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
610 // associated with input events. This is important because the input system
611 // uses the timestamps extensively and assumes they were recorded using the monotonic
612 // clock.
613 int clockId = CLOCK_MONOTONIC;
Chris Yef59a2f42020-10-16 12:55:26 -0700614 if (classes.test(InputDeviceClass::SENSOR)) {
615 // Each new sensor event should use the same time base as
616 // SystemClock.elapsedRealtimeNanos().
617 clockId = CLOCK_BOOTTIME;
618 }
Chris Ye989bb932020-07-04 16:18:59 -0700619 bool usingClockIoctl = !ioctl(fd, EVIOCSCLOCKID, &clockId);
620 ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
621}
622
623bool EventHub::Device::hasKeycodeLocked(int keycode) const {
624 if (!keyMap.haveKeyLayout()) {
625 return false;
626 }
627
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700628 std::vector<int32_t> scanCodes = keyMap.keyLayoutMap->findScanCodesForKey(keycode);
Chris Ye989bb932020-07-04 16:18:59 -0700629 const size_t N = scanCodes.size();
630 for (size_t i = 0; i < N && i <= KEY_MAX; i++) {
631 int32_t sc = scanCodes[i];
632 if (sc >= 0 && sc <= KEY_MAX && keyBitmask.test(sc)) {
633 return true;
634 }
635 }
636
637 return false;
638}
639
640void EventHub::Device::loadConfigurationLocked() {
641 configurationFile =
642 getInputDeviceConfigurationFilePathByDeviceIdentifier(identifier,
643 InputDeviceConfigurationFileType::
644 CONFIGURATION);
645 if (configurationFile.empty()) {
646 ALOGD("No input device configuration file found for device '%s'.", identifier.name.c_str());
647 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500648 android::base::Result<std::unique_ptr<PropertyMap>> propertyMap =
649 PropertyMap::load(configurationFile.c_str());
650 if (!propertyMap.ok()) {
Chris Ye989bb932020-07-04 16:18:59 -0700651 ALOGE("Error loading input device configuration file for device '%s'. "
652 "Using default configuration.",
653 identifier.name.c_str());
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500654 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500655 configuration = std::move(*propertyMap);
Chris Ye989bb932020-07-04 16:18:59 -0700656 }
657 }
658}
659
660bool EventHub::Device::loadVirtualKeyMapLocked() {
661 // The virtual key map is supplied by the kernel as a system board property file.
662 std::string propPath = "/sys/board_properties/virtualkeys.";
663 propPath += identifier.getCanonicalName();
664 if (access(propPath.c_str(), R_OK)) {
665 return false;
666 }
667 virtualKeyMap = VirtualKeyMap::load(propPath);
668 return virtualKeyMap != nullptr;
669}
670
671status_t EventHub::Device::loadKeyMapLocked() {
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500672 return keyMap.load(identifier, configuration.get());
Chris Ye989bb932020-07-04 16:18:59 -0700673}
674
675bool EventHub::Device::isExternalDeviceLocked() {
676 if (configuration) {
Harry Cuttsf13161a2023-03-08 14:15:49 +0000677 std::optional<bool> isInternal = configuration->getBool("device.internal");
678 if (isInternal.has_value()) {
679 return !isInternal.value();
Chris Ye989bb932020-07-04 16:18:59 -0700680 }
681 }
682 return identifier.bus == BUS_USB || identifier.bus == BUS_BLUETOOTH;
683}
684
685bool EventHub::Device::deviceHasMicLocked() {
686 if (configuration) {
Harry Cuttsf13161a2023-03-08 14:15:49 +0000687 std::optional<bool> hasMic = configuration->getBool("audio.mic");
688 if (hasMic.has_value()) {
689 return hasMic.value();
Chris Ye989bb932020-07-04 16:18:59 -0700690 }
691 }
692 return false;
693}
694
695void EventHub::Device::setLedStateLocked(int32_t led, bool on) {
696 int32_t sc;
697 if (hasValidFd() && mapLed(led, &sc) != NAME_NOT_FOUND) {
698 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -0700699 ev.input_event_sec = 0;
700 ev.input_event_usec = 0;
Chris Ye989bb932020-07-04 16:18:59 -0700701 ev.type = EV_LED;
702 ev.code = sc;
703 ev.value = on ? 1 : 0;
704
705 ssize_t nWrite;
706 do {
707 nWrite = write(fd, &ev, sizeof(struct input_event));
708 } while (nWrite == -1 && errno == EINTR);
709 }
710}
711
712void EventHub::Device::setLedForControllerLocked() {
713 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
714 setLedStateLocked(ALED_CONTROLLER_1 + i, controllerNumber == i + 1);
715 }
716}
717
718status_t EventHub::Device::mapLed(int32_t led, int32_t* outScanCode) const {
719 if (!keyMap.haveKeyLayout()) {
720 return NAME_NOT_FOUND;
721 }
722
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700723 std::optional<int32_t> scanCode = keyMap.keyLayoutMap->findScanCodeForLed(led);
724 if (scanCode.has_value()) {
725 if (*scanCode >= 0 && *scanCode <= LED_MAX && ledBitmask.test(*scanCode)) {
726 *outScanCode = *scanCode;
Chris Ye989bb932020-07-04 16:18:59 -0700727 return NO_ERROR;
728 }
729 }
730 return NAME_NOT_FOUND;
731}
732
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100733/**
734 * Get the capabilities for the current process.
735 * Crashes the system if unable to create / check / destroy the capabilities object.
736 */
737class Capabilities final {
738public:
739 explicit Capabilities() {
740 mCaps = cap_get_proc();
741 LOG_ALWAYS_FATAL_IF(mCaps == nullptr, "Could not get capabilities of the current process");
742 }
743
744 /**
745 * Check whether the current process has a specific capability
746 * in the set of effective capabilities.
747 * Return CAP_SET if the process has the requested capability
748 * Return CAP_CLEAR otherwise.
749 */
750 cap_flag_value_t checkEffectiveCapability(cap_value_t capability) {
751 cap_flag_value_t value;
752 const int result = cap_get_flag(mCaps, capability, CAP_EFFECTIVE, &value);
753 LOG_ALWAYS_FATAL_IF(result == -1, "Could not obtain the requested capability");
754 return value;
755 }
756
757 ~Capabilities() {
758 const int result = cap_free(mCaps);
759 LOG_ALWAYS_FATAL_IF(result == -1, "Could not release the capabilities structure");
760 }
761
762private:
763 cap_t mCaps;
764};
765
766static void ensureProcessCanBlockSuspend() {
767 Capabilities capabilities;
768 const bool canBlockSuspend =
769 capabilities.checkEffectiveCapability(CAP_BLOCK_SUSPEND) == CAP_SET;
770 LOG_ALWAYS_FATAL_IF(!canBlockSuspend,
771 "Input must be able to block suspend to properly process events");
772}
773
Michael Wrightd02c5b62014-02-10 15:10:22 -0800774// --- EventHub ---
775
Michael Wrightd02c5b62014-02-10 15:10:22 -0800776const int EventHub::EPOLL_MAX_EVENTS;
777
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700778EventHub::EventHub(void)
779 : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
780 mNextDeviceId(1),
781 mControllerNumbers(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800782 mNeedToSendFinishedDeviceScan(false),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700783 mNeedToReopenDevices(false),
784 mNeedToScanDevices(true),
785 mPendingEventCount(0),
786 mPendingEventIndex(0),
787 mPendingINotify(false) {
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100788 ensureProcessCanBlockSuspend();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800789
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800790 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800791 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800792
Michael Wright8e9a8562022-02-09 13:44:29 +0000793 mINotifyFd = inotify_init1(IN_CLOEXEC);
Prabir Pradhan952e65b2022-06-23 17:49:55 +0000794 LOG_ALWAYS_FATAL_IF(mINotifyFd < 0, "Could not create inotify instance: %s", strerror(errno));
Usama Arifb27c8e62021-06-03 16:44:09 +0100795
796 std::error_code errorCode;
797 bool isDeviceInotifyAdded = false;
798 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
799 addDeviceInputInotify();
Philip Quinn39b81682019-01-09 22:20:39 -0800800 } else {
Usama Arifb27c8e62021-06-03 16:44:09 +0100801 addDeviceInotify();
802 isDeviceInotifyAdded = true;
803 if (errorCode) {
804 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
805 errorCode.message().c_str());
806 }
807 }
808
809 if (isV4lScanningEnabled() && !isDeviceInotifyAdded) {
810 addDeviceInotify();
811 } else {
Philip Quinn39b81682019-01-09 22:20:39 -0800812 ALOGI("Video device scanning disabled");
813 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800814
Siarhei Vishniakou2d0e9482019-09-24 12:52:47 +0100815 struct epoll_event eventItem = {};
816 eventItem.events = EPOLLIN | EPOLLWAKEUP;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700817 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800818 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800819 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
820
821 int wakeFds[2];
Michael Wright8e9a8562022-02-09 13:44:29 +0000822 result = pipe2(wakeFds, O_CLOEXEC);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800823 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
824
825 mWakeReadPipeFd = wakeFds[0];
826 mWakeWritePipeFd = wakeFds[1];
827
828 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
829 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700830 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800831
832 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
833 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700834 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800835
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700836 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800837 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
838 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700839 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800840}
841
842EventHub::~EventHub(void) {
843 closeAllDevicesLocked();
844
Michael Wrightd02c5b62014-02-10 15:10:22 -0800845 ::close(mEpollFd);
846 ::close(mINotifyFd);
847 ::close(mWakeReadPipeFd);
848 ::close(mWakeWritePipeFd);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800849}
850
Usama Arifb27c8e62021-06-03 16:44:09 +0100851/**
852 * On devices that don't have any input devices (like some development boards), the /dev/input
853 * directory will be absent. However, the user may still plug in an input device at a later time.
854 * Add watch for contents of /dev/input only when /dev/input appears.
855 */
856void EventHub::addDeviceInputInotify() {
857 mDeviceInputWd = inotify_add_watch(mINotifyFd, DEVICE_INPUT_PATH, IN_DELETE | IN_CREATE);
858 LOG_ALWAYS_FATAL_IF(mDeviceInputWd < 0, "Could not register INotify for %s: %s",
859 DEVICE_INPUT_PATH, strerror(errno));
860}
861
862void EventHub::addDeviceInotify() {
863 mDeviceWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
864 LOG_ALWAYS_FATAL_IF(mDeviceWd < 0, "Could not register INotify for %s: %s", DEVICE_PATH,
865 strerror(errno));
866}
867
Michael Wrightd02c5b62014-02-10 15:10:22 -0800868InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000869 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800870 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700871 return device != nullptr ? device->identifier : InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800872}
873
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700874ftl::Flags<InputDeviceClass> EventHub::getDeviceClasses(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000875 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800876 Device* device = getDeviceLocked(deviceId);
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700877 return device != nullptr ? device->classes : ftl::Flags<InputDeviceClass>(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800878}
879
880int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000881 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800882 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700883 return device != nullptr ? device->controllerNumber : 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800884}
885
Harry Cuttsc34f7582023-03-07 16:23:30 +0000886std::optional<PropertyMap> EventHub::getConfiguration(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000887 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800888 Device* device = getDeviceLocked(deviceId);
Harry Cuttsc34f7582023-03-07 16:23:30 +0000889 if (device == nullptr || device->configuration == nullptr) {
890 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -0800891 }
Harry Cuttsc34f7582023-03-07 16:23:30 +0000892 return *device->configuration;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800893}
894
895status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700896 RawAbsoluteAxisInfo* outAxisInfo) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800897 outAxisInfo->clear();
898
899 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000900 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800901
902 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700903 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700905 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
906 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
907 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800908 return -errno;
909 }
910
911 if (info.minimum != info.maximum) {
912 outAxisInfo->valid = true;
913 outAxisInfo->minValue = info.minimum;
914 outAxisInfo->maxValue = info.maximum;
915 outAxisInfo->flat = info.flat;
916 outAxisInfo->fuzz = info.fuzz;
917 outAxisInfo->resolution = info.resolution;
918 }
919 return OK;
920 }
921 }
922 return -1;
923}
924
925bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
926 if (axis >= 0 && axis <= REL_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000927 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800928 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700929 return device != nullptr ? device->relBitmask.test(axis) : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800930 }
931 return false;
932}
933
934bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
Chris Ye87143712020-11-10 05:05:58 +0000935 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800936
Chris Ye989bb932020-07-04 16:18:59 -0700937 Device* device = getDeviceLocked(deviceId);
938 return property >= 0 && property <= INPUT_PROP_MAX && device != nullptr
939 ? device->propBitmask.test(property)
940 : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800941}
942
Chris Yef59a2f42020-10-16 12:55:26 -0700943bool EventHub::hasMscEvent(int32_t deviceId, int mscEvent) const {
944 std::scoped_lock _l(mLock);
945
946 Device* device = getDeviceLocked(deviceId);
947 return mscEvent >= 0 && mscEvent <= MSC_MAX && device != nullptr
948 ? device->mscBitmask.test(mscEvent)
949 : false;
950}
951
Michael Wrightd02c5b62014-02-10 15:10:22 -0800952int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
953 if (scanCode >= 0 && scanCode <= KEY_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000954 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800955
956 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700957 if (device != nullptr && device->hasValidFd() && device->keyBitmask.test(scanCode)) {
958 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
959 return device->keyState.test(scanCode) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800960 }
961 }
962 }
963 return AKEY_STATE_UNKNOWN;
964}
965
966int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
Chris Ye87143712020-11-10 05:05:58 +0000967 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800968
969 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700970 if (device != nullptr && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700971 std::vector<int32_t> scanCodes = device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800972 if (scanCodes.size() != 0) {
Chris Ye66fbac32020-07-06 20:36:43 -0700973 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800974 for (size_t i = 0; i < scanCodes.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800975 int32_t sc = scanCodes[i];
Chris Ye66fbac32020-07-06 20:36:43 -0700976 if (sc >= 0 && sc <= KEY_MAX && device->keyState.test(sc)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800977 return AKEY_STATE_DOWN;
978 }
979 }
980 return AKEY_STATE_UP;
981 }
982 }
983 }
984 return AKEY_STATE_UNKNOWN;
985}
986
Philip Junker4af3b3d2021-12-14 10:36:55 +0100987int32_t EventHub::getKeyCodeForKeyLocation(int32_t deviceId, int32_t locationKeyCode) const {
988 std::scoped_lock _l(mLock);
989
990 Device* device = getDeviceLocked(deviceId);
991 if (device == nullptr || !device->hasValidFd() || device->keyMap.keyCharacterMap == nullptr ||
992 device->keyMap.keyLayoutMap == nullptr) {
993 return AKEYCODE_UNKNOWN;
994 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700995 std::vector<int32_t> scanCodes =
996 device->keyMap.keyLayoutMap->findScanCodesForKey(locationKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +0100997 if (scanCodes.empty()) {
998 ALOGW("Failed to get key code for key location: no scan code maps to key code %d for input"
999 "device %d",
1000 locationKeyCode, deviceId);
1001 return AKEYCODE_UNKNOWN;
1002 }
1003 if (scanCodes.size() > 1) {
1004 ALOGW("Multiple scan codes map to the same key code %d, returning only the first match",
1005 locationKeyCode);
1006 }
1007 int32_t outKeyCode;
1008 status_t mapKeyRes =
Harry Cutts33476232023-01-30 19:57:29 +00001009 device->getKeyCharacterMap()->mapKey(scanCodes[0], /*usageCode=*/0, &outKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +01001010 switch (mapKeyRes) {
1011 case OK:
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001012 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +01001013 case NAME_NOT_FOUND:
1014 // key character map doesn't re-map this scanCode, hence the keyCode remains the same
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001015 outKeyCode = locationKeyCode;
1016 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +01001017 default:
1018 ALOGW("Failed to get key code for key location: Key character map returned error %s",
1019 statusToString(mapKeyRes).c_str());
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001020 outKeyCode = AKEYCODE_UNKNOWN;
1021 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +01001022 }
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001023 // Remap if there is a Key remapping added to the KCM and return the remapped key
1024 return device->getKeyCharacterMap()->applyKeyRemapping(outKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +01001025}
1026
Michael Wrightd02c5b62014-02-10 15:10:22 -08001027int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
1028 if (sw >= 0 && sw <= SW_MAX) {
Chris Ye87143712020-11-10 05:05:58 +00001029 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001030
1031 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001032 if (device != nullptr && device->hasValidFd() && device->swBitmask.test(sw)) {
1033 if (device->readDeviceBitMask(EVIOCGSW(0), device->swState) >= 0) {
1034 return device->swState.test(sw) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001035 }
1036 }
1037 }
1038 return AKEY_STATE_UNKNOWN;
1039}
1040
1041status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
1042 *outValue = 0;
1043
1044 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +00001045 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001046
1047 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001048 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001049 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001050 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
1051 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
1052 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001053 return -errno;
1054 }
1055
1056 *outValue = info.value;
1057 return OK;
1058 }
1059 }
1060 return -1;
1061}
1062
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001063bool EventHub::markSupportedKeyCodes(int32_t deviceId, const std::vector<int32_t>& keyCodes,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001064 uint8_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +00001065 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001066
1067 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001068 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001069 for (size_t codeIndex = 0; codeIndex < keyCodes.size(); codeIndex++) {
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001070 std::vector<int32_t> scanCodes =
1071 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCodes[codeIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001072
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001073 // check the possible scan codes identified by the layout map against the
1074 // map of codes actually emitted by the driver
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001075 for (const int32_t scanCode : scanCodes) {
1076 if (device->keyBitmask.test(scanCode)) {
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001077 outFlags[codeIndex] = 1;
1078 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001079 }
1080 }
1081 }
1082 return true;
1083 }
1084 return false;
1085}
1086
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001087void EventHub::addKeyRemapping(int32_t deviceId, int32_t fromKeyCode, int32_t toKeyCode) const {
1088 std::scoped_lock _l(mLock);
1089 Device* device = getDeviceLocked(deviceId);
1090 if (device == nullptr) {
1091 return;
1092 }
1093 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
1094 if (kcm) {
1095 kcm->addKeyRemapping(fromKeyCode, toKeyCode);
1096 }
1097}
1098
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001099status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
1100 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +00001101 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001102 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001103 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001104
Chris Ye66fbac32020-07-06 20:36:43 -07001105 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001106 // Check the key character map first.
Chris Ye3a1e4462020-08-12 10:13:15 -07001107 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
1108 if (kcm) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001109 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
1110 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001111 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001112 }
1113 }
1114
1115 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001116 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -08001117 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001118 status = NO_ERROR;
1119 }
1120 }
1121
1122 if (status == NO_ERROR) {
Chris Ye3a1e4462020-08-12 10:13:15 -07001123 if (kcm) {
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001124 // Remap keys based on user-defined key remappings and key behavior defined in the
1125 // corresponding kcm file
1126 *outKeycode = kcm->applyKeyRemapping(*outKeycode);
1127
1128 // Remap keys based on Key behavior defined in KCM file
1129 std::tie(*outKeycode, *outMetaState) =
1130 kcm->applyKeyBehavior(*outKeycode, metaState);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001131 } else {
1132 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001133 }
1134 }
1135 }
1136
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001137 if (status != NO_ERROR) {
1138 *outKeycode = 0;
1139 *outFlags = 0;
1140 *outMetaState = metaState;
1141 }
1142
1143 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001144}
1145
1146status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
Chris Ye87143712020-11-10 05:05:58 +00001147 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001148 Device* device = getDeviceLocked(deviceId);
1149
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001150 if (device == nullptr || !device->keyMap.haveKeyLayout()) {
1151 return NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001152 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001153 std::optional<AxisInfo> info = device->keyMap.keyLayoutMap->mapAxis(scanCode);
1154 if (!info.has_value()) {
1155 return NAME_NOT_FOUND;
1156 }
1157 *outAxisInfo = *info;
1158 return NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001159}
1160
Chris Yef59a2f42020-10-16 12:55:26 -07001161base::Result<std::pair<InputDeviceSensorType, int32_t>> EventHub::mapSensor(int32_t deviceId,
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001162 int32_t absCode) const {
Chris Yef59a2f42020-10-16 12:55:26 -07001163 std::scoped_lock _l(mLock);
1164 Device* device = getDeviceLocked(deviceId);
1165
1166 if (device != nullptr && device->keyMap.haveKeyLayout()) {
1167 return device->keyMap.keyLayoutMap->mapSensor(absCode);
1168 }
1169 return Errorf("Device not found or device has no key layout.");
1170}
1171
Chris Yee2b1e5c2021-03-10 22:45:12 -08001172// Gets the battery info map from battery ID to RawBatteryInfo of the miscellaneous device
1173// associated with the device ID. Returns an empty map if no miscellaneous device found.
1174const std::unordered_map<int32_t, RawBatteryInfo>& EventHub::getBatteryInfoLocked(
1175 int32_t deviceId) const {
1176 static const std::unordered_map<int32_t, RawBatteryInfo> EMPTY_BATTERY_INFO = {};
1177 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001178 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001179 return EMPTY_BATTERY_INFO;
1180 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001181 return device->associatedDevice->batteryInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001182}
1183
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001184std::vector<int32_t> EventHub::getRawBatteryIds(int32_t deviceId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001185 std::scoped_lock _l(mLock);
1186 std::vector<int32_t> batteryIds;
1187
Prabir Pradhan51894782022-08-23 16:29:10 +00001188 for (const auto& [id, info] : getBatteryInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001189 batteryIds.push_back(id);
1190 }
1191
1192 return batteryIds;
1193}
1194
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001195std::optional<RawBatteryInfo> EventHub::getRawBatteryInfo(int32_t deviceId,
1196 int32_t batteryId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001197 std::scoped_lock _l(mLock);
1198
1199 const auto infos = getBatteryInfoLocked(deviceId);
1200
1201 auto it = infos.find(batteryId);
1202 if (it != infos.end()) {
1203 return it->second;
1204 }
1205
1206 return std::nullopt;
1207}
1208
1209// Gets the light info map from light ID to RawLightInfo of the miscellaneous device associated
Prabir Pradhan51894782022-08-23 16:29:10 +00001210// with the device ID. Returns an empty map if no miscellaneous device found.
Chris Yee2b1e5c2021-03-10 22:45:12 -08001211const std::unordered_map<int32_t, RawLightInfo>& EventHub::getLightInfoLocked(
1212 int32_t deviceId) const {
1213 static const std::unordered_map<int32_t, RawLightInfo> EMPTY_LIGHT_INFO = {};
1214 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001215 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001216 return EMPTY_LIGHT_INFO;
1217 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001218 return device->associatedDevice->lightInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001219}
1220
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001221std::vector<int32_t> EventHub::getRawLightIds(int32_t deviceId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001222 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001223 std::vector<int32_t> lightIds;
1224
Prabir Pradhan51894782022-08-23 16:29:10 +00001225 for (const auto& [id, info] : getLightInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001226 lightIds.push_back(id);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001227 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001228
Chris Ye3fdbfef2021-01-06 18:45:18 -08001229 return lightIds;
1230}
1231
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001232std::optional<RawLightInfo> EventHub::getRawLightInfo(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001233 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001234
Chris Yee2b1e5c2021-03-10 22:45:12 -08001235 const auto infos = getLightInfoLocked(deviceId);
1236
1237 auto it = infos.find(lightId);
1238 if (it != infos.end()) {
1239 return it->second;
Chris Ye3fdbfef2021-01-06 18:45:18 -08001240 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001241
Chris Ye3fdbfef2021-01-06 18:45:18 -08001242 return std::nullopt;
1243}
1244
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001245std::optional<int32_t> EventHub::getLightBrightness(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001246 std::scoped_lock _l(mLock);
1247
Chris Yee2b1e5c2021-03-10 22:45:12 -08001248 const auto infos = getLightInfoLocked(deviceId);
1249 auto it = infos.find(lightId);
1250 if (it == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001251 return std::nullopt;
1252 }
1253 std::string buffer;
1254 if (!base::ReadFileToString(it->second.path / LIGHT_NODES.at(InputLightClass::BRIGHTNESS),
1255 &buffer)) {
1256 return std::nullopt;
1257 }
1258 return std::stoi(buffer);
1259}
1260
1261std::optional<std::unordered_map<LightColor, int32_t>> EventHub::getLightIntensities(
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001262 int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001263 std::scoped_lock _l(mLock);
1264
Chris Yee2b1e5c2021-03-10 22:45:12 -08001265 const auto infos = getLightInfoLocked(deviceId);
1266 auto lightIt = infos.find(lightId);
1267 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001268 return std::nullopt;
1269 }
1270
1271 auto ret =
1272 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1273
1274 if (!ret.has_value()) {
1275 return std::nullopt;
1276 }
1277 std::array<LightColor, COLOR_NUM> colors = ret.value();
1278
1279 std::string intensityStr;
1280 if (!base::ReadFileToString(lightIt->second.path /
1281 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY),
1282 &intensityStr)) {
1283 return std::nullopt;
1284 }
1285
1286 // Intensity node outputs 3 color values
1287 std::regex intensityPattern("([0-9]+)\\s([0-9]+)\\s([0-9]+)[\\n]");
1288 std::smatch results;
1289
1290 if (!std::regex_match(intensityStr, results, intensityPattern)) {
1291 return std::nullopt;
1292 }
1293 std::unordered_map<LightColor, int32_t> intensities;
1294 for (size_t i = 1; i < results.size(); i++) {
1295 int value = std::stoi(results[i].str());
1296 intensities.emplace(colors[i - 1], value);
1297 }
1298 return intensities;
1299}
1300
1301void EventHub::setLightBrightness(int32_t deviceId, int32_t lightId, int32_t brightness) {
1302 std::scoped_lock _l(mLock);
1303
Chris Yee2b1e5c2021-03-10 22:45:12 -08001304 const auto infos = getLightInfoLocked(deviceId);
1305 auto lightIt = infos.find(lightId);
1306 if (lightIt == infos.end()) {
1307 ALOGE("%s lightId %d not found ", __func__, lightId);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001308 return;
1309 }
1310
1311 if (!base::WriteStringToFile(std::to_string(brightness),
1312 lightIt->second.path /
1313 LIGHT_NODES.at(InputLightClass::BRIGHTNESS))) {
1314 ALOGE("Can not write to file, error: %s", strerror(errno));
1315 }
1316}
1317
1318void EventHub::setLightIntensities(int32_t deviceId, int32_t lightId,
1319 std::unordered_map<LightColor, int32_t> intensities) {
1320 std::scoped_lock _l(mLock);
1321
Chris Yee2b1e5c2021-03-10 22:45:12 -08001322 const auto infos = getLightInfoLocked(deviceId);
1323 auto lightIt = infos.find(lightId);
1324 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001325 ALOGE("Light Id %d does not exist.", lightId);
1326 return;
1327 }
1328
1329 auto ret =
1330 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1331
1332 if (!ret.has_value()) {
1333 return;
1334 }
1335 std::array<LightColor, COLOR_NUM> colors = ret.value();
1336
1337 std::string rgbStr;
1338 for (size_t i = 0; i < COLOR_NUM; i++) {
1339 auto it = intensities.find(colors[i]);
1340 if (it != intensities.end()) {
1341 rgbStr += std::to_string(it->second);
1342 // Insert space between colors
1343 if (i < COLOR_NUM - 1) {
1344 rgbStr += " ";
1345 }
1346 }
1347 }
1348 // Append new line
1349 rgbStr += "\n";
1350
1351 if (!base::WriteStringToFile(rgbStr,
1352 lightIt->second.path /
1353 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY))) {
1354 ALOGE("Can not write to file, error: %s", strerror(errno));
1355 }
1356}
1357
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001358std::optional<RawLayoutInfo> EventHub::getRawLayoutInfo(int32_t deviceId) const {
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001359 std::scoped_lock _l(mLock);
1360 Device* device = getDeviceLocked(deviceId);
1361 if (device == nullptr || !device->associatedDevice) {
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001362 return std::nullopt;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001363 }
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001364 return device->associatedDevice->layoutInfo;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001365}
1366
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001367void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Chris Ye87143712020-11-10 05:05:58 +00001368 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001369
1370 mExcludedDevices = devices;
1371}
1372
1373bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
Chris Ye87143712020-11-10 05:05:58 +00001374 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001375 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001376 if (device != nullptr && scanCode >= 0 && scanCode <= KEY_MAX) {
1377 return device->keyBitmask.test(scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001378 }
1379 return false;
1380}
1381
Arthur Hungcb40a002021-08-03 14:31:01 +00001382bool EventHub::hasKeyCode(int32_t deviceId, int32_t keyCode) const {
1383 std::scoped_lock _l(mLock);
1384 Device* device = getDeviceLocked(deviceId);
1385 if (device != nullptr) {
1386 return device->hasKeycodeLocked(keyCode);
1387 }
1388 return false;
1389}
1390
Michael Wrightd02c5b62014-02-10 15:10:22 -08001391bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
Chris Ye87143712020-11-10 05:05:58 +00001392 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001393 Device* device = getDeviceLocked(deviceId);
1394 int32_t sc;
Chris Ye989bb932020-07-04 16:18:59 -07001395 if (device != nullptr && device->mapLed(led, &sc) == NO_ERROR) {
Chris Ye66fbac32020-07-06 20:36:43 -07001396 return device->ledBitmask.test(sc);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001397 }
1398 return false;
1399}
1400
1401void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
Chris Ye87143712020-11-10 05:05:58 +00001402 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001403 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -07001404 if (device != nullptr && device->hasValidFd()) {
1405 device->setLedStateLocked(led, on);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001406 }
1407}
1408
1409void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001410 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001411 outVirtualKeys.clear();
1412
Chris Ye87143712020-11-10 05:05:58 +00001413 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001414 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001415 if (device != nullptr && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001416 const std::vector<VirtualKeyDefinition> virtualKeys =
1417 device->virtualKeyMap->getVirtualKeys();
1418 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001419 }
1420}
1421
Chris Ye3a1e4462020-08-12 10:13:15 -07001422const std::shared_ptr<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001423 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001424 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001425 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001426 return device->getKeyCharacterMap();
1427 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001428 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001429}
1430
Vaibhav Devmurari23e8ae92022-12-29 12:07:56 +00001431// If provided map is null, it will reset key character map to default KCM.
Chris Ye3a1e4462020-08-12 10:13:15 -07001432bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, std::shared_ptr<KeyCharacterMap> map) {
Chris Ye87143712020-11-10 05:05:58 +00001433 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001434 Device* device = getDeviceLocked(deviceId);
Vaibhav Devmurari23e8ae92022-12-29 12:07:56 +00001435 if (device == nullptr || device->keyMap.keyCharacterMap == nullptr) {
Philip Junker90bc9492021-12-10 18:39:42 +01001436 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001437 }
Vaibhav Devmurari23e8ae92022-12-29 12:07:56 +00001438 if (map == nullptr) {
1439 device->keyMap.keyCharacterMap->clearLayoutOverlay();
1440 return true;
1441 }
Philip Junker90bc9492021-12-10 18:39:42 +01001442 device->keyMap.keyCharacterMap->combine(*map);
1443 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001444}
1445
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001446static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
1447 std::string rawDescriptor;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001448 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001449 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001450 if (!identifier.uniqueId.empty()) {
1451 rawDescriptor += "uniqueId:";
1452 rawDescriptor += identifier.uniqueId;
Josh Bartel938632f2022-07-19 15:34:22 -05001453 }
1454 if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001455 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001456 }
1457
1458 if (identifier.vendor == 0 && identifier.product == 0) {
1459 // If we don't know the vendor and product id, then the device is probably
1460 // built-in so we need to rely on other information to uniquely identify
1461 // the input device. Usually we try to avoid relying on the device name or
1462 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001463 if (!identifier.name.empty()) {
1464 rawDescriptor += "name:";
1465 rawDescriptor += identifier.name;
1466 } else if (!identifier.location.empty()) {
1467 rawDescriptor += "location:";
1468 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001469 }
1470 }
1471 identifier.descriptor = sha1(rawDescriptor);
1472 return rawDescriptor;
1473}
1474
1475void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
1476 // Compute a device descriptor that uniquely identifies the device.
1477 // The descriptor is assumed to be a stable identifier. Its value should not
1478 // change between reboots, reconnections, firmware updates or new releases
1479 // of Android. In practice we sometimes get devices that cannot be uniquely
1480 // identified. In this case we enforce uniqueness between connected devices.
1481 // Ideally, we also want the descriptor to be short and relatively opaque.
Josh Bartel938632f2022-07-19 15:34:22 -05001482 // Note that we explicitly do not use the path or location for external devices
1483 // as their path or location will change as they are plugged/unplugged or moved
1484 // to different ports. We do fallback to using name and location in the case of
1485 // internal devices which are detected by the vendor and product being 0 in
1486 // generateDescriptor. If two identical descriptors are detected we will fallback
1487 // to using a 'nonce' and incrementing it until the new descriptor no longer has
1488 // a match with any existing descriptors.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001489
1490 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001491 std::string rawDescriptor = generateDescriptor(identifier);
Josh Bartel938632f2022-07-19 15:34:22 -05001492 // Enforce that the generated descriptor is unique.
1493 while (hasDeviceWithDescriptorLocked(identifier.descriptor)) {
1494 identifier.nonce++;
1495 rawDescriptor = generateDescriptor(identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001496 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001497 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001498 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001499}
1500
Prabir Pradhancb42b472022-08-23 16:01:19 +00001501std::shared_ptr<const EventHub::AssociatedDevice> EventHub::obtainAssociatedDeviceLocked(
1502 const std::filesystem::path& devicePath) const {
1503 const std::optional<std::filesystem::path> sysfsRootPathOpt =
1504 getSysfsRootPath(devicePath.c_str());
1505 if (!sysfsRootPathOpt) {
1506 return nullptr;
1507 }
1508
1509 const auto& path = *sysfsRootPathOpt;
Prabir Pradhancb42b472022-08-23 16:01:19 +00001510
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00001511 std::shared_ptr<const AssociatedDevice> associatedDevice = std::make_shared<AssociatedDevice>(
Prabir Pradhancb42b472022-08-23 16:01:19 +00001512 AssociatedDevice{.sysfsRootPath = path,
1513 .batteryInfos = readBatteryConfiguration(path),
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001514 .lightInfos = readLightsConfiguration(path),
1515 .layoutInfo = readLayoutConfiguration(path)});
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00001516
1517 bool associatedDeviceChanged = false;
1518 for (const auto& [id, dev] : mDevices) {
1519 if (dev->associatedDevice && dev->associatedDevice->sysfsRootPath == path) {
1520 if (*associatedDevice != *dev->associatedDevice) {
1521 associatedDeviceChanged = true;
1522 dev->associatedDevice = associatedDevice;
1523 }
1524 associatedDevice = dev->associatedDevice;
1525 }
1526 }
1527 ALOGI_IF(associatedDeviceChanged,
1528 "The AssociatedDevice changed for path '%s'. Using new AssociatedDevice: %s",
1529 path.c_str(), associatedDevice->dump().c_str());
1530
1531 return associatedDevice;
Prabir Pradhancb42b472022-08-23 16:01:19 +00001532}
1533
Vaibhav Devmurari5fc7d852023-03-17 18:43:33 +00001534bool EventHub::AssociatedDevice::isChanged() const {
1535 std::unordered_map<int32_t, RawBatteryInfo> newBatteryInfos =
1536 readBatteryConfiguration(sysfsRootPath);
1537 std::unordered_map<int32_t, RawLightInfo> newLightInfos =
1538 readLightsConfiguration(sysfsRootPath);
1539 std::optional<RawLayoutInfo> newLayoutInfo = readLayoutConfiguration(sysfsRootPath);
1540
1541 if (newBatteryInfos == batteryInfos && newLightInfos == lightInfos &&
1542 newLayoutInfo == layoutInfo) {
1543 return false;
1544 }
1545 return true;
1546}
1547
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001548void EventHub::vibrate(int32_t deviceId, const VibrationElement& element) {
Chris Ye87143712020-11-10 05:05:58 +00001549 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001550 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001551 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001552 ff_effect effect;
1553 memset(&effect, 0, sizeof(effect));
1554 effect.type = FF_RUMBLE;
1555 effect.id = device->ffEffectId;
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001556 // evdev FF_RUMBLE effect only supports two channels of vibration.
Chris Ye6393a262020-08-04 19:41:36 -07001557 effect.u.rumble.strong_magnitude = element.getMagnitude(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1558 effect.u.rumble.weak_magnitude = element.getMagnitude(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001559 effect.replay.length = element.duration.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001560 effect.replay.delay = 0;
1561 if (ioctl(device->fd, EVIOCSFF, &effect)) {
1562 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001563 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001564 return;
1565 }
1566 device->ffEffectId = effect.id;
1567
1568 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -07001569 ev.input_event_sec = 0;
1570 ev.input_event_usec = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001571 ev.type = EV_FF;
1572 ev.code = device->ffEffectId;
1573 ev.value = 1;
1574 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1575 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001576 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001577 return;
1578 }
1579 device->ffEffectPlaying = true;
1580 }
1581}
1582
1583void EventHub::cancelVibrate(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001584 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001585 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001586 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001587 if (device->ffEffectPlaying) {
1588 device->ffEffectPlaying = false;
1589
1590 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -07001591 ev.input_event_sec = 0;
1592 ev.input_event_usec = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001593 ev.type = EV_FF;
1594 ev.code = device->ffEffectId;
1595 ev.value = 0;
1596 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1597 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001598 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001599 return;
1600 }
1601 }
1602 }
1603}
1604
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001605std::vector<int32_t> EventHub::getVibratorIds(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001606 std::scoped_lock _l(mLock);
1607 std::vector<int32_t> vibrators;
1608 Device* device = getDeviceLocked(deviceId);
1609 if (device != nullptr && device->hasValidFd() &&
1610 device->classes.test(InputDeviceClass::VIBRATOR)) {
1611 vibrators.push_back(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1612 vibrators.push_back(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
1613 }
1614 return vibrators;
1615}
1616
Josh Bartel938632f2022-07-19 15:34:22 -05001617/**
1618 * Checks both mDevices and mOpeningDevices for a device with the descriptor passed.
1619 */
1620bool EventHub::hasDeviceWithDescriptorLocked(const std::string& descriptor) const {
1621 for (const auto& device : mOpeningDevices) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001622 if (descriptor == device->identifier.descriptor) {
Josh Bartel938632f2022-07-19 15:34:22 -05001623 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001624 }
1625 }
Josh Bartel938632f2022-07-19 15:34:22 -05001626
1627 for (const auto& [id, device] : mDevices) {
1628 if (descriptor == device->identifier.descriptor) {
1629 return true;
1630 }
1631 }
1632 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001633}
1634
1635EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001636 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001637 deviceId = mBuiltInKeyboardId;
1638 }
Chris Ye989bb932020-07-04 16:18:59 -07001639 const auto& it = mDevices.find(deviceId);
1640 return it != mDevices.end() ? it->second.get() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001641}
1642
Chris Ye8594e192020-07-14 10:34:06 -07001643EventHub::Device* EventHub::getDeviceByPathLocked(const std::string& devicePath) const {
Chris Ye989bb932020-07-04 16:18:59 -07001644 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001645 if (device->path == devicePath) {
Chris Ye989bb932020-07-04 16:18:59 -07001646 return device.get();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001647 }
1648 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001649 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001650}
1651
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001652/**
1653 * The file descriptor could be either input device, or a video device (associated with a
1654 * specific input device). Check both cases here, and return the device that this event
1655 * belongs to. Caller can compare the fd's once more to determine event type.
1656 * Looks through all input devices, and only attached video devices. Unattached video
1657 * devices are ignored.
1658 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001659EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
Chris Ye989bb932020-07-04 16:18:59 -07001660 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001661 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001662 // This is an input device event
Chris Ye989bb932020-07-04 16:18:59 -07001663 return device.get();
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001664 }
1665 if (device->videoDevice && device->videoDevice->getFd() == fd) {
1666 // This is a video device event
Chris Ye989bb932020-07-04 16:18:59 -07001667 return device.get();
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001668 }
1669 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001670 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
1671 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001672 return nullptr;
1673}
1674
Chris Yee2b1e5c2021-03-10 22:45:12 -08001675std::optional<int32_t> EventHub::getBatteryCapacity(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001676 std::filesystem::path batteryPath;
1677 {
1678 // Do not read the sysfs node to get the battery state while holding
1679 // the EventHub lock. For some peripheral devices, reading battery state
1680 // can be broken and take 5+ seconds. Holding the lock in this case would
1681 // block all other event processing during this time. For now, we assume this
1682 // call never happens on the InputReader thread and read the sysfs node outside
1683 // the lock to prevent event processing from being blocked by this call.
1684 std::scoped_lock _l(mLock);
Kim Low03ea0352020-11-06 12:45:07 -08001685
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001686 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001687 auto it = infos.find(batteryId);
1688 if (it == infos.end()) {
1689 return std::nullopt;
1690 }
1691 batteryPath = it->second.path;
1692 } // release lock
1693
Chris Yee2b1e5c2021-03-10 22:45:12 -08001694 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001695
1696 // Some devices report battery capacity as an integer through the "capacity" file
Andy Chenf9f1a022022-08-29 20:07:10 -04001697 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001698 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001699 return std::stoi(base::Trim(buffer));
Kim Low03ea0352020-11-06 12:45:07 -08001700 }
1701
1702 // Other devices report capacity as an enum value POWER_SUPPLY_CAPACITY_LEVEL_XXX
1703 // These values are taken from kernel source code include/linux/power_supply.h
Andy Chenf9f1a022022-08-29 20:07:10 -04001704 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY_LEVEL),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001705 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001706 // Remove any white space such as trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001707 const auto levelIt = BATTERY_LEVEL.find(base::Trim(buffer));
1708 if (levelIt != BATTERY_LEVEL.end()) {
1709 return levelIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001710 }
1711 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001712
Kim Low03ea0352020-11-06 12:45:07 -08001713 return std::nullopt;
1714}
1715
Chris Yee2b1e5c2021-03-10 22:45:12 -08001716std::optional<int32_t> EventHub::getBatteryStatus(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001717 std::filesystem::path batteryPath;
1718 {
1719 // Do not read the sysfs node to get the battery state while holding
1720 // the EventHub lock. For some peripheral devices, reading battery state
1721 // can be broken and take 5+ seconds. Holding the lock in this case would
1722 // block all other event processing during this time. For now, we assume this
1723 // call never happens on the InputReader thread and read the sysfs node outside
1724 // the lock to prevent event processing from being blocked by this call.
1725 std::scoped_lock _l(mLock);
1726
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001727 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001728 auto it = infos.find(batteryId);
1729 if (it == infos.end()) {
1730 return std::nullopt;
1731 }
1732 batteryPath = it->second.path;
1733 } // release lock
1734
Chris Yee2b1e5c2021-03-10 22:45:12 -08001735 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001736
Andy Chenf9f1a022022-08-29 20:07:10 -04001737 if (!base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::STATUS),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001738 &buffer)) {
Kim Low03ea0352020-11-06 12:45:07 -08001739 ALOGE("Failed to read sysfs battery info: %s", strerror(errno));
1740 return std::nullopt;
1741 }
1742
Chris Yed1936772021-02-22 10:30:40 -08001743 // Remove white space like trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001744 const auto statusIt = BATTERY_STATUS.find(base::Trim(buffer));
1745 if (statusIt != BATTERY_STATUS.end()) {
1746 return statusIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001747 }
1748
1749 return std::nullopt;
1750}
1751
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001752std::vector<RawEvent> EventHub::getEvents(int timeoutMillis) {
Chris Ye87143712020-11-10 05:05:58 +00001753 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001754
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001755 std::array<input_event, EVENT_BUFFER_SIZE> readBuffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001756
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001757 std::vector<RawEvent> events;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001758 bool awoken = false;
1759 for (;;) {
1760 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
1761
1762 // Reopen input devices if needed.
1763 if (mNeedToReopenDevices) {
1764 mNeedToReopenDevices = false;
1765
1766 ALOGI("Reopening all input devices due to a configuration change.");
1767
1768 closeAllDevicesLocked();
1769 mNeedToScanDevices = true;
1770 break; // return to the caller before we actually rescan
1771 }
1772
1773 // Report any devices that had last been added/removed.
Chris Ye989bb932020-07-04 16:18:59 -07001774 for (auto it = mClosingDevices.begin(); it != mClosingDevices.end();) {
1775 std::unique_ptr<Device> device = std::move(*it);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001776 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001777 const int32_t deviceId = (device->id == mBuiltInKeyboardId)
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001778 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
1779 : device->id;
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001780 events.push_back({
1781 .when = now,
1782 .deviceId = deviceId,
1783 .type = DEVICE_REMOVED,
1784 });
Chris Ye989bb932020-07-04 16:18:59 -07001785 it = mClosingDevices.erase(it);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001786 mNeedToSendFinishedDeviceScan = true;
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001787 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001788 break;
1789 }
1790 }
1791
1792 if (mNeedToScanDevices) {
1793 mNeedToScanDevices = false;
1794 scanDevicesLocked();
1795 mNeedToSendFinishedDeviceScan = true;
1796 }
1797
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001798 while (!mOpeningDevices.empty()) {
1799 std::unique_ptr<Device> device = std::move(*mOpeningDevices.rbegin());
1800 mOpeningDevices.pop_back();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001801 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001802 const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1803 events.push_back({
1804 .when = now,
1805 .deviceId = deviceId,
1806 .type = DEVICE_ADDED,
1807 });
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001808
1809 // Try to find a matching video device by comparing device names
1810 for (auto it = mUnattachedVideoDevices.begin(); it != mUnattachedVideoDevices.end();
1811 it++) {
1812 std::unique_ptr<TouchVideoDevice>& videoDevice = *it;
Chris Yed3fef462021-03-07 17:10:08 -08001813 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001814 // videoDevice was transferred to 'device'
1815 it = mUnattachedVideoDevices.erase(it);
1816 break;
1817 }
1818 }
1819
1820 auto [dev_it, inserted] = mDevices.insert_or_assign(device->id, std::move(device));
1821 if (!inserted) {
Chris Ye989bb932020-07-04 16:18:59 -07001822 ALOGW("Device id %d exists, replaced.", device->id);
1823 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001824 mNeedToSendFinishedDeviceScan = true;
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001825 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001826 break;
1827 }
1828 }
1829
1830 if (mNeedToSendFinishedDeviceScan) {
1831 mNeedToSendFinishedDeviceScan = false;
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001832 events.push_back({
1833 .when = now,
1834 .type = FINISHED_DEVICE_SCAN,
1835 });
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001836 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001837 break;
1838 }
1839 }
1840
1841 // Grab the next input event.
1842 bool deviceChanged = false;
1843 while (mPendingEventIndex < mPendingEventCount) {
1844 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001845 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001846 if (eventItem.events & EPOLLIN) {
1847 mPendingINotify = true;
1848 } else {
1849 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
1850 }
1851 continue;
1852 }
1853
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001854 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001855 if (eventItem.events & EPOLLIN) {
1856 ALOGV("awoken after wake()");
1857 awoken = true;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001858 char wakeReadBuffer[16];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001859 ssize_t nRead;
1860 do {
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001861 nRead = read(mWakeReadPipeFd, wakeReadBuffer, sizeof(wakeReadBuffer));
1862 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(wakeReadBuffer));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001863 } else {
1864 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001865 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001866 }
1867 continue;
1868 }
1869
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001870 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Chris Ye989bb932020-07-04 16:18:59 -07001871 if (device == nullptr) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001872 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
1873 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001874 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001875 continue;
1876 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001877 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
1878 if (eventItem.events & EPOLLIN) {
1879 size_t numFrames = device->videoDevice->readAndQueueFrames();
1880 if (numFrames == 0) {
1881 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001882 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001883 }
1884 } else if (eventItem.events & EPOLLHUP) {
1885 // TODO(b/121395353) - consider adding EPOLLRDHUP
1886 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001887 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001888 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1889 device->videoDevice = nullptr;
1890 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001891 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1892 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001893 ALOG_ASSERT(!DEBUG);
1894 }
1895 continue;
1896 }
1897 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -08001898 if (eventItem.events & EPOLLIN) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001899 int32_t readSize =
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001900 read(device->fd, readBuffer.data(),
1901 sizeof(decltype(readBuffer)::value_type) * readBuffer.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001902 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
1903 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -07001904 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001905 " capacity: %zu errno: %d)\n",
1906 device->fd, readSize, readBuffer.size(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001907 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001908 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001909 } else if (readSize < 0) {
1910 if (errno != EAGAIN && errno != EINTR) {
1911 ALOGW("could not get event (errno=%d)", errno);
1912 }
1913 } else if ((readSize % sizeof(struct input_event)) != 0) {
1914 ALOGE("could not get event (wrong size: %d)", readSize);
1915 } else {
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001916 const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001917
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001918 const size_t count = size_t(readSize) / sizeof(struct input_event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001919 for (size_t i = 0; i < count; i++) {
1920 struct input_event& iev = readBuffer[i];
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001921 events.push_back({
1922 .when = processEventTimestamp(iev),
1923 .readTime = systemTime(SYSTEM_TIME_MONOTONIC),
1924 .deviceId = deviceId,
1925 .type = iev.type,
1926 .code = iev.code,
1927 .value = iev.value,
1928 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08001929 }
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001930 if (events.size() >= EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001931 // The result buffer is full. Reset the pending event index
1932 // so we will try to read the device again on the next iteration.
1933 mPendingEventIndex -= 1;
1934 break;
1935 }
1936 }
1937 } else if (eventItem.events & EPOLLHUP) {
1938 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001939 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001940 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001941 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001942 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001943 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1944 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001945 }
1946 }
1947
1948 // readNotify() will modify the list of devices so this must be done after
1949 // processing all other events to ensure that we read all remaining events
1950 // before closing the devices.
1951 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
1952 mPendingINotify = false;
Prabir Pradhan952e65b2022-06-23 17:49:55 +00001953 const auto res = readNotifyLocked();
1954 if (!res.ok()) {
1955 ALOGW("Failed to read from inotify: %s", res.error().message().c_str());
1956 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001957 deviceChanged = true;
1958 }
1959
1960 // Report added or removed devices immediately.
1961 if (deviceChanged) {
1962 continue;
1963 }
1964
1965 // Return now if we have collected any events or if we were explicitly awoken.
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001966 if (!events.empty() || awoken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001967 break;
1968 }
1969
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001970 // Poll for events.
1971 // When a device driver has pending (unread) events, it acquires
1972 // a kernel wake lock. Once the last pending event has been read, the device
1973 // driver will release the kernel wake lock, but the epoll will hold the wakelock,
1974 // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
1975 // is called again for the same fd that produced the event.
1976 // Thus the system can only sleep if there are no events pending or
1977 // currently being processed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001978 //
1979 // The timeout is advisory only. If the device is asleep, it will not wake just to
1980 // service the timeout.
1981 mPendingEventIndex = 0;
1982
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001983 mLock.unlock(); // release lock before poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001984
1985 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1986
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001987 mLock.lock(); // reacquire lock after poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001988
1989 if (pollResult == 0) {
1990 // Timed out.
1991 mPendingEventCount = 0;
1992 break;
1993 }
1994
1995 if (pollResult < 0) {
1996 // An error occurred.
1997 mPendingEventCount = 0;
1998
1999 // Sleep after errors to avoid locking up the system.
2000 // Hopefully the error is transient.
2001 if (errno != EINTR) {
2002 ALOGW("poll failed (errno=%d)\n", errno);
2003 usleep(100000);
2004 }
2005 } else {
2006 // Some events occurred.
2007 mPendingEventCount = size_t(pollResult);
2008 }
2009 }
2010
2011 // All done, return the number of events we read.
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002012 return events;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002013}
2014
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08002015std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002016 std::scoped_lock _l(mLock);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08002017
2018 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07002019 if (device == nullptr || !device->videoDevice) {
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08002020 return {};
2021 }
2022 return device->videoDevice->consumeFrames();
2023}
2024
Michael Wrightd02c5b62014-02-10 15:10:22 -08002025void EventHub::wake() {
2026 ALOGV("wake() called");
2027
2028 ssize_t nWrite;
2029 do {
2030 nWrite = write(mWakeWritePipeFd, "W", 1);
2031 } while (nWrite == -1 && errno == EINTR);
2032
2033 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002034 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002035 }
2036}
2037
2038void EventHub::scanDevicesLocked() {
Usama Arifb27c8e62021-06-03 16:44:09 +01002039 status_t result;
2040 std::error_code errorCode;
2041
2042 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
2043 result = scanDirLocked(DEVICE_INPUT_PATH);
2044 if (result < 0) {
2045 ALOGE("scan dir failed for %s", DEVICE_INPUT_PATH);
2046 }
2047 } else {
2048 if (errorCode) {
2049 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
2050 errorCode.message().c_str());
2051 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002052 }
Philip Quinn39b81682019-01-09 22:20:39 -08002053 if (isV4lScanningEnabled()) {
Usama Arifb27c8e62021-06-03 16:44:09 +01002054 result = scanVideoDirLocked(DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08002055 if (result != OK) {
Usama Arifb27c8e62021-06-03 16:44:09 +01002056 ALOGE("scan video dir failed for %s", DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08002057 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002058 }
Chris Ye989bb932020-07-04 16:18:59 -07002059 if (mDevices.find(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) == mDevices.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002060 createVirtualKeyboardLocked();
2061 }
2062}
2063
2064// ----------------------------------------------------------------------------
2065
Michael Wrightd02c5b62014-02-10 15:10:22 -08002066static const int32_t GAMEPAD_KEYCODES[] = {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002067 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C, //
2068 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z, //
2069 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1, //
2070 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2, //
2071 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR, //
2072 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE, //
Michael Wrightd02c5b62014-02-10 15:10:22 -08002073};
2074
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002075status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002076 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002077 struct epoll_event eventItem = {};
2078 eventItem.events = EPOLLIN | EPOLLWAKEUP;
2079 eventItem.data.fd = fd;
2080 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
2081 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002082 return -errno;
2083 }
2084 return OK;
2085}
2086
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002087status_t EventHub::unregisterFdFromEpoll(int fd) {
2088 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
2089 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
2090 return -errno;
2091 }
2092 return OK;
2093}
2094
Chris Ye989bb932020-07-04 16:18:59 -07002095status_t EventHub::registerDeviceForEpollLocked(Device& device) {
2096 status_t result = registerFdForEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002097 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07002098 ALOGE("Could not add input device fd to epoll for device %" PRId32, device.id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002099 return result;
2100 }
Chris Ye989bb932020-07-04 16:18:59 -07002101 if (device.videoDevice) {
2102 registerVideoDeviceForEpollLocked(*device.videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002103 }
2104 return result;
2105}
2106
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002107void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
2108 status_t result = registerFdForEpoll(videoDevice.getFd());
2109 if (result != OK) {
2110 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
2111 }
2112}
2113
Chris Ye989bb932020-07-04 16:18:59 -07002114status_t EventHub::unregisterDeviceFromEpollLocked(Device& device) {
2115 if (device.hasValidFd()) {
2116 status_t result = unregisterFdFromEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002117 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07002118 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device.id);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002119 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002120 }
2121 }
Chris Ye989bb932020-07-04 16:18:59 -07002122 if (device.videoDevice) {
2123 unregisterVideoDeviceFromEpollLocked(*device.videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002124 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002125 return OK;
2126}
2127
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002128void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
2129 if (videoDevice.hasValidFd()) {
2130 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
2131 if (result != OK) {
2132 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002133 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002134 }
2135 }
2136}
2137
Chris Yed3fef462021-03-07 17:10:08 -08002138void EventHub::reportDeviceAddedForStatisticsLocked(const InputDeviceIdentifier& identifier,
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002139 ftl::Flags<InputDeviceClass> classes) {
Chris Ye657c2f02021-05-25 16:24:37 -07002140 SHA256_CTX ctx;
2141 SHA256_Init(&ctx);
2142 SHA256_Update(&ctx, reinterpret_cast<const uint8_t*>(identifier.uniqueId.c_str()),
2143 identifier.uniqueId.size());
2144 std::array<uint8_t, SHA256_DIGEST_LENGTH> digest;
2145 SHA256_Final(digest.data(), &ctx);
2146
2147 std::string obfuscatedId;
2148 for (size_t i = 0; i < OBFUSCATED_LENGTH; i++) {
2149 obfuscatedId += StringPrintf("%02x", digest[i]);
2150 }
2151
Chris Yed3fef462021-03-07 17:10:08 -08002152 android::util::stats_write(android::util::INPUTDEVICE_REGISTERED, identifier.name.c_str(),
2153 identifier.vendor, identifier.product, identifier.version,
Chris Ye657c2f02021-05-25 16:24:37 -07002154 identifier.bus, obfuscatedId.c_str(), classes.get());
Chris Yed3fef462021-03-07 17:10:08 -08002155}
2156
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002157void EventHub::openDeviceLocked(const std::string& devicePath) {
2158 // If an input device happens to register around the time when EventHub's constructor runs, it
2159 // is possible that the same input event node (for example, /dev/input/event3) will be noticed
2160 // in both 'inotify' callback and also in the 'scanDirLocked' pass. To prevent duplicate devices
2161 // from getting registered, ensure that this path is not already covered by an existing device.
2162 for (const auto& [deviceId, device] : mDevices) {
2163 if (device->path == devicePath) {
2164 return; // device was already registered
2165 }
2166 }
2167
Michael Wrightd02c5b62014-02-10 15:10:22 -08002168 char buffer[80];
2169
Chris Ye8594e192020-07-14 10:34:06 -07002170 ALOGV("Opening device: %s", devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002171
Chris Ye8594e192020-07-14 10:34:06 -07002172 int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002173 if (fd < 0) {
Chris Ye8594e192020-07-14 10:34:06 -07002174 ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002175 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002176 }
2177
2178 InputDeviceIdentifier identifier;
2179
2180 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002181 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Chris Ye8594e192020-07-14 10:34:06 -07002182 ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002183 } else {
2184 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002185 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002186 }
2187
2188 // Check to see if the device is on our excluded list
2189 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002190 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002191 if (identifier.name == item) {
Chris Ye8594e192020-07-14 10:34:06 -07002192 ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002193 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002194 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002195 }
2196 }
2197
2198 // Get device driver version.
2199 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002200 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Chris Ye8594e192020-07-14 10:34:06 -07002201 ALOGE("could not get driver version for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002202 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002203 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002204 }
2205
2206 // Get device identifier.
2207 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002208 if (ioctl(fd, EVIOCGID, &inputId)) {
Chris Ye8594e192020-07-14 10:34:06 -07002209 ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002210 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002211 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002212 }
2213 identifier.bus = inputId.bustype;
2214 identifier.product = inputId.product;
2215 identifier.vendor = inputId.vendor;
2216 identifier.version = inputId.version;
2217
2218 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002219 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
2220 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002221 } else {
2222 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002223 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002224 }
2225
2226 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002227 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
2228 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002229 } else {
2230 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002231 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002232 }
2233
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002234 // Attempt to get the bluetooth address of an input device from the uniqueId.
2235 if (identifier.bus == BUS_BLUETOOTH &&
2236 std::regex_match(identifier.uniqueId,
2237 std::regex("^[A-Fa-f0-9]{2}(?::[A-Fa-f0-9]{2}){5}$"))) {
2238 identifier.bluetoothAddress = identifier.uniqueId;
2239 // The Bluetooth stack requires alphabetic characters to be uppercase in a valid address.
2240 for (auto& c : *identifier.bluetoothAddress) {
2241 c = ::toupper(c);
2242 }
2243 }
2244
Michael Wrightd02c5b62014-02-10 15:10:22 -08002245 // Fill in the descriptor.
2246 assignDescriptorLocked(identifier);
2247
Michael Wrightd02c5b62014-02-10 15:10:22 -08002248 // Allocate device. (The device object takes ownership of the fd at this point.)
2249 int32_t deviceId = mNextDeviceId++;
Prabir Pradhancb42b472022-08-23 16:01:19 +00002250 std::unique_ptr<Device> device =
2251 std::make_unique<Device>(fd, deviceId, devicePath, identifier,
2252 obtainAssociatedDeviceLocked(devicePath));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002253
Chris Ye8594e192020-07-14 10:34:06 -07002254 ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002255 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002256 " vendor %04x\n"
2257 " product %04x\n"
2258 " version %04x\n",
2259 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002260 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
2261 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
2262 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
2263 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002264 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
2265 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002266
2267 // Load the configuration file for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002268 device->loadConfigurationLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002269
2270 // Figure out the kinds of events the device reports.
Chris Ye66fbac32020-07-06 20:36:43 -07002271 device->readDeviceBitMask(EVIOCGBIT(EV_KEY, 0), device->keyBitmask);
2272 device->readDeviceBitMask(EVIOCGBIT(EV_ABS, 0), device->absBitmask);
2273 device->readDeviceBitMask(EVIOCGBIT(EV_REL, 0), device->relBitmask);
2274 device->readDeviceBitMask(EVIOCGBIT(EV_SW, 0), device->swBitmask);
2275 device->readDeviceBitMask(EVIOCGBIT(EV_LED, 0), device->ledBitmask);
2276 device->readDeviceBitMask(EVIOCGBIT(EV_FF, 0), device->ffBitmask);
Chris Yef59a2f42020-10-16 12:55:26 -07002277 device->readDeviceBitMask(EVIOCGBIT(EV_MSC, 0), device->mscBitmask);
Chris Ye66fbac32020-07-06 20:36:43 -07002278 device->readDeviceBitMask(EVIOCGPROP(0), device->propBitmask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002279
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002280 // See if this is a device with keys. This could be full keyboard, or other devices like
2281 // gamepads, joysticks, and styluses with buttons that should generate key presses.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002282 bool haveKeyboardKeys =
Chris Ye66fbac32020-07-06 20:36:43 -07002283 device->keyBitmask.any(0, BTN_MISC) || device->keyBitmask.any(BTN_WHEEL, KEY_MAX + 1);
2284 bool haveGamepadButtons = device->keyBitmask.any(BTN_MISC, BTN_MOUSE) ||
2285 device->keyBitmask.any(BTN_JOYSTICK, BTN_DIGI);
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002286 bool haveStylusButtons = device->keyBitmask.test(BTN_STYLUS) ||
2287 device->keyBitmask.test(BTN_STYLUS2) || device->keyBitmask.test(BTN_STYLUS3);
2288 if (haveKeyboardKeys || haveGamepadButtons || haveStylusButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002289 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002290 }
2291
2292 // See if this is a cursor device such as a trackball or mouse.
Chris Ye66fbac32020-07-06 20:36:43 -07002293 if (device->keyBitmask.test(BTN_MOUSE) && device->relBitmask.test(REL_X) &&
2294 device->relBitmask.test(REL_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002295 device->classes |= InputDeviceClass::CURSOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002296 }
2297
Prabir Pradhana3621852022-10-14 18:57:23 +00002298 // See if the device is specially configured to be of a certain type.
Harry Cuttsf13161a2023-03-08 14:15:49 +00002299 if (device->configuration) {
2300 std::string deviceType = device->configuration->getString("device.type").value_or("");
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07002301 if (deviceType == "rotaryEncoder") {
Chris Ye1b0c7342020-07-28 21:57:03 -07002302 device->classes |= InputDeviceClass::ROTARY_ENCODER;
Prabir Pradhana3621852022-10-14 18:57:23 +00002303 } else if (deviceType == "externalStylus") {
2304 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002305 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002306 }
2307
Michael Wrightd02c5b62014-02-10 15:10:22 -08002308 // See if this is a touch pad.
2309 // Is this a new modern multi-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002310 if (device->absBitmask.test(ABS_MT_POSITION_X) && device->absBitmask.test(ABS_MT_POSITION_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002311 // Some joysticks such as the PS3 controller report axes that conflict
2312 // with the ABS_MT range. Try to confirm that the device really is
2313 // a touch screen.
Chris Ye66fbac32020-07-06 20:36:43 -07002314 if (device->keyBitmask.test(BTN_TOUCH) || !haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002315 device->classes |= (InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT);
Harry Cutts79cc9fa2022-10-28 15:32:39 +00002316 if (device->propBitmask.test(INPUT_PROP_POINTER) &&
2317 !device->keyBitmask.any(BTN_TOOL_PEN, BTN_TOOL_FINGER) && !haveStylusButtons) {
2318 device->classes |= InputDeviceClass::TOUCHPAD;
2319 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002320 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002321 // Is this an old style single-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002322 } else if (device->keyBitmask.test(BTN_TOUCH) && device->absBitmask.test(ABS_X) &&
2323 device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002324 device->classes |= InputDeviceClass::TOUCH;
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002325 // Is this a stylus that reports contact/pressure independently of touch coordinates?
Chris Ye66fbac32020-07-06 20:36:43 -07002326 } else if ((device->absBitmask.test(ABS_PRESSURE) || device->keyBitmask.test(BTN_TOUCH)) &&
2327 !device->absBitmask.test(ABS_X) && !device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002328 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002329 }
2330
2331 // See if this device is a joystick.
2332 // Assumes that joysticks always have gamepad buttons in order to distinguish them
2333 // from other devices such as accelerometers that also have absolute axes.
2334 if (haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002335 auto assumedClasses = device->classes | InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002336 for (int i = 0; i <= ABS_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002337 if (device->absBitmask.test(i) &&
Chris Ye1b0c7342020-07-28 21:57:03 -07002338 (getAbsAxisUsage(i, assumedClasses).test(InputDeviceClass::JOYSTICK))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002339 device->classes = assumedClasses;
2340 break;
2341 }
2342 }
2343 }
2344
Chris Yef59a2f42020-10-16 12:55:26 -07002345 // Check whether this device is an accelerometer.
2346 if (device->propBitmask.test(INPUT_PROP_ACCELEROMETER)) {
2347 device->classes |= InputDeviceClass::SENSOR;
2348 }
2349
Michael Wrightd02c5b62014-02-10 15:10:22 -08002350 // Check whether this device has switches.
2351 for (int i = 0; i <= SW_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002352 if (device->swBitmask.test(i)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002353 device->classes |= InputDeviceClass::SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002354 break;
2355 }
2356 }
2357
2358 // Check whether this device supports the vibrator.
Chris Ye66fbac32020-07-06 20:36:43 -07002359 if (device->ffBitmask.test(FF_RUMBLE)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002360 device->classes |= InputDeviceClass::VIBRATOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002361 }
2362
2363 // Configure virtual keys.
Chris Ye1b0c7342020-07-28 21:57:03 -07002364 if ((device->classes.test(InputDeviceClass::TOUCH))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002365 // Load the virtual keys for the touch screen, if any.
2366 // We do this now so that we can make sure to load the keymap if necessary.
Chris Ye989bb932020-07-04 16:18:59 -07002367 bool success = device->loadVirtualKeyMapLocked();
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06002368 if (success) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002369 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002370 }
2371 }
2372
2373 // Load the key map.
Chris Yef59a2f42020-10-16 12:55:26 -07002374 // We need to do this for joysticks too because the key layout may specify axes, and for
2375 // sensor as well because the key layout may specify the axes to sensor data mapping.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002376 status_t keyMapStatus = NAME_NOT_FOUND;
Chris Yef59a2f42020-10-16 12:55:26 -07002377 if (device->classes.any(InputDeviceClass::KEYBOARD | InputDeviceClass::JOYSTICK |
2378 InputDeviceClass::SENSOR)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002379 // Load the keymap for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002380 keyMapStatus = device->loadKeyMapLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002381 }
2382
2383 // Configure the keyboard, gamepad or virtual keyboard.
Chris Ye1b0c7342020-07-28 21:57:03 -07002384 if (device->classes.test(InputDeviceClass::KEYBOARD)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002385 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002386 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002387 isEligibleBuiltInKeyboard(device->identifier, device->configuration.get(),
2388 &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002389 mBuiltInKeyboardId = device->id;
2390 }
2391
2392 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
Chris Ye989bb932020-07-04 16:18:59 -07002393 if (device->hasKeycodeLocked(AKEYCODE_Q)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002394 device->classes |= InputDeviceClass::ALPHAKEY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002395 }
2396
2397 // See if this device has a DPAD.
Chris Ye989bb932020-07-04 16:18:59 -07002398 if (device->hasKeycodeLocked(AKEYCODE_DPAD_UP) &&
2399 device->hasKeycodeLocked(AKEYCODE_DPAD_DOWN) &&
2400 device->hasKeycodeLocked(AKEYCODE_DPAD_LEFT) &&
2401 device->hasKeycodeLocked(AKEYCODE_DPAD_RIGHT) &&
2402 device->hasKeycodeLocked(AKEYCODE_DPAD_CENTER)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002403 device->classes |= InputDeviceClass::DPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002404 }
2405
2406 // See if this device has a gamepad.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002407 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES) / sizeof(GAMEPAD_KEYCODES[0]); i++) {
Chris Ye989bb932020-07-04 16:18:59 -07002408 if (device->hasKeycodeLocked(GAMEPAD_KEYCODES[i])) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002409 device->classes |= InputDeviceClass::GAMEPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002410 break;
2411 }
2412 }
Prabir Pradhana3621852022-10-14 18:57:23 +00002413
2414 // See if this device has any stylus buttons that we would want to fuse with touch data.
2415 if (!device->classes.any(InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT)) {
2416 for (int32_t keycode : STYLUS_BUTTON_KEYCODES) {
2417 if (device->hasKeycodeLocked(keycode)) {
2418 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
2419 break;
2420 }
2421 }
2422 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002423 }
2424
2425 // If the device isn't recognized as something we handle, don't monitor it.
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002426 if (device->classes == ftl::Flags<InputDeviceClass>(0)) {
Chris Ye8594e192020-07-14 10:34:06 -07002427 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002428 device->identifier.name.c_str());
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002429 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002430 }
2431
Chris Ye3fdbfef2021-01-06 18:45:18 -08002432 // Classify InputDeviceClass::BATTERY.
Prabir Pradhan51894782022-08-23 16:29:10 +00002433 if (device->associatedDevice && !device->associatedDevice->batteryInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002434 device->classes |= InputDeviceClass::BATTERY;
2435 }
Kim Low03ea0352020-11-06 12:45:07 -08002436
Chris Ye3fdbfef2021-01-06 18:45:18 -08002437 // Classify InputDeviceClass::LIGHT.
Prabir Pradhan51894782022-08-23 16:29:10 +00002438 if (device->associatedDevice && !device->associatedDevice->lightInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002439 device->classes |= InputDeviceClass::LIGHT;
Kim Low03ea0352020-11-06 12:45:07 -08002440 }
2441
Tim Kilbourn063ff532015-04-08 10:26:18 -07002442 // Determine whether the device has a mic.
Chris Ye989bb932020-07-04 16:18:59 -07002443 if (device->deviceHasMicLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002444 device->classes |= InputDeviceClass::MIC;
Tim Kilbourn063ff532015-04-08 10:26:18 -07002445 }
2446
Michael Wrightd02c5b62014-02-10 15:10:22 -08002447 // Determine whether the device is external or internal.
Chris Ye989bb932020-07-04 16:18:59 -07002448 if (device->isExternalDeviceLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002449 device->classes |= InputDeviceClass::EXTERNAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002450 }
2451
Chris Ye1b0c7342020-07-28 21:57:03 -07002452 if (device->classes.any(InputDeviceClass::JOYSTICK | InputDeviceClass::DPAD) &&
2453 device->classes.test(InputDeviceClass::GAMEPAD)) {
Chris Ye989bb932020-07-04 16:18:59 -07002454 device->controllerNumber = getNextControllerNumberLocked(device->identifier.name);
2455 device->setLedForControllerLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002456 }
2457
Chris Ye989bb932020-07-04 16:18:59 -07002458 if (registerDeviceForEpollLocked(*device) != OK) {
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002459 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002460 }
2461
Chris Ye989bb932020-07-04 16:18:59 -07002462 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002463
Chris Ye1b0c7342020-07-28 21:57:03 -07002464 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=%s, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002465 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Chris Ye1b0c7342020-07-28 21:57:03 -07002466 deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(),
2467 device->classes.string().c_str(), device->configurationFile.c_str(),
2468 device->keyMap.keyLayoutFile.c_str(), device->keyMap.keyCharacterMapFile.c_str(),
2469 toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002470
Chris Ye989bb932020-07-04 16:18:59 -07002471 addDeviceLocked(std::move(device));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002472}
2473
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002474void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
2475 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
2476 if (!videoDevice) {
2477 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
2478 return;
2479 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002480 // Transfer ownership of this video device to a matching input device
Chris Ye989bb932020-07-04 16:18:59 -07002481 for (const auto& [id, device] : mDevices) {
Chris Yed3fef462021-03-07 17:10:08 -08002482 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002483 return; // 'device' now owns 'videoDevice'
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002484 }
2485 }
2486
2487 // Couldn't find a matching input device, so just add it to a temporary holding queue.
2488 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002489 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002490 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002491 mUnattachedVideoDevices.push_back(std::move(videoDevice));
2492}
2493
Chris Yed3fef462021-03-07 17:10:08 -08002494bool EventHub::tryAddVideoDeviceLocked(EventHub::Device& device,
2495 std::unique_ptr<TouchVideoDevice>& videoDevice) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002496 if (videoDevice->getName() != device.identifier.name) {
2497 return false;
2498 }
2499 device.videoDevice = std::move(videoDevice);
2500 if (device.enabled) {
2501 registerVideoDeviceForEpollLocked(*device.videoDevice);
2502 }
2503 return true;
2504}
2505
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002506bool EventHub::isDeviceEnabled(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00002507 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002508 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002509 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002510 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2511 return false;
2512 }
2513 return device->enabled;
2514}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002515
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002516status_t EventHub::enableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002517 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002518 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002519 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002520 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2521 return BAD_VALUE;
2522 }
2523 if (device->enabled) {
2524 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
2525 return OK;
2526 }
2527 status_t result = device->enable();
2528 if (result != OK) {
2529 ALOGE("Failed to enable device %" PRId32, deviceId);
2530 return result;
2531 }
2532
Chris Ye989bb932020-07-04 16:18:59 -07002533 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002534
Chris Ye989bb932020-07-04 16:18:59 -07002535 return registerDeviceForEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002536}
2537
2538status_t EventHub::disableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002539 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002540 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002541 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002542 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2543 return BAD_VALUE;
2544 }
2545 if (!device->enabled) {
2546 ALOGW("Duplicate call to %s, input device already disabled", __func__);
2547 return OK;
2548 }
Chris Ye989bb932020-07-04 16:18:59 -07002549 unregisterDeviceFromEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002550 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002551}
2552
Vaibhav Devmurari5fc7d852023-03-17 18:43:33 +00002553// TODO(b/274755573): Shift to uevent handling on native side and remove this method
2554// Currently using Java UEventObserver to trigger this which uses UEvent infrastructure that uses a
2555// NETLINK socket to observe UEvents. We can create similar infrastructure on Eventhub side to
2556// directly observe UEvents instead of triggering from Java side.
2557void EventHub::sysfsNodeChanged(const std::string& sysfsNodePath) {
2558 std::scoped_lock _l(mLock);
2559
2560 // Check in opening devices
2561 for (auto it = mOpeningDevices.begin(); it != mOpeningDevices.end(); it++) {
2562 std::unique_ptr<Device>& device = *it;
2563 if (device->associatedDevice &&
2564 sysfsNodePath.find(device->associatedDevice->sysfsRootPath.string()) !=
2565 std::string::npos &&
2566 device->associatedDevice->isChanged()) {
2567 it = mOpeningDevices.erase(it);
2568 openDeviceLocked(device->path);
2569 }
2570 }
2571
2572 // Check in already added device
2573 std::vector<Device*> devicesToReopen;
2574 for (const auto& [id, device] : mDevices) {
2575 if (device->associatedDevice &&
2576 sysfsNodePath.find(device->associatedDevice->sysfsRootPath.string()) !=
2577 std::string::npos &&
2578 device->associatedDevice->isChanged()) {
2579 devicesToReopen.push_back(device.get());
2580 }
2581 }
2582 for (const auto& device : devicesToReopen) {
2583 closeDeviceLocked(*device);
2584 openDeviceLocked(device->path);
2585 }
2586 devicesToReopen.clear();
2587}
2588
Michael Wrightd02c5b62014-02-10 15:10:22 -08002589void EventHub::createVirtualKeyboardLocked() {
2590 InputDeviceIdentifier identifier;
2591 identifier.name = "Virtual";
2592 identifier.uniqueId = "<virtual>";
2593 assignDescriptorLocked(identifier);
2594
Chris Ye989bb932020-07-04 16:18:59 -07002595 std::unique_ptr<Device> device =
2596 std::make_unique<Device>(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
Harry Cutts33476232023-01-30 19:57:29 +00002597 identifier, /*associatedDevice=*/nullptr);
Chris Ye1b0c7342020-07-28 21:57:03 -07002598 device->classes = InputDeviceClass::KEYBOARD | InputDeviceClass::ALPHAKEY |
2599 InputDeviceClass::DPAD | InputDeviceClass::VIRTUAL;
Chris Ye989bb932020-07-04 16:18:59 -07002600 device->loadKeyMapLocked();
2601 addDeviceLocked(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002602}
2603
Chris Ye989bb932020-07-04 16:18:59 -07002604void EventHub::addDeviceLocked(std::unique_ptr<Device> device) {
Chris Yed3fef462021-03-07 17:10:08 -08002605 reportDeviceAddedForStatisticsLocked(device->identifier, device->classes);
Chris Ye989bb932020-07-04 16:18:59 -07002606 mOpeningDevices.push_back(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002607}
2608
Chris Ye989bb932020-07-04 16:18:59 -07002609int32_t EventHub::getNextControllerNumberLocked(const std::string& name) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002610 if (mControllerNumbers.isFull()) {
2611 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Chris Ye989bb932020-07-04 16:18:59 -07002612 name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002613 return 0;
2614 }
2615 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
2616 // one
2617 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
2618}
2619
Chris Ye989bb932020-07-04 16:18:59 -07002620void EventHub::releaseControllerNumberLocked(int32_t num) {
2621 if (num > 0) {
2622 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002623 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002624}
2625
Chris Ye8594e192020-07-14 10:34:06 -07002626void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002627 Device* device = getDeviceByPathLocked(devicePath);
Chris Ye989bb932020-07-04 16:18:59 -07002628 if (device != nullptr) {
2629 closeDeviceLocked(*device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002630 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002631 }
Chris Ye8594e192020-07-14 10:34:06 -07002632 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002633}
2634
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002635/**
2636 * Find the video device by filename, and close it.
2637 * The video device is closed by path during an inotify event, where we don't have the
2638 * additional context about the video device fd, or the associated input device.
2639 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002640void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002641 // A video device may be owned by an existing input device, or it may be stored in
2642 // the mUnattachedVideoDevices queue. Check both locations.
Chris Ye989bb932020-07-04 16:18:59 -07002643 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002644 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002645 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002646 device->videoDevice = nullptr;
2647 return;
2648 }
2649 }
Siarhei Vishniakouf47c339e2021-12-30 11:22:26 -08002650 std::erase_if(mUnattachedVideoDevices,
2651 [&devicePath](const std::unique_ptr<TouchVideoDevice>& videoDevice) {
2652 return videoDevice->getPath() == devicePath;
2653 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08002654}
2655
2656void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002657 mUnattachedVideoDevices.clear();
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002658 while (!mDevices.empty()) {
2659 closeDeviceLocked(*(mDevices.begin()->second));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002660 }
2661}
2662
Chris Ye989bb932020-07-04 16:18:59 -07002663void EventHub::closeDeviceLocked(Device& device) {
2664 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=%s", device.path.c_str(),
2665 device.identifier.name.c_str(), device.id, device.fd, device.classes.string().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002666
Chris Ye989bb932020-07-04 16:18:59 -07002667 if (device.id == mBuiltInKeyboardId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002668 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Chris Ye989bb932020-07-04 16:18:59 -07002669 device.path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002670 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
2671 }
2672
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002673 unregisterDeviceFromEpollLocked(device);
Chris Ye989bb932020-07-04 16:18:59 -07002674 if (device.videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002675 // This must be done after the video device is removed from epoll
Chris Ye989bb932020-07-04 16:18:59 -07002676 mUnattachedVideoDevices.push_back(std::move(device.videoDevice));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002677 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002678
Chris Ye989bb932020-07-04 16:18:59 -07002679 releaseControllerNumberLocked(device.controllerNumber);
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002680 device.controllerNumber = 0;
Chris Ye989bb932020-07-04 16:18:59 -07002681 device.close();
Chris Ye989bb932020-07-04 16:18:59 -07002682 mClosingDevices.push_back(std::move(mDevices[device.id]));
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002683
Chris Ye989bb932020-07-04 16:18:59 -07002684 mDevices.erase(device.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002685}
2686
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002687base::Result<void> EventHub::readNotifyLocked() {
2688 static constexpr auto EVENT_SIZE = static_cast<ssize_t>(sizeof(inotify_event));
2689 uint8_t eventBuffer[512];
2690 ssize_t sizeRead;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002691
2692 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002693 do {
2694 sizeRead = read(mINotifyFd, eventBuffer, sizeof(eventBuffer));
2695 } while (sizeRead < 0 && errno == EINTR);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002696
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002697 if (sizeRead < EVENT_SIZE) return Errorf("could not get event, %s", strerror(errno));
2698
2699 for (ssize_t eventPos = 0; sizeRead >= EVENT_SIZE;) {
2700 const inotify_event* event;
2701 event = (const inotify_event*)(eventBuffer + eventPos);
2702 if (event->len == 0) continue;
2703
2704 handleNotifyEventLocked(*event);
2705
2706 const ssize_t eventSize = EVENT_SIZE + event->len;
2707 sizeRead -= eventSize;
2708 eventPos += eventSize;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002709 }
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002710 return {};
2711}
2712
2713void EventHub::handleNotifyEventLocked(const inotify_event& event) {
2714 if (event.wd == mDeviceInputWd) {
2715 std::string filename = std::string(DEVICE_INPUT_PATH) + "/" + event.name;
2716 if (event.mask & IN_CREATE) {
2717 openDeviceLocked(filename);
2718 } else {
2719 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
2720 closeDeviceByPathLocked(filename);
2721 }
2722 } else if (event.wd == mDeviceWd) {
2723 if (isV4lTouchNode(event.name)) {
2724 std::string filename = std::string(DEVICE_PATH) + "/" + event.name;
2725 if (event.mask & IN_CREATE) {
2726 openVideoDeviceLocked(filename);
2727 } else {
2728 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
2729 closeVideoDeviceByPathLocked(filename);
2730 }
2731 } else if (strcmp(event.name, "input") == 0 && event.mask & IN_CREATE) {
2732 addDeviceInputInotify();
2733 }
2734 } else {
2735 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event.wd);
2736 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002737}
2738
Chris Ye8594e192020-07-14 10:34:06 -07002739status_t EventHub::scanDirLocked(const std::string& dirname) {
2740 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2741 openDeviceLocked(entry.path());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002742 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002743 return 0;
2744}
2745
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002746/**
2747 * Look for all dirname/v4l-touch* devices, and open them.
2748 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002749status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Chris Ye8594e192020-07-14 10:34:06 -07002750 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2751 if (isV4lTouchNode(entry.path())) {
2752 ALOGI("Found touch video device %s", entry.path().c_str());
2753 openVideoDeviceLocked(entry.path());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002754 }
2755 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002756 return OK;
2757}
2758
Michael Wrightd02c5b62014-02-10 15:10:22 -08002759void EventHub::requestReopenDevices() {
2760 ALOGV("requestReopenDevices() called");
2761
Chris Ye87143712020-11-10 05:05:58 +00002762 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002763 mNeedToReopenDevices = true;
2764}
2765
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002766void EventHub::dump(std::string& dump) const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002767 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002768
2769 { // acquire lock
Chris Ye87143712020-11-10 05:05:58 +00002770 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002771
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002772 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002773
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002774 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002775
Chris Ye989bb932020-07-04 16:18:59 -07002776 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002777 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002778 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002779 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002780 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002781 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002782 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002783 }
Chris Ye1b0c7342020-07-28 21:57:03 -07002784 dump += StringPrintf(INDENT3 "Classes: %s\n", device->classes.string().c_str());
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002785 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002786 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002787 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
2788 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002789 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002790 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002791 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002792 "product=0x%04x, version=0x%04x, bluetoothAddress=%s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002793 device->identifier.bus, device->identifier.vendor,
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002794 device->identifier.product, device->identifier.version,
2795 toString(device->identifier.bluetoothAddress).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002796 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002797 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002798 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002799 device->keyMap.keyCharacterMapFile.c_str());
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00002800 if (device->associatedDevice && device->associatedDevice->layoutInfo) {
2801 dump += StringPrintf(INDENT3 "LanguageTag: %s\n",
2802 device->associatedDevice->layoutInfo->languageTag.c_str());
2803 dump += StringPrintf(INDENT3 "LayoutType: %s\n",
2804 device->associatedDevice->layoutInfo->layoutType.c_str());
2805 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002806 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002807 device->configurationFile.c_str());
Prabir Pradhan51894782022-08-23 16:29:10 +00002808 dump += StringPrintf(INDENT3 "VideoDevice: %s\n",
2809 device->videoDevice ? device->videoDevice->dump().c_str()
2810 : "<none>");
2811 dump += StringPrintf(INDENT3 "SysfsDevicePath: %s\n",
2812 device->associatedDevice
2813 ? device->associatedDevice->sysfsRootPath.c_str()
2814 : "<none>");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002815 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002816
2817 dump += INDENT "Unattached video devices:\n";
2818 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
2819 dump += INDENT2 + videoDevice->dump() + "\n";
2820 }
2821 if (mUnattachedVideoDevices.empty()) {
2822 dump += INDENT2 "<none>\n";
2823 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002824 } // release lock
2825}
2826
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002827void EventHub::monitor() const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002828 // Acquire and release the lock to ensure that the event hub has not deadlocked.
Chris Ye1c2e0892020-11-30 21:41:44 -08002829 std::unique_lock<std::mutex> lock(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002830}
2831
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00002832std::string EventHub::AssociatedDevice::dump() const {
2833 return StringPrintf("path=%s, numBatteries=%zu, numLight=%zu", sysfsRootPath.c_str(),
2834 batteryInfos.size(), lightInfos.size());
2835}
2836
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002837} // namespace android