blob: 4d0e13ed2f88f5feeca17ff3c0e7460898b957ee [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
Prabir Pradhanae10ee62023-05-12 19:44:18 +000061#include "KeyCodeClassifications.h"
62
Michael Wrightd02c5b62014-02-10 15:10:22 -080063#define INDENT " "
64#define INDENT2 " "
65#define INDENT3 " "
66
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080067using android::base::StringPrintf;
68
Michael Wrightd02c5b62014-02-10 15:10:22 -080069namespace android {
70
Dominik Laskowski2f01d772022-03-23 16:01:29 -070071using namespace ftl::flag_operators;
72
Usama Arifb27c8e62021-06-03 16:44:09 +010073static const char* DEVICE_INPUT_PATH = "/dev/input";
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080074// v4l2 devices go directly into /dev
Usama Arifb27c8e62021-06-03 16:44:09 +010075static const char* DEVICE_PATH = "/dev";
Michael Wrightd02c5b62014-02-10 15:10:22 -080076
Chris Ye657c2f02021-05-25 16:24:37 -070077static constexpr size_t OBFUSCATED_LENGTH = 8;
78
Chris Ye87143712020-11-10 05:05:58 +000079static constexpr int32_t FF_STRONG_MAGNITUDE_CHANNEL_IDX = 0;
80static constexpr int32_t FF_WEAK_MAGNITUDE_CHANNEL_IDX = 1;
Chris Ye6393a262020-08-04 19:41:36 -070081
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -070082static constexpr size_t EVENT_BUFFER_SIZE = 256;
83
Chris Yee2b1e5c2021-03-10 22:45:12 -080084// Mapping for input battery class node IDs lookup.
85// https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
86static const std::unordered_map<std::string, InputBatteryClass> BATTERY_CLASSES =
87 {{"capacity", InputBatteryClass::CAPACITY},
88 {"capacity_level", InputBatteryClass::CAPACITY_LEVEL},
89 {"status", InputBatteryClass::STATUS}};
90
91// Mapping for input battery class node names lookup.
92// https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
93static const std::unordered_map<InputBatteryClass, std::string> BATTERY_NODES =
94 {{InputBatteryClass::CAPACITY, "capacity"},
95 {InputBatteryClass::CAPACITY_LEVEL, "capacity_level"},
96 {InputBatteryClass::STATUS, "status"}};
97
Kim Low03ea0352020-11-06 12:45:07 -080098// must be kept in sync with definitions in kernel /drivers/power/supply/power_supply_sysfs.c
99static const std::unordered_map<std::string, int32_t> BATTERY_STATUS =
100 {{"Unknown", BATTERY_STATUS_UNKNOWN},
101 {"Charging", BATTERY_STATUS_CHARGING},
102 {"Discharging", BATTERY_STATUS_DISCHARGING},
103 {"Not charging", BATTERY_STATUS_NOT_CHARGING},
104 {"Full", BATTERY_STATUS_FULL}};
105
106// Mapping taken from
107// https://gitlab.freedesktop.org/upower/upower/-/blob/master/src/linux/up-device-supply.c#L484
108static const std::unordered_map<std::string, int32_t> BATTERY_LEVEL = {{"Critical", 5},
109 {"Low", 10},
110 {"Normal", 55},
111 {"High", 70},
112 {"Full", 100},
113 {"Unknown", 50}};
114
Chris Ye3fdbfef2021-01-06 18:45:18 -0800115// Mapping for input led class node names lookup.
116// https://www.kernel.org/doc/html/latest/leds/leds-class.html
117static const std::unordered_map<std::string, InputLightClass> LIGHT_CLASSES =
118 {{"red", InputLightClass::RED},
119 {"green", InputLightClass::GREEN},
120 {"blue", InputLightClass::BLUE},
121 {"global", InputLightClass::GLOBAL},
122 {"brightness", InputLightClass::BRIGHTNESS},
123 {"multi_index", InputLightClass::MULTI_INDEX},
124 {"multi_intensity", InputLightClass::MULTI_INTENSITY},
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000125 {"max_brightness", InputLightClass::MAX_BRIGHTNESS},
126 {"kbd_backlight", InputLightClass::KEYBOARD_BACKLIGHT}};
Chris Ye3fdbfef2021-01-06 18:45:18 -0800127
128// Mapping for input multicolor led class node names.
129// https://www.kernel.org/doc/html/latest/leds/leds-class-multicolor.html
130static const std::unordered_map<InputLightClass, std::string> LIGHT_NODES =
131 {{InputLightClass::BRIGHTNESS, "brightness"},
132 {InputLightClass::MULTI_INDEX, "multi_index"},
133 {InputLightClass::MULTI_INTENSITY, "multi_intensity"}};
134
135// Mapping for light color name and the light color
136const std::unordered_map<std::string, LightColor> LIGHT_COLORS = {{"red", LightColor::RED},
137 {"green", LightColor::GREEN},
138 {"blue", LightColor::BLUE}};
139
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000140// Mapping for country code to Layout info.
141// See bCountryCode in 6.2.1 of https://usb.org/sites/default/files/hid1_11.pdf.
142const std::unordered_map<std::int32_t, RawLayoutInfo> LAYOUT_INFOS =
143 {{0, RawLayoutInfo{.languageTag = "", .layoutType = ""}}, // NOT_SUPPORTED
144 {1, RawLayoutInfo{.languageTag = "ar-Arab", .layoutType = ""}}, // ARABIC
145 {2, RawLayoutInfo{.languageTag = "fr-BE", .layoutType = ""}}, // BELGIAN
146 {3, RawLayoutInfo{.languageTag = "fr-CA", .layoutType = ""}}, // CANADIAN_BILINGUAL
147 {4, RawLayoutInfo{.languageTag = "fr-CA", .layoutType = ""}}, // CANADIAN_FRENCH
148 {5, RawLayoutInfo{.languageTag = "cs", .layoutType = ""}}, // CZECH_REPUBLIC
149 {6, RawLayoutInfo{.languageTag = "da", .layoutType = ""}}, // DANISH
150 {7, RawLayoutInfo{.languageTag = "fi", .layoutType = ""}}, // FINNISH
151 {8, RawLayoutInfo{.languageTag = "fr-FR", .layoutType = ""}}, // FRENCH
152 {9, RawLayoutInfo{.languageTag = "de", .layoutType = ""}}, // GERMAN
153 {10, RawLayoutInfo{.languageTag = "el", .layoutType = ""}}, // GREEK
154 {11, RawLayoutInfo{.languageTag = "iw", .layoutType = ""}}, // HEBREW
155 {12, RawLayoutInfo{.languageTag = "hu", .layoutType = ""}}, // HUNGARY
156 {13, RawLayoutInfo{.languageTag = "en", .layoutType = "extended"}}, // INTERNATIONAL (ISO)
157 {14, RawLayoutInfo{.languageTag = "it", .layoutType = ""}}, // ITALIAN
158 {15, RawLayoutInfo{.languageTag = "ja", .layoutType = ""}}, // JAPAN
159 {16, RawLayoutInfo{.languageTag = "ko", .layoutType = ""}}, // KOREAN
160 {17, RawLayoutInfo{.languageTag = "es-419", .layoutType = ""}}, // LATIN_AMERICA
161 {18, RawLayoutInfo{.languageTag = "nl", .layoutType = ""}}, // DUTCH
162 {19, RawLayoutInfo{.languageTag = "nb", .layoutType = ""}}, // NORWEGIAN
163 {20, RawLayoutInfo{.languageTag = "fa", .layoutType = ""}}, // PERSIAN
164 {21, RawLayoutInfo{.languageTag = "pl", .layoutType = ""}}, // POLAND
165 {22, RawLayoutInfo{.languageTag = "pt", .layoutType = ""}}, // PORTUGUESE
166 {23, RawLayoutInfo{.languageTag = "ru", .layoutType = ""}}, // RUSSIA
167 {24, RawLayoutInfo{.languageTag = "sk", .layoutType = ""}}, // SLOVAKIA
168 {25, RawLayoutInfo{.languageTag = "es-ES", .layoutType = ""}}, // SPANISH
169 {26, RawLayoutInfo{.languageTag = "sv", .layoutType = ""}}, // SWEDISH
170 {27, RawLayoutInfo{.languageTag = "fr-CH", .layoutType = ""}}, // SWISS_FRENCH
171 {28, RawLayoutInfo{.languageTag = "de-CH", .layoutType = ""}}, // SWISS_GERMAN
172 {29, RawLayoutInfo{.languageTag = "de-CH", .layoutType = ""}}, // SWITZERLAND
173 {30, RawLayoutInfo{.languageTag = "zh-TW", .layoutType = ""}}, // TAIWAN
174 {31, RawLayoutInfo{.languageTag = "tr", .layoutType = "turkish_q"}}, // TURKISH_Q
175 {32, RawLayoutInfo{.languageTag = "en-GB", .layoutType = ""}}, // UK
176 {33, RawLayoutInfo{.languageTag = "en-US", .layoutType = ""}}, // US
177 {34, RawLayoutInfo{.languageTag = "", .layoutType = ""}}, // YUGOSLAVIA
178 {35, RawLayoutInfo{.languageTag = "tr", .layoutType = "turkish_f"}}}; // TURKISH_F
179
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100180static std::string sha1(const std::string& in) {
Dan Albert677d87e2014-06-16 17:31:28 -0700181 SHA_CTX ctx;
182 SHA1_Init(&ctx);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100183 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
Dan Albert677d87e2014-06-16 17:31:28 -0700184 u_char digest[SHA_DIGEST_LENGTH];
185 SHA1_Final(digest, &ctx);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800186
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100187 std::string out;
Dan Albert677d87e2014-06-16 17:31:28 -0700188 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100189 out += StringPrintf("%02x", digest[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800190 }
191 return out;
192}
193
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800194/**
195 * Return true if name matches "v4l-touch*"
196 */
Chris Ye8594e192020-07-14 10:34:06 -0700197static bool isV4lTouchNode(std::string name) {
198 return name.find("v4l-touch") != std::string::npos;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800199}
200
Philip Quinn39b81682019-01-09 22:20:39 -0800201/**
202 * Returns true if V4L devices should be scanned.
203 *
204 * The system property ro.input.video_enabled can be used to control whether
205 * EventHub scans and opens V4L devices. As V4L does not support multiple
206 * clients, EventHub effectively blocks access to these devices when it opens
Siarhei Vishniakou29f88492019-04-05 14:11:43 -0700207 * them.
208 *
209 * Setting this to "false" would prevent any video devices from being discovered and
210 * associated with input devices.
211 *
212 * This property can be used as follows:
213 * 1. To turn off features that are dependent on video device presence.
214 * 2. During testing and development, to allow other clients to read video devices
215 * directly from /dev.
Philip Quinn39b81682019-01-09 22:20:39 -0800216 */
217static bool isV4lScanningEnabled() {
Harry Cutts33476232023-01-30 19:57:29 +0000218 return property_get_bool("ro.input.video_enabled", /*default_value=*/true);
Philip Quinn39b81682019-01-09 22:20:39 -0800219}
220
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800221static nsecs_t processEventTimestamp(const struct input_event& event) {
222 // Use the time specified in the event instead of the current time
223 // so that downstream code can get more accurate estimates of
224 // event dispatch latency from the time the event is enqueued onto
225 // the evdev client buffer.
226 //
227 // The event's timestamp fortuitously uses the same monotonic clock
228 // time base as the rest of Android. The kernel event device driver
229 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
230 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
231 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
232 // system call that also queries ktime_get_ts().
233
Colin Cross5b799302022-10-18 21:52:41 -0700234 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.input_event_sec) +
235 microseconds_to_nanoseconds(event.input_event_usec);
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800236 return inputEventTime;
237}
238
Kim Low03ea0352020-11-06 12:45:07 -0800239/**
Prabir Pradhancb42b472022-08-23 16:01:19 +0000240 * Returns the sysfs root path of the input device.
Kim Low03ea0352020-11-06 12:45:07 -0800241 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800242static std::optional<std::filesystem::path> getSysfsRootPath(const char* devicePath) {
Kim Low03ea0352020-11-06 12:45:07 -0800243 std::error_code errorCode;
244
245 // Stat the device path to get the major and minor number of the character file
246 struct stat statbuf;
247 if (stat(devicePath, &statbuf) == -1) {
248 ALOGE("Could not stat device %s due to error: %s.", devicePath, std::strerror(errno));
Chris Ye3fdbfef2021-01-06 18:45:18 -0800249 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800250 }
251
252 unsigned int major_num = major(statbuf.st_rdev);
253 unsigned int minor_num = minor(statbuf.st_rdev);
254
255 // Realpath "/sys/dev/char/{major}:{minor}" to get the sysfs path to the input event
256 auto sysfsPath = std::filesystem::path("/sys/dev/char/");
257 sysfsPath /= std::to_string(major_num) + ":" + std::to_string(minor_num);
258 sysfsPath = std::filesystem::canonical(sysfsPath, errorCode);
259
260 // Make sure nothing went wrong in call to canonical()
261 if (errorCode) {
262 ALOGW("Could not run filesystem::canonical() due to error %d : %s.", errorCode.value(),
263 errorCode.message().c_str());
Chris Ye3fdbfef2021-01-06 18:45:18 -0800264 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800265 }
266
267 // Continue to go up a directory until we reach a directory named "input"
268 while (sysfsPath != "/" && sysfsPath.filename() != "input") {
269 sysfsPath = sysfsPath.parent_path();
270 }
271
272 // Then go up one more and you will be at the sysfs root of the device
273 sysfsPath = sysfsPath.parent_path();
274
275 // Make sure we didn't reach root path and that directory actually exists
276 if (sysfsPath == "/" || !std::filesystem::exists(sysfsPath, errorCode)) {
277 if (errorCode) {
278 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
279 errorCode.message().c_str());
280 }
281
282 // Not found
Chris Ye3fdbfef2021-01-06 18:45:18 -0800283 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800284 }
285
286 return sysfsPath;
287}
288
289/**
Chris Ye3fdbfef2021-01-06 18:45:18 -0800290 * Returns the list of files under a specified path.
Kim Low03ea0352020-11-06 12:45:07 -0800291 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800292static std::vector<std::filesystem::path> allFilesInPath(const std::filesystem::path& path) {
293 std::vector<std::filesystem::path> nodes;
294 std::error_code errorCode;
295 auto iter = std::filesystem::directory_iterator(path, errorCode);
296 while (!errorCode && iter != std::filesystem::directory_iterator()) {
297 nodes.push_back(iter->path());
298 iter++;
299 }
300 return nodes;
301}
302
303/**
304 * Returns the list of files under a specified directory in a sysfs path.
305 * Example:
306 * findSysfsNodes(sysfsRootPath, SysfsClass::LEDS) will return all led nodes under "leds" directory
307 * in the sysfs path.
308 */
309static std::vector<std::filesystem::path> findSysfsNodes(const std::filesystem::path& sysfsRoot,
310 SysfsClass clazz) {
Dominik Laskowski75788452021-02-09 18:51:25 -0800311 std::string nodeStr = ftl::enum_string(clazz);
Chris Ye3fdbfef2021-01-06 18:45:18 -0800312 std::for_each(nodeStr.begin(), nodeStr.end(),
313 [](char& c) { c = std::tolower(static_cast<unsigned char>(c)); });
314 std::vector<std::filesystem::path> nodes;
315 for (auto path = sysfsRoot; path != "/" && nodes.empty(); path = path.parent_path()) {
316 nodes = allFilesInPath(path / nodeStr);
317 }
318 return nodes;
319}
320
321static std::optional<std::array<LightColor, COLOR_NUM>> getColorIndexArray(
322 std::filesystem::path path) {
323 std::string indexStr;
324 if (!base::ReadFileToString(path, &indexStr)) {
325 return std::nullopt;
326 }
327
328 // Parse the multi color LED index file, refer to kernel docs
329 // leds/leds-class-multicolor.html
330 std::regex indexPattern("(red|green|blue)\\s(red|green|blue)\\s(red|green|blue)[\\n]");
331 std::smatch results;
332 std::array<LightColor, COLOR_NUM> colors;
333 if (!std::regex_match(indexStr, results, indexPattern)) {
334 return std::nullopt;
335 }
336
337 for (size_t i = 1; i < results.size(); i++) {
338 const auto it = LIGHT_COLORS.find(results[i].str());
339 if (it != LIGHT_COLORS.end()) {
340 // intensities.emplace(it->second, 0);
341 colors[i - 1] = it->second;
Kim Low03ea0352020-11-06 12:45:07 -0800342 }
343 }
Chris Ye3fdbfef2021-01-06 18:45:18 -0800344 return colors;
Kim Low03ea0352020-11-06 12:45:07 -0800345}
346
Prabir Pradhancb42b472022-08-23 16:01:19 +0000347/**
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000348 * Read country code information exposed through the sysfs path and convert it to Layout info.
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000349 */
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000350static std::optional<RawLayoutInfo> readLayoutConfiguration(
351 const std::filesystem::path& sysfsRootPath) {
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000352 // Check the sysfs root path
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000353 int32_t hidCountryCode = -1;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000354 std::string str;
355 if (base::ReadFileToString(sysfsRootPath / "country", &str)) {
356 hidCountryCode = std::stoi(str, nullptr, 16);
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000357 // Update this condition if new supported country codes are added to HID spec.
Vaibhav Devmurari990ff7b2022-12-22 18:23:21 +0000358 if (hidCountryCode > 35 || hidCountryCode < 0) {
359 ALOGE("HID country code should be in range [0, 35], but for sysfs path %s it was %d",
360 sysfsRootPath.c_str(), hidCountryCode);
Vaibhav Devmurari990ff7b2022-12-22 18:23:21 +0000361 }
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000362 }
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000363 const auto it = LAYOUT_INFOS.find(hidCountryCode);
364 if (it != LAYOUT_INFOS.end()) {
365 return it->second;
366 }
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000367
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000368 return std::nullopt;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000369}
370
371/**
Prabir Pradhancb42b472022-08-23 16:01:19 +0000372 * Read information about batteries exposed through the sysfs path.
373 */
374static std::unordered_map<int32_t /*batteryId*/, RawBatteryInfo> readBatteryConfiguration(
375 const std::filesystem::path& sysfsRootPath) {
376 std::unordered_map<int32_t, RawBatteryInfo> batteryInfos;
377 int32_t nextBatteryId = 0;
378 // Check if device has any battery.
379 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::POWER_SUPPLY);
380 for (const auto& nodePath : paths) {
381 RawBatteryInfo info;
382 info.id = ++nextBatteryId;
383 info.path = nodePath;
384 info.name = nodePath.filename();
385
386 // Scan the path for all the files
387 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
388 const auto& files = allFilesInPath(nodePath);
389 for (const auto& file : files) {
390 const auto it = BATTERY_CLASSES.find(file.filename().string());
391 if (it != BATTERY_CLASSES.end()) {
392 info.flags |= it->second;
393 }
394 }
395 batteryInfos.insert_or_assign(info.id, info);
396 ALOGD("configureBatteryLocked rawBatteryId %d name %s", info.id, info.name.c_str());
397 }
398 return batteryInfos;
399}
400
401/**
402 * Read information about lights exposed through the sysfs path.
403 */
404static std::unordered_map<int32_t /*lightId*/, RawLightInfo> readLightsConfiguration(
405 const std::filesystem::path& sysfsRootPath) {
406 std::unordered_map<int32_t, RawLightInfo> lightInfos;
407 int32_t nextLightId = 0;
408 // Check if device has any lights.
409 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::LEDS);
410 for (const auto& nodePath : paths) {
411 RawLightInfo info;
412 info.id = ++nextLightId;
413 info.path = nodePath;
414 info.name = nodePath.filename();
415 info.maxBrightness = std::nullopt;
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000416
417 // Light name should follow the naming pattern <name>:<color>:<function>
418 // Refer kernel docs /leds/leds-class.html for valid supported LED names.
419 std::regex indexPattern("([a-zA-Z0-9_.:]*:)?([a-zA-Z0-9_.]*):([a-zA-Z0-9_.]*)");
420 std::smatch results;
421
422 if (std::regex_match(info.name, results, indexPattern)) {
423 // regex_match will return full match at index 0 and <name> at index 1. For RawLightInfo
424 // we only care about sections <color> and <function> which will be at index 2 and 3.
425 for (int i = 2; i <= 3; i++) {
426 const auto it = LIGHT_CLASSES.find(results.str(i));
427 if (it != LIGHT_CLASSES.end()) {
428 info.flags |= it->second;
429 }
Prabir Pradhancb42b472022-08-23 16:01:19 +0000430 }
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000431
432 // Set name of the raw light to <function> which represents playerIDs for LEDs that
433 // turn on/off based on the current player ID (Refer to PeripheralController.cpp for
434 // player ID logic)
435 info.name = results.str(3);
Prabir Pradhancb42b472022-08-23 16:01:19 +0000436 }
437 // Scan the path for all the files
438 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
439 const auto& files = allFilesInPath(nodePath);
440 for (const auto& file : files) {
441 const auto it = LIGHT_CLASSES.find(file.filename().string());
442 if (it != LIGHT_CLASSES.end()) {
443 info.flags |= it->second;
444 // If the node has maximum brightness, read it
445 if (it->second == InputLightClass::MAX_BRIGHTNESS) {
446 std::string str;
447 if (base::ReadFileToString(file, &str)) {
448 info.maxBrightness = std::stoi(str);
449 }
450 }
451 }
452 }
453 lightInfos.insert_or_assign(info.id, info);
454 ALOGD("configureLightsLocked rawLightId %d name %s", info.id, info.name.c_str());
455 }
456 return lightInfos;
457}
458
Michael Wrightd02c5b62014-02-10 15:10:22 -0800459// --- Global Functions ---
460
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700461ftl::Flags<InputDeviceClass> getAbsAxisUsage(int32_t axis,
462 ftl::Flags<InputDeviceClass> deviceClasses) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800463 // Touch devices get dibs on touch-related axes.
Chris Ye1b0c7342020-07-28 21:57:03 -0700464 if (deviceClasses.test(InputDeviceClass::TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800465 switch (axis) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700466 case ABS_X:
467 case ABS_Y:
468 case ABS_PRESSURE:
469 case ABS_TOOL_WIDTH:
470 case ABS_DISTANCE:
471 case ABS_TILT_X:
472 case ABS_TILT_Y:
473 case ABS_MT_SLOT:
474 case ABS_MT_TOUCH_MAJOR:
475 case ABS_MT_TOUCH_MINOR:
476 case ABS_MT_WIDTH_MAJOR:
477 case ABS_MT_WIDTH_MINOR:
478 case ABS_MT_ORIENTATION:
479 case ABS_MT_POSITION_X:
480 case ABS_MT_POSITION_Y:
481 case ABS_MT_TOOL_TYPE:
482 case ABS_MT_BLOB_ID:
483 case ABS_MT_TRACKING_ID:
484 case ABS_MT_PRESSURE:
485 case ABS_MT_DISTANCE:
Chris Ye1b0c7342020-07-28 21:57:03 -0700486 return InputDeviceClass::TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800487 }
488 }
489
Chris Yef59a2f42020-10-16 12:55:26 -0700490 if (deviceClasses.test(InputDeviceClass::SENSOR)) {
491 switch (axis) {
492 case ABS_X:
493 case ABS_Y:
494 case ABS_Z:
495 case ABS_RX:
496 case ABS_RY:
497 case ABS_RZ:
498 return InputDeviceClass::SENSOR;
499 }
500 }
501
Michael Wright842500e2015-03-13 17:32:02 -0700502 // External stylus gets the pressure axis
Chris Ye1b0c7342020-07-28 21:57:03 -0700503 if (deviceClasses.test(InputDeviceClass::EXTERNAL_STYLUS)) {
Michael Wright842500e2015-03-13 17:32:02 -0700504 if (axis == ABS_PRESSURE) {
Chris Ye1b0c7342020-07-28 21:57:03 -0700505 return InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -0700506 }
507 }
508
Michael Wrightd02c5b62014-02-10 15:10:22 -0800509 // Joystick devices get the rest.
Chris Ye1b0c7342020-07-28 21:57:03 -0700510 return deviceClasses & InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800511}
512
Harry Cuttsea73eaa2023-01-16 17:55:46 +0000513// --- RawAbsoluteAxisInfo ---
514
515std::ostream& operator<<(std::ostream& out, const RawAbsoluteAxisInfo& info) {
516 if (info.valid) {
517 out << "min=" << info.minValue << ", max=" << info.maxValue << ", flat=" << info.flat
518 << ", fuzz=" << info.fuzz << ", resolution=" << info.resolution;
519 } else {
520 out << "unknown range";
521 }
522 return out;
523}
524
Michael Wrightd02c5b62014-02-10 15:10:22 -0800525// --- EventHub::Device ---
526
Prabir Pradhancb42b472022-08-23 16:01:19 +0000527EventHub::Device::Device(int fd, int32_t id, std::string path, InputDeviceIdentifier identifier,
528 std::shared_ptr<const AssociatedDevice> assocDev)
Chris Ye989bb932020-07-04 16:18:59 -0700529 : fd(fd),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700530 id(id),
Prabir Pradhancb42b472022-08-23 16:01:19 +0000531 path(std::move(path)),
532 identifier(std::move(identifier)),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700533 classes(0),
534 configuration(nullptr),
535 virtualKeyMap(nullptr),
536 ffEffectPlaying(false),
537 ffEffectId(-1),
Prabir Pradhancb42b472022-08-23 16:01:19 +0000538 associatedDevice(std::move(assocDev)),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700539 controllerNumber(0),
540 enabled(true),
Chris Ye66fbac32020-07-06 20:36:43 -0700541 isVirtual(fd < 0) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800542
543EventHub::Device::~Device() {
544 close();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800545}
546
547void EventHub::Device::close() {
548 if (fd >= 0) {
549 ::close(fd);
550 fd = -1;
551 }
552}
553
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700554status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100555 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700556 if (fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100557 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700558 return -errno;
559 }
560 enabled = true;
561 return OK;
562}
563
564status_t EventHub::Device::disable() {
565 close();
566 enabled = false;
567 return OK;
568}
569
Chris Ye989bb932020-07-04 16:18:59 -0700570bool EventHub::Device::hasValidFd() const {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700571 return !isVirtual && enabled;
572}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800573
Chris Ye3a1e4462020-08-12 10:13:15 -0700574const std::shared_ptr<KeyCharacterMap> EventHub::Device::getKeyCharacterMap() const {
Chris Ye989bb932020-07-04 16:18:59 -0700575 return keyMap.keyCharacterMap;
576}
577
578template <std::size_t N>
579status_t EventHub::Device::readDeviceBitMask(unsigned long ioctlCode, BitArray<N>& bitArray) {
580 if (!hasValidFd()) {
581 return BAD_VALUE;
582 }
583 if ((_IOC_SIZE(ioctlCode) == 0)) {
584 ioctlCode |= _IOC(0, 0, 0, bitArray.bytes());
585 }
586
587 typename BitArray<N>::Buffer buffer;
588 status_t ret = ioctl(fd, ioctlCode, buffer.data());
589 bitArray.loadFromBuffer(buffer);
590 return ret;
591}
592
593void EventHub::Device::configureFd() {
594 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
595 if (classes.test(InputDeviceClass::KEYBOARD)) {
596 // Disable kernel key repeat since we handle it ourselves
597 unsigned int repeatRate[] = {0, 0};
598 if (ioctl(fd, EVIOCSREP, repeatRate)) {
599 ALOGW("Unable to disable kernel key repeat for %s: %s", path.c_str(), strerror(errno));
600 }
601 }
602
603 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
604 // associated with input events. This is important because the input system
605 // uses the timestamps extensively and assumes they were recorded using the monotonic
606 // clock.
607 int clockId = CLOCK_MONOTONIC;
Chris Yef59a2f42020-10-16 12:55:26 -0700608 if (classes.test(InputDeviceClass::SENSOR)) {
609 // Each new sensor event should use the same time base as
610 // SystemClock.elapsedRealtimeNanos().
611 clockId = CLOCK_BOOTTIME;
612 }
Chris Ye989bb932020-07-04 16:18:59 -0700613 bool usingClockIoctl = !ioctl(fd, EVIOCSCLOCKID, &clockId);
614 ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
615}
616
617bool EventHub::Device::hasKeycodeLocked(int keycode) const {
618 if (!keyMap.haveKeyLayout()) {
619 return false;
620 }
621
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700622 std::vector<int32_t> scanCodes = keyMap.keyLayoutMap->findScanCodesForKey(keycode);
Chris Ye989bb932020-07-04 16:18:59 -0700623 const size_t N = scanCodes.size();
624 for (size_t i = 0; i < N && i <= KEY_MAX; i++) {
625 int32_t sc = scanCodes[i];
626 if (sc >= 0 && sc <= KEY_MAX && keyBitmask.test(sc)) {
627 return true;
628 }
629 }
630
Charles Linaadf8d52023-03-30 13:34:54 +0800631 std::vector<int32_t> usageCodes = keyMap.keyLayoutMap->findUsageCodesForKey(keycode);
632 if (usageCodes.size() > 0 && mscBitmask.test(MSC_SCAN)) {
633 return true;
634 }
635
Chris Ye989bb932020-07-04 16:18:59 -0700636 return false;
637}
638
639void EventHub::Device::loadConfigurationLocked() {
640 configurationFile =
641 getInputDeviceConfigurationFilePathByDeviceIdentifier(identifier,
642 InputDeviceConfigurationFileType::
643 CONFIGURATION);
644 if (configurationFile.empty()) {
645 ALOGD("No input device configuration file found for device '%s'.", identifier.name.c_str());
646 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500647 android::base::Result<std::unique_ptr<PropertyMap>> propertyMap =
648 PropertyMap::load(configurationFile.c_str());
649 if (!propertyMap.ok()) {
Chris Ye989bb932020-07-04 16:18:59 -0700650 ALOGE("Error loading input device configuration file for device '%s'. "
651 "Using default configuration.",
652 identifier.name.c_str());
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500653 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500654 configuration = std::move(*propertyMap);
Chris Ye989bb932020-07-04 16:18:59 -0700655 }
656 }
657}
658
659bool EventHub::Device::loadVirtualKeyMapLocked() {
660 // The virtual key map is supplied by the kernel as a system board property file.
661 std::string propPath = "/sys/board_properties/virtualkeys.";
662 propPath += identifier.getCanonicalName();
663 if (access(propPath.c_str(), R_OK)) {
664 return false;
665 }
666 virtualKeyMap = VirtualKeyMap::load(propPath);
667 return virtualKeyMap != nullptr;
668}
669
670status_t EventHub::Device::loadKeyMapLocked() {
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500671 return keyMap.load(identifier, configuration.get());
Chris Ye989bb932020-07-04 16:18:59 -0700672}
673
674bool EventHub::Device::isExternalDeviceLocked() {
675 if (configuration) {
Harry Cuttsf13161a2023-03-08 14:15:49 +0000676 std::optional<bool> isInternal = configuration->getBool("device.internal");
677 if (isInternal.has_value()) {
678 return !isInternal.value();
Chris Ye989bb932020-07-04 16:18:59 -0700679 }
680 }
681 return identifier.bus == BUS_USB || identifier.bus == BUS_BLUETOOTH;
682}
683
684bool EventHub::Device::deviceHasMicLocked() {
685 if (configuration) {
Harry Cuttsf13161a2023-03-08 14:15:49 +0000686 std::optional<bool> hasMic = configuration->getBool("audio.mic");
687 if (hasMic.has_value()) {
688 return hasMic.value();
Chris Ye989bb932020-07-04 16:18:59 -0700689 }
690 }
691 return false;
692}
693
694void EventHub::Device::setLedStateLocked(int32_t led, bool on) {
695 int32_t sc;
696 if (hasValidFd() && mapLed(led, &sc) != NAME_NOT_FOUND) {
697 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -0700698 ev.input_event_sec = 0;
699 ev.input_event_usec = 0;
Chris Ye989bb932020-07-04 16:18:59 -0700700 ev.type = EV_LED;
701 ev.code = sc;
702 ev.value = on ? 1 : 0;
703
704 ssize_t nWrite;
705 do {
706 nWrite = write(fd, &ev, sizeof(struct input_event));
707 } while (nWrite == -1 && errno == EINTR);
708 }
709}
710
711void EventHub::Device::setLedForControllerLocked() {
712 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
713 setLedStateLocked(ALED_CONTROLLER_1 + i, controllerNumber == i + 1);
714 }
715}
716
717status_t EventHub::Device::mapLed(int32_t led, int32_t* outScanCode) const {
718 if (!keyMap.haveKeyLayout()) {
719 return NAME_NOT_FOUND;
720 }
721
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700722 std::optional<int32_t> scanCode = keyMap.keyLayoutMap->findScanCodeForLed(led);
723 if (scanCode.has_value()) {
724 if (*scanCode >= 0 && *scanCode <= LED_MAX && ledBitmask.test(*scanCode)) {
725 *outScanCode = *scanCode;
Chris Ye989bb932020-07-04 16:18:59 -0700726 return NO_ERROR;
727 }
728 }
729 return NAME_NOT_FOUND;
730}
731
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100732/**
733 * Get the capabilities for the current process.
734 * Crashes the system if unable to create / check / destroy the capabilities object.
735 */
736class Capabilities final {
737public:
738 explicit Capabilities() {
739 mCaps = cap_get_proc();
740 LOG_ALWAYS_FATAL_IF(mCaps == nullptr, "Could not get capabilities of the current process");
741 }
742
743 /**
744 * Check whether the current process has a specific capability
745 * in the set of effective capabilities.
746 * Return CAP_SET if the process has the requested capability
747 * Return CAP_CLEAR otherwise.
748 */
749 cap_flag_value_t checkEffectiveCapability(cap_value_t capability) {
750 cap_flag_value_t value;
751 const int result = cap_get_flag(mCaps, capability, CAP_EFFECTIVE, &value);
752 LOG_ALWAYS_FATAL_IF(result == -1, "Could not obtain the requested capability");
753 return value;
754 }
755
756 ~Capabilities() {
757 const int result = cap_free(mCaps);
758 LOG_ALWAYS_FATAL_IF(result == -1, "Could not release the capabilities structure");
759 }
760
761private:
762 cap_t mCaps;
763};
764
765static void ensureProcessCanBlockSuspend() {
766 Capabilities capabilities;
767 const bool canBlockSuspend =
768 capabilities.checkEffectiveCapability(CAP_BLOCK_SUSPEND) == CAP_SET;
769 LOG_ALWAYS_FATAL_IF(!canBlockSuspend,
770 "Input must be able to block suspend to properly process events");
771}
772
Michael Wrightd02c5b62014-02-10 15:10:22 -0800773// --- EventHub ---
774
Michael Wrightd02c5b62014-02-10 15:10:22 -0800775const int EventHub::EPOLL_MAX_EVENTS;
776
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700777EventHub::EventHub(void)
778 : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
779 mNextDeviceId(1),
780 mControllerNumbers(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800781 mNeedToSendFinishedDeviceScan(false),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700782 mNeedToReopenDevices(false),
783 mNeedToScanDevices(true),
784 mPendingEventCount(0),
785 mPendingEventIndex(0),
786 mPendingINotify(false) {
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100787 ensureProcessCanBlockSuspend();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800789 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800790 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800791
Michael Wright8e9a8562022-02-09 13:44:29 +0000792 mINotifyFd = inotify_init1(IN_CLOEXEC);
Prabir Pradhan952e65b2022-06-23 17:49:55 +0000793 LOG_ALWAYS_FATAL_IF(mINotifyFd < 0, "Could not create inotify instance: %s", strerror(errno));
Usama Arifb27c8e62021-06-03 16:44:09 +0100794
795 std::error_code errorCode;
796 bool isDeviceInotifyAdded = false;
797 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
798 addDeviceInputInotify();
Philip Quinn39b81682019-01-09 22:20:39 -0800799 } else {
Usama Arifb27c8e62021-06-03 16:44:09 +0100800 addDeviceInotify();
801 isDeviceInotifyAdded = true;
802 if (errorCode) {
803 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
804 errorCode.message().c_str());
805 }
806 }
807
808 if (isV4lScanningEnabled() && !isDeviceInotifyAdded) {
809 addDeviceInotify();
810 } else {
Philip Quinn39b81682019-01-09 22:20:39 -0800811 ALOGI("Video device scanning disabled");
812 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800813
Siarhei Vishniakou2d0e9482019-09-24 12:52:47 +0100814 struct epoll_event eventItem = {};
815 eventItem.events = EPOLLIN | EPOLLWAKEUP;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700816 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800817 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800818 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
819
820 int wakeFds[2];
Michael Wright8e9a8562022-02-09 13:44:29 +0000821 result = pipe2(wakeFds, O_CLOEXEC);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800822 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
823
824 mWakeReadPipeFd = wakeFds[0];
825 mWakeWritePipeFd = wakeFds[1];
826
827 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
828 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700829 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800830
831 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
832 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700833 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800834
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700835 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800836 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
837 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700838 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800839}
840
841EventHub::~EventHub(void) {
842 closeAllDevicesLocked();
843
Michael Wrightd02c5b62014-02-10 15:10:22 -0800844 ::close(mEpollFd);
845 ::close(mINotifyFd);
846 ::close(mWakeReadPipeFd);
847 ::close(mWakeWritePipeFd);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800848}
849
Usama Arifb27c8e62021-06-03 16:44:09 +0100850/**
851 * On devices that don't have any input devices (like some development boards), the /dev/input
852 * directory will be absent. However, the user may still plug in an input device at a later time.
853 * Add watch for contents of /dev/input only when /dev/input appears.
854 */
855void EventHub::addDeviceInputInotify() {
856 mDeviceInputWd = inotify_add_watch(mINotifyFd, DEVICE_INPUT_PATH, IN_DELETE | IN_CREATE);
857 LOG_ALWAYS_FATAL_IF(mDeviceInputWd < 0, "Could not register INotify for %s: %s",
858 DEVICE_INPUT_PATH, strerror(errno));
859}
860
861void EventHub::addDeviceInotify() {
862 mDeviceWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
863 LOG_ALWAYS_FATAL_IF(mDeviceWd < 0, "Could not register INotify for %s: %s", DEVICE_PATH,
864 strerror(errno));
865}
866
Arpit Singh77140f42023-06-13 11:35:27 +0000867void EventHub::populateDeviceAbsoluteAxisInfo(Device& device) {
868 for (int axis = 0; axis <= ABS_MAX; axis++) {
869 if (!device.absBitmask.test(axis)) {
870 continue;
871 }
872 struct input_absinfo info {};
873 if (ioctl(device.fd, EVIOCGABS(axis), &info)) {
874 ALOGE("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
875 device.identifier.name.c_str(), device.fd, errno);
876 continue;
877 }
878 if (info.minimum == info.maximum) {
879 continue;
880 }
881 RawAbsoluteAxisInfo& outAxisInfo = device.rawAbsoluteAxisInfoCache[axis];
882 outAxisInfo.valid = true;
883 outAxisInfo.minValue = info.minimum;
884 outAxisInfo.maxValue = info.maximum;
885 outAxisInfo.flat = info.flat;
886 outAxisInfo.fuzz = info.fuzz;
887 outAxisInfo.resolution = info.resolution;
888 }
889}
890
Michael Wrightd02c5b62014-02-10 15:10:22 -0800891InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000892 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800893 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700894 return device != nullptr ? device->identifier : InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800895}
896
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700897ftl::Flags<InputDeviceClass> EventHub::getDeviceClasses(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000898 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800899 Device* device = getDeviceLocked(deviceId);
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700900 return device != nullptr ? device->classes : ftl::Flags<InputDeviceClass>(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800901}
902
903int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000904 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800905 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700906 return device != nullptr ? device->controllerNumber : 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800907}
908
Harry Cuttsc34f7582023-03-07 16:23:30 +0000909std::optional<PropertyMap> EventHub::getConfiguration(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000910 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800911 Device* device = getDeviceLocked(deviceId);
Harry Cuttsc34f7582023-03-07 16:23:30 +0000912 if (device == nullptr || device->configuration == nullptr) {
913 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -0800914 }
Harry Cuttsc34f7582023-03-07 16:23:30 +0000915 return *device->configuration;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800916}
917
918status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700919 RawAbsoluteAxisInfo* outAxisInfo) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800920 outAxisInfo->clear();
Arpit Singh77140f42023-06-13 11:35:27 +0000921 if (axis < 0 || axis > ABS_MAX) {
922 return -1;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800923 }
Arpit Singh77140f42023-06-13 11:35:27 +0000924 std::scoped_lock _l(mLock);
925 Device* device = getDeviceLocked(deviceId);
926 if (device == nullptr) {
927 return -1;
928 }
929 auto it = device->rawAbsoluteAxisInfoCache.find(axis);
930 if (it == device->rawAbsoluteAxisInfoCache.end()) {
931 return -1;
932 }
933 *outAxisInfo = it->second;
934 return OK;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800935}
936
937bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
938 if (axis >= 0 && axis <= REL_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000939 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800940 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700941 return device != nullptr ? device->relBitmask.test(axis) : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800942 }
943 return false;
944}
945
946bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
Chris Ye87143712020-11-10 05:05:58 +0000947 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800948
Chris Ye989bb932020-07-04 16:18:59 -0700949 Device* device = getDeviceLocked(deviceId);
950 return property >= 0 && property <= INPUT_PROP_MAX && device != nullptr
951 ? device->propBitmask.test(property)
952 : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800953}
954
Chris Yef59a2f42020-10-16 12:55:26 -0700955bool EventHub::hasMscEvent(int32_t deviceId, int mscEvent) const {
956 std::scoped_lock _l(mLock);
957
958 Device* device = getDeviceLocked(deviceId);
959 return mscEvent >= 0 && mscEvent <= MSC_MAX && device != nullptr
960 ? device->mscBitmask.test(mscEvent)
961 : false;
962}
963
Michael Wrightd02c5b62014-02-10 15:10:22 -0800964int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
965 if (scanCode >= 0 && scanCode <= KEY_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000966 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800967
968 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700969 if (device != nullptr && device->hasValidFd() && device->keyBitmask.test(scanCode)) {
970 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
971 return device->keyState.test(scanCode) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800972 }
973 }
974 }
975 return AKEY_STATE_UNKNOWN;
976}
977
978int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
Chris Ye87143712020-11-10 05:05:58 +0000979 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800980
981 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700982 if (device != nullptr && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700983 std::vector<int32_t> scanCodes = device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800984 if (scanCodes.size() != 0) {
Chris Ye66fbac32020-07-06 20:36:43 -0700985 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800986 for (size_t i = 0; i < scanCodes.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800987 int32_t sc = scanCodes[i];
Chris Ye66fbac32020-07-06 20:36:43 -0700988 if (sc >= 0 && sc <= KEY_MAX && device->keyState.test(sc)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800989 return AKEY_STATE_DOWN;
990 }
991 }
992 return AKEY_STATE_UP;
993 }
994 }
995 }
996 return AKEY_STATE_UNKNOWN;
997}
998
Philip Junker4af3b3d2021-12-14 10:36:55 +0100999int32_t EventHub::getKeyCodeForKeyLocation(int32_t deviceId, int32_t locationKeyCode) const {
1000 std::scoped_lock _l(mLock);
1001
1002 Device* device = getDeviceLocked(deviceId);
1003 if (device == nullptr || !device->hasValidFd() || device->keyMap.keyCharacterMap == nullptr ||
1004 device->keyMap.keyLayoutMap == nullptr) {
1005 return AKEYCODE_UNKNOWN;
1006 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001007 std::vector<int32_t> scanCodes =
1008 device->keyMap.keyLayoutMap->findScanCodesForKey(locationKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +01001009 if (scanCodes.empty()) {
1010 ALOGW("Failed to get key code for key location: no scan code maps to key code %d for input"
1011 "device %d",
1012 locationKeyCode, deviceId);
1013 return AKEYCODE_UNKNOWN;
1014 }
1015 if (scanCodes.size() > 1) {
1016 ALOGW("Multiple scan codes map to the same key code %d, returning only the first match",
1017 locationKeyCode);
1018 }
1019 int32_t outKeyCode;
1020 status_t mapKeyRes =
Harry Cutts33476232023-01-30 19:57:29 +00001021 device->getKeyCharacterMap()->mapKey(scanCodes[0], /*usageCode=*/0, &outKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +01001022 switch (mapKeyRes) {
1023 case OK:
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001024 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +01001025 case NAME_NOT_FOUND:
1026 // key character map doesn't re-map this scanCode, hence the keyCode remains the same
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001027 outKeyCode = locationKeyCode;
1028 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +01001029 default:
1030 ALOGW("Failed to get key code for key location: Key character map returned error %s",
1031 statusToString(mapKeyRes).c_str());
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001032 outKeyCode = AKEYCODE_UNKNOWN;
1033 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +01001034 }
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001035 // Remap if there is a Key remapping added to the KCM and return the remapped key
1036 return device->getKeyCharacterMap()->applyKeyRemapping(outKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +01001037}
1038
Michael Wrightd02c5b62014-02-10 15:10:22 -08001039int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
1040 if (sw >= 0 && sw <= SW_MAX) {
Chris Ye87143712020-11-10 05:05:58 +00001041 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001042
1043 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001044 if (device != nullptr && device->hasValidFd() && device->swBitmask.test(sw)) {
1045 if (device->readDeviceBitMask(EVIOCGSW(0), device->swState) >= 0) {
1046 return device->swState.test(sw) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001047 }
1048 }
1049 }
1050 return AKEY_STATE_UNKNOWN;
1051}
1052
1053status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
1054 *outValue = 0;
1055
1056 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +00001057 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001058
1059 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001060 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001061 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001062 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
1063 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
1064 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001065 return -errno;
1066 }
1067
1068 *outValue = info.value;
1069 return OK;
1070 }
1071 }
1072 return -1;
1073}
1074
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001075bool EventHub::markSupportedKeyCodes(int32_t deviceId, const std::vector<int32_t>& keyCodes,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001076 uint8_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +00001077 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001078
1079 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001080 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001081 for (size_t codeIndex = 0; codeIndex < keyCodes.size(); codeIndex++) {
Sergej Salnikove5420e72023-05-11 11:52:54 +00001082 if (device->hasKeycodeLocked(keyCodes[codeIndex])) {
1083 outFlags[codeIndex] = 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001084 }
1085 }
1086 return true;
1087 }
1088 return false;
1089}
1090
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001091void EventHub::addKeyRemapping(int32_t deviceId, int32_t fromKeyCode, int32_t toKeyCode) const {
1092 std::scoped_lock _l(mLock);
1093 Device* device = getDeviceLocked(deviceId);
1094 if (device == nullptr) {
1095 return;
1096 }
1097 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
1098 if (kcm) {
1099 kcm->addKeyRemapping(fromKeyCode, toKeyCode);
1100 }
1101}
1102
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001103status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
1104 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +00001105 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001106 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001107 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001108
Chris Ye66fbac32020-07-06 20:36:43 -07001109 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001110 // Check the key character map first.
Chris Ye3a1e4462020-08-12 10:13:15 -07001111 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
1112 if (kcm) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001113 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
1114 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001115 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001116 }
1117 }
1118
1119 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001120 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -08001121 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001122 status = NO_ERROR;
1123 }
1124 }
1125
1126 if (status == NO_ERROR) {
Chris Ye3a1e4462020-08-12 10:13:15 -07001127 if (kcm) {
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001128 // Remap keys based on user-defined key remappings and key behavior defined in the
1129 // corresponding kcm file
1130 *outKeycode = kcm->applyKeyRemapping(*outKeycode);
1131
1132 // Remap keys based on Key behavior defined in KCM file
1133 std::tie(*outKeycode, *outMetaState) =
1134 kcm->applyKeyBehavior(*outKeycode, metaState);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001135 } else {
1136 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001137 }
1138 }
1139 }
1140
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001141 if (status != NO_ERROR) {
1142 *outKeycode = 0;
1143 *outFlags = 0;
1144 *outMetaState = metaState;
1145 }
1146
1147 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001148}
1149
1150status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
Chris Ye87143712020-11-10 05:05:58 +00001151 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001152 Device* device = getDeviceLocked(deviceId);
1153
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001154 if (device == nullptr || !device->keyMap.haveKeyLayout()) {
1155 return NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001156 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001157 std::optional<AxisInfo> info = device->keyMap.keyLayoutMap->mapAxis(scanCode);
1158 if (!info.has_value()) {
1159 return NAME_NOT_FOUND;
1160 }
1161 *outAxisInfo = *info;
1162 return NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001163}
1164
Chris Yef59a2f42020-10-16 12:55:26 -07001165base::Result<std::pair<InputDeviceSensorType, int32_t>> EventHub::mapSensor(int32_t deviceId,
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001166 int32_t absCode) const {
Chris Yef59a2f42020-10-16 12:55:26 -07001167 std::scoped_lock _l(mLock);
1168 Device* device = getDeviceLocked(deviceId);
1169
1170 if (device != nullptr && device->keyMap.haveKeyLayout()) {
1171 return device->keyMap.keyLayoutMap->mapSensor(absCode);
1172 }
1173 return Errorf("Device not found or device has no key layout.");
1174}
1175
Chris Yee2b1e5c2021-03-10 22:45:12 -08001176// Gets the battery info map from battery ID to RawBatteryInfo of the miscellaneous device
1177// associated with the device ID. Returns an empty map if no miscellaneous device found.
1178const std::unordered_map<int32_t, RawBatteryInfo>& EventHub::getBatteryInfoLocked(
1179 int32_t deviceId) const {
1180 static const std::unordered_map<int32_t, RawBatteryInfo> EMPTY_BATTERY_INFO = {};
1181 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001182 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001183 return EMPTY_BATTERY_INFO;
1184 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001185 return device->associatedDevice->batteryInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001186}
1187
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001188std::vector<int32_t> EventHub::getRawBatteryIds(int32_t deviceId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001189 std::scoped_lock _l(mLock);
1190 std::vector<int32_t> batteryIds;
1191
Prabir Pradhan51894782022-08-23 16:29:10 +00001192 for (const auto& [id, info] : getBatteryInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001193 batteryIds.push_back(id);
1194 }
1195
1196 return batteryIds;
1197}
1198
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001199std::optional<RawBatteryInfo> EventHub::getRawBatteryInfo(int32_t deviceId,
1200 int32_t batteryId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001201 std::scoped_lock _l(mLock);
1202
1203 const auto infos = getBatteryInfoLocked(deviceId);
1204
1205 auto it = infos.find(batteryId);
1206 if (it != infos.end()) {
1207 return it->second;
1208 }
1209
1210 return std::nullopt;
1211}
1212
1213// Gets the light info map from light ID to RawLightInfo of the miscellaneous device associated
Prabir Pradhan51894782022-08-23 16:29:10 +00001214// with the device ID. Returns an empty map if no miscellaneous device found.
Chris Yee2b1e5c2021-03-10 22:45:12 -08001215const std::unordered_map<int32_t, RawLightInfo>& EventHub::getLightInfoLocked(
1216 int32_t deviceId) const {
1217 static const std::unordered_map<int32_t, RawLightInfo> EMPTY_LIGHT_INFO = {};
1218 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001219 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001220 return EMPTY_LIGHT_INFO;
1221 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001222 return device->associatedDevice->lightInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001223}
1224
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001225std::vector<int32_t> EventHub::getRawLightIds(int32_t deviceId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001226 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001227 std::vector<int32_t> lightIds;
1228
Prabir Pradhan51894782022-08-23 16:29:10 +00001229 for (const auto& [id, info] : getLightInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001230 lightIds.push_back(id);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001231 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001232
Chris Ye3fdbfef2021-01-06 18:45:18 -08001233 return lightIds;
1234}
1235
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001236std::optional<RawLightInfo> EventHub::getRawLightInfo(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001237 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001238
Chris Yee2b1e5c2021-03-10 22:45:12 -08001239 const auto infos = getLightInfoLocked(deviceId);
1240
1241 auto it = infos.find(lightId);
1242 if (it != infos.end()) {
1243 return it->second;
Chris Ye3fdbfef2021-01-06 18:45:18 -08001244 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001245
Chris Ye3fdbfef2021-01-06 18:45:18 -08001246 return std::nullopt;
1247}
1248
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001249std::optional<int32_t> EventHub::getLightBrightness(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001250 std::scoped_lock _l(mLock);
1251
Chris Yee2b1e5c2021-03-10 22:45:12 -08001252 const auto infos = getLightInfoLocked(deviceId);
1253 auto it = infos.find(lightId);
1254 if (it == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001255 return std::nullopt;
1256 }
1257 std::string buffer;
1258 if (!base::ReadFileToString(it->second.path / LIGHT_NODES.at(InputLightClass::BRIGHTNESS),
1259 &buffer)) {
1260 return std::nullopt;
1261 }
1262 return std::stoi(buffer);
1263}
1264
1265std::optional<std::unordered_map<LightColor, int32_t>> EventHub::getLightIntensities(
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001266 int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001267 std::scoped_lock _l(mLock);
1268
Chris Yee2b1e5c2021-03-10 22:45:12 -08001269 const auto infos = getLightInfoLocked(deviceId);
1270 auto lightIt = infos.find(lightId);
1271 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001272 return std::nullopt;
1273 }
1274
1275 auto ret =
1276 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1277
1278 if (!ret.has_value()) {
1279 return std::nullopt;
1280 }
1281 std::array<LightColor, COLOR_NUM> colors = ret.value();
1282
1283 std::string intensityStr;
1284 if (!base::ReadFileToString(lightIt->second.path /
1285 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY),
1286 &intensityStr)) {
1287 return std::nullopt;
1288 }
1289
1290 // Intensity node outputs 3 color values
1291 std::regex intensityPattern("([0-9]+)\\s([0-9]+)\\s([0-9]+)[\\n]");
1292 std::smatch results;
1293
1294 if (!std::regex_match(intensityStr, results, intensityPattern)) {
1295 return std::nullopt;
1296 }
1297 std::unordered_map<LightColor, int32_t> intensities;
1298 for (size_t i = 1; i < results.size(); i++) {
1299 int value = std::stoi(results[i].str());
1300 intensities.emplace(colors[i - 1], value);
1301 }
1302 return intensities;
1303}
1304
1305void EventHub::setLightBrightness(int32_t deviceId, int32_t lightId, int32_t brightness) {
1306 std::scoped_lock _l(mLock);
1307
Chris Yee2b1e5c2021-03-10 22:45:12 -08001308 const auto infos = getLightInfoLocked(deviceId);
1309 auto lightIt = infos.find(lightId);
1310 if (lightIt == infos.end()) {
1311 ALOGE("%s lightId %d not found ", __func__, lightId);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001312 return;
1313 }
1314
1315 if (!base::WriteStringToFile(std::to_string(brightness),
1316 lightIt->second.path /
1317 LIGHT_NODES.at(InputLightClass::BRIGHTNESS))) {
1318 ALOGE("Can not write to file, error: %s", strerror(errno));
1319 }
1320}
1321
1322void EventHub::setLightIntensities(int32_t deviceId, int32_t lightId,
1323 std::unordered_map<LightColor, int32_t> intensities) {
1324 std::scoped_lock _l(mLock);
1325
Chris Yee2b1e5c2021-03-10 22:45:12 -08001326 const auto infos = getLightInfoLocked(deviceId);
1327 auto lightIt = infos.find(lightId);
1328 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001329 ALOGE("Light Id %d does not exist.", lightId);
1330 return;
1331 }
1332
1333 auto ret =
1334 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1335
1336 if (!ret.has_value()) {
1337 return;
1338 }
1339 std::array<LightColor, COLOR_NUM> colors = ret.value();
1340
1341 std::string rgbStr;
1342 for (size_t i = 0; i < COLOR_NUM; i++) {
1343 auto it = intensities.find(colors[i]);
1344 if (it != intensities.end()) {
1345 rgbStr += std::to_string(it->second);
1346 // Insert space between colors
1347 if (i < COLOR_NUM - 1) {
1348 rgbStr += " ";
1349 }
1350 }
1351 }
1352 // Append new line
1353 rgbStr += "\n";
1354
1355 if (!base::WriteStringToFile(rgbStr,
1356 lightIt->second.path /
1357 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY))) {
1358 ALOGE("Can not write to file, error: %s", strerror(errno));
1359 }
1360}
1361
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001362std::optional<RawLayoutInfo> EventHub::getRawLayoutInfo(int32_t deviceId) const {
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001363 std::scoped_lock _l(mLock);
1364 Device* device = getDeviceLocked(deviceId);
1365 if (device == nullptr || !device->associatedDevice) {
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001366 return std::nullopt;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001367 }
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001368 return device->associatedDevice->layoutInfo;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001369}
1370
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001371void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Chris Ye87143712020-11-10 05:05:58 +00001372 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001373
1374 mExcludedDevices = devices;
1375}
1376
1377bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
Chris Ye87143712020-11-10 05:05:58 +00001378 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001379 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001380 if (device != nullptr && scanCode >= 0 && scanCode <= KEY_MAX) {
1381 return device->keyBitmask.test(scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001382 }
1383 return false;
1384}
1385
Arthur Hungcb40a002021-08-03 14:31:01 +00001386bool EventHub::hasKeyCode(int32_t deviceId, int32_t keyCode) const {
1387 std::scoped_lock _l(mLock);
1388 Device* device = getDeviceLocked(deviceId);
1389 if (device != nullptr) {
1390 return device->hasKeycodeLocked(keyCode);
1391 }
1392 return false;
1393}
1394
Michael Wrightd02c5b62014-02-10 15:10:22 -08001395bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
Chris Ye87143712020-11-10 05:05:58 +00001396 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001397 Device* device = getDeviceLocked(deviceId);
1398 int32_t sc;
Chris Ye989bb932020-07-04 16:18:59 -07001399 if (device != nullptr && device->mapLed(led, &sc) == NO_ERROR) {
Chris Ye66fbac32020-07-06 20:36:43 -07001400 return device->ledBitmask.test(sc);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001401 }
1402 return false;
1403}
1404
1405void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
Chris Ye87143712020-11-10 05:05:58 +00001406 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001407 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -07001408 if (device != nullptr && device->hasValidFd()) {
1409 device->setLedStateLocked(led, on);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001410 }
1411}
1412
1413void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001414 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001415 outVirtualKeys.clear();
1416
Chris Ye87143712020-11-10 05:05:58 +00001417 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001418 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001419 if (device != nullptr && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001420 const std::vector<VirtualKeyDefinition> virtualKeys =
1421 device->virtualKeyMap->getVirtualKeys();
1422 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001423 }
1424}
1425
Chris Ye3a1e4462020-08-12 10:13:15 -07001426const std::shared_ptr<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001427 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001428 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001429 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001430 return device->getKeyCharacterMap();
1431 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001432 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001433}
1434
Vaibhav Devmurari23e8ae92022-12-29 12:07:56 +00001435// If provided map is null, it will reset key character map to default KCM.
Chris Ye3a1e4462020-08-12 10:13:15 -07001436bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, std::shared_ptr<KeyCharacterMap> map) {
Chris Ye87143712020-11-10 05:05:58 +00001437 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001438 Device* device = getDeviceLocked(deviceId);
Vaibhav Devmurari23e8ae92022-12-29 12:07:56 +00001439 if (device == nullptr || device->keyMap.keyCharacterMap == nullptr) {
Philip Junker90bc9492021-12-10 18:39:42 +01001440 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001441 }
Vaibhav Devmurari23e8ae92022-12-29 12:07:56 +00001442 if (map == nullptr) {
1443 device->keyMap.keyCharacterMap->clearLayoutOverlay();
1444 return true;
1445 }
Philip Junker90bc9492021-12-10 18:39:42 +01001446 device->keyMap.keyCharacterMap->combine(*map);
1447 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001448}
1449
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001450static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
1451 std::string rawDescriptor;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001452 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001453 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001454 if (!identifier.uniqueId.empty()) {
1455 rawDescriptor += "uniqueId:";
1456 rawDescriptor += identifier.uniqueId;
Josh Bartel938632f2022-07-19 15:34:22 -05001457 }
1458 if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001459 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001460 }
1461
1462 if (identifier.vendor == 0 && identifier.product == 0) {
1463 // If we don't know the vendor and product id, then the device is probably
1464 // built-in so we need to rely on other information to uniquely identify
1465 // the input device. Usually we try to avoid relying on the device name or
1466 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001467 if (!identifier.name.empty()) {
1468 rawDescriptor += "name:";
1469 rawDescriptor += identifier.name;
1470 } else if (!identifier.location.empty()) {
1471 rawDescriptor += "location:";
1472 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001473 }
1474 }
1475 identifier.descriptor = sha1(rawDescriptor);
1476 return rawDescriptor;
1477}
1478
1479void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
1480 // Compute a device descriptor that uniquely identifies the device.
1481 // The descriptor is assumed to be a stable identifier. Its value should not
1482 // change between reboots, reconnections, firmware updates or new releases
1483 // of Android. In practice we sometimes get devices that cannot be uniquely
1484 // identified. In this case we enforce uniqueness between connected devices.
1485 // Ideally, we also want the descriptor to be short and relatively opaque.
Josh Bartel938632f2022-07-19 15:34:22 -05001486 // Note that we explicitly do not use the path or location for external devices
1487 // as their path or location will change as they are plugged/unplugged or moved
1488 // to different ports. We do fallback to using name and location in the case of
1489 // internal devices which are detected by the vendor and product being 0 in
1490 // generateDescriptor. If two identical descriptors are detected we will fallback
1491 // to using a 'nonce' and incrementing it until the new descriptor no longer has
1492 // a match with any existing descriptors.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001493
1494 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001495 std::string rawDescriptor = generateDescriptor(identifier);
Josh Bartel938632f2022-07-19 15:34:22 -05001496 // Enforce that the generated descriptor is unique.
1497 while (hasDeviceWithDescriptorLocked(identifier.descriptor)) {
1498 identifier.nonce++;
1499 rawDescriptor = generateDescriptor(identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001500 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001501 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001502 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001503}
1504
Prabir Pradhancb42b472022-08-23 16:01:19 +00001505std::shared_ptr<const EventHub::AssociatedDevice> EventHub::obtainAssociatedDeviceLocked(
1506 const std::filesystem::path& devicePath) const {
1507 const std::optional<std::filesystem::path> sysfsRootPathOpt =
1508 getSysfsRootPath(devicePath.c_str());
1509 if (!sysfsRootPathOpt) {
1510 return nullptr;
1511 }
1512
1513 const auto& path = *sysfsRootPathOpt;
Prabir Pradhancb42b472022-08-23 16:01:19 +00001514
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00001515 std::shared_ptr<const AssociatedDevice> associatedDevice = std::make_shared<AssociatedDevice>(
Prabir Pradhancb42b472022-08-23 16:01:19 +00001516 AssociatedDevice{.sysfsRootPath = path,
1517 .batteryInfos = readBatteryConfiguration(path),
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001518 .lightInfos = readLightsConfiguration(path),
1519 .layoutInfo = readLayoutConfiguration(path)});
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00001520
1521 bool associatedDeviceChanged = false;
1522 for (const auto& [id, dev] : mDevices) {
1523 if (dev->associatedDevice && dev->associatedDevice->sysfsRootPath == path) {
1524 if (*associatedDevice != *dev->associatedDevice) {
1525 associatedDeviceChanged = true;
1526 dev->associatedDevice = associatedDevice;
1527 }
1528 associatedDevice = dev->associatedDevice;
1529 }
1530 }
1531 ALOGI_IF(associatedDeviceChanged,
1532 "The AssociatedDevice changed for path '%s'. Using new AssociatedDevice: %s",
1533 path.c_str(), associatedDevice->dump().c_str());
1534
1535 return associatedDevice;
Prabir Pradhancb42b472022-08-23 16:01:19 +00001536}
1537
Vaibhav Devmurari5fc7d852023-03-17 18:43:33 +00001538bool EventHub::AssociatedDevice::isChanged() const {
1539 std::unordered_map<int32_t, RawBatteryInfo> newBatteryInfos =
1540 readBatteryConfiguration(sysfsRootPath);
1541 std::unordered_map<int32_t, RawLightInfo> newLightInfos =
1542 readLightsConfiguration(sysfsRootPath);
1543 std::optional<RawLayoutInfo> newLayoutInfo = readLayoutConfiguration(sysfsRootPath);
1544
1545 if (newBatteryInfos == batteryInfos && newLightInfos == lightInfos &&
1546 newLayoutInfo == layoutInfo) {
1547 return false;
1548 }
1549 return true;
1550}
1551
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001552void EventHub::vibrate(int32_t deviceId, const VibrationElement& element) {
Chris Ye87143712020-11-10 05:05:58 +00001553 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001554 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001555 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001556 ff_effect effect;
1557 memset(&effect, 0, sizeof(effect));
1558 effect.type = FF_RUMBLE;
1559 effect.id = device->ffEffectId;
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001560 // evdev FF_RUMBLE effect only supports two channels of vibration.
Chris Ye6393a262020-08-04 19:41:36 -07001561 effect.u.rumble.strong_magnitude = element.getMagnitude(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1562 effect.u.rumble.weak_magnitude = element.getMagnitude(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001563 effect.replay.length = element.duration.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001564 effect.replay.delay = 0;
1565 if (ioctl(device->fd, EVIOCSFF, &effect)) {
1566 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001567 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001568 return;
1569 }
1570 device->ffEffectId = effect.id;
1571
1572 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -07001573 ev.input_event_sec = 0;
1574 ev.input_event_usec = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001575 ev.type = EV_FF;
1576 ev.code = device->ffEffectId;
1577 ev.value = 1;
1578 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1579 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001580 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001581 return;
1582 }
1583 device->ffEffectPlaying = true;
1584 }
1585}
1586
1587void EventHub::cancelVibrate(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001588 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001589 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001590 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001591 if (device->ffEffectPlaying) {
1592 device->ffEffectPlaying = false;
1593
1594 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -07001595 ev.input_event_sec = 0;
1596 ev.input_event_usec = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001597 ev.type = EV_FF;
1598 ev.code = device->ffEffectId;
1599 ev.value = 0;
1600 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1601 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001602 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001603 return;
1604 }
1605 }
1606 }
1607}
1608
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001609std::vector<int32_t> EventHub::getVibratorIds(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001610 std::scoped_lock _l(mLock);
1611 std::vector<int32_t> vibrators;
1612 Device* device = getDeviceLocked(deviceId);
1613 if (device != nullptr && device->hasValidFd() &&
1614 device->classes.test(InputDeviceClass::VIBRATOR)) {
1615 vibrators.push_back(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1616 vibrators.push_back(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
1617 }
1618 return vibrators;
1619}
1620
Josh Bartel938632f2022-07-19 15:34:22 -05001621/**
1622 * Checks both mDevices and mOpeningDevices for a device with the descriptor passed.
1623 */
1624bool EventHub::hasDeviceWithDescriptorLocked(const std::string& descriptor) const {
1625 for (const auto& device : mOpeningDevices) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001626 if (descriptor == device->identifier.descriptor) {
Josh Bartel938632f2022-07-19 15:34:22 -05001627 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001628 }
1629 }
Josh Bartel938632f2022-07-19 15:34:22 -05001630
1631 for (const auto& [id, device] : mDevices) {
1632 if (descriptor == device->identifier.descriptor) {
1633 return true;
1634 }
1635 }
1636 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001637}
1638
1639EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001640 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001641 deviceId = mBuiltInKeyboardId;
1642 }
Chris Ye989bb932020-07-04 16:18:59 -07001643 const auto& it = mDevices.find(deviceId);
1644 return it != mDevices.end() ? it->second.get() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001645}
1646
Chris Ye8594e192020-07-14 10:34:06 -07001647EventHub::Device* EventHub::getDeviceByPathLocked(const std::string& devicePath) const {
Chris Ye989bb932020-07-04 16:18:59 -07001648 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001649 if (device->path == devicePath) {
Chris Ye989bb932020-07-04 16:18:59 -07001650 return device.get();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001651 }
1652 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001653 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001654}
1655
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001656/**
1657 * The file descriptor could be either input device, or a video device (associated with a
1658 * specific input device). Check both cases here, and return the device that this event
1659 * belongs to. Caller can compare the fd's once more to determine event type.
1660 * Looks through all input devices, and only attached video devices. Unattached video
1661 * devices are ignored.
1662 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001663EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
Chris Ye989bb932020-07-04 16:18:59 -07001664 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001665 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001666 // This is an input device event
Chris Ye989bb932020-07-04 16:18:59 -07001667 return device.get();
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001668 }
1669 if (device->videoDevice && device->videoDevice->getFd() == fd) {
1670 // This is a video device event
Chris Ye989bb932020-07-04 16:18:59 -07001671 return device.get();
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001672 }
1673 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001674 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
1675 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001676 return nullptr;
1677}
1678
Chris Yee2b1e5c2021-03-10 22:45:12 -08001679std::optional<int32_t> EventHub::getBatteryCapacity(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001680 std::filesystem::path batteryPath;
1681 {
1682 // Do not read the sysfs node to get the battery state while holding
1683 // the EventHub lock. For some peripheral devices, reading battery state
1684 // can be broken and take 5+ seconds. Holding the lock in this case would
1685 // block all other event processing during this time. For now, we assume this
1686 // call never happens on the InputReader thread and read the sysfs node outside
1687 // the lock to prevent event processing from being blocked by this call.
1688 std::scoped_lock _l(mLock);
Kim Low03ea0352020-11-06 12:45:07 -08001689
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001690 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001691 auto it = infos.find(batteryId);
1692 if (it == infos.end()) {
1693 return std::nullopt;
1694 }
1695 batteryPath = it->second.path;
1696 } // release lock
1697
Chris Yee2b1e5c2021-03-10 22:45:12 -08001698 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001699
1700 // Some devices report battery capacity as an integer through the "capacity" file
Andy Chenf9f1a022022-08-29 20:07:10 -04001701 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001702 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001703 return std::stoi(base::Trim(buffer));
Kim Low03ea0352020-11-06 12:45:07 -08001704 }
1705
1706 // Other devices report capacity as an enum value POWER_SUPPLY_CAPACITY_LEVEL_XXX
1707 // These values are taken from kernel source code include/linux/power_supply.h
Andy Chenf9f1a022022-08-29 20:07:10 -04001708 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY_LEVEL),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001709 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001710 // Remove any white space such as trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001711 const auto levelIt = BATTERY_LEVEL.find(base::Trim(buffer));
1712 if (levelIt != BATTERY_LEVEL.end()) {
1713 return levelIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001714 }
1715 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001716
Kim Low03ea0352020-11-06 12:45:07 -08001717 return std::nullopt;
1718}
1719
Chris Yee2b1e5c2021-03-10 22:45:12 -08001720std::optional<int32_t> EventHub::getBatteryStatus(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001721 std::filesystem::path batteryPath;
1722 {
1723 // Do not read the sysfs node to get the battery state while holding
1724 // the EventHub lock. For some peripheral devices, reading battery state
1725 // can be broken and take 5+ seconds. Holding the lock in this case would
1726 // block all other event processing during this time. For now, we assume this
1727 // call never happens on the InputReader thread and read the sysfs node outside
1728 // the lock to prevent event processing from being blocked by this call.
1729 std::scoped_lock _l(mLock);
1730
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001731 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001732 auto it = infos.find(batteryId);
1733 if (it == infos.end()) {
1734 return std::nullopt;
1735 }
1736 batteryPath = it->second.path;
1737 } // release lock
1738
Chris Yee2b1e5c2021-03-10 22:45:12 -08001739 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001740
Andy Chenf9f1a022022-08-29 20:07:10 -04001741 if (!base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::STATUS),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001742 &buffer)) {
Kim Low03ea0352020-11-06 12:45:07 -08001743 ALOGE("Failed to read sysfs battery info: %s", strerror(errno));
1744 return std::nullopt;
1745 }
1746
Chris Yed1936772021-02-22 10:30:40 -08001747 // Remove white space like trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001748 const auto statusIt = BATTERY_STATUS.find(base::Trim(buffer));
1749 if (statusIt != BATTERY_STATUS.end()) {
1750 return statusIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001751 }
1752
1753 return std::nullopt;
1754}
1755
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001756std::vector<RawEvent> EventHub::getEvents(int timeoutMillis) {
Chris Ye87143712020-11-10 05:05:58 +00001757 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001758
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001759 std::array<input_event, EVENT_BUFFER_SIZE> readBuffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001760
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001761 std::vector<RawEvent> events;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001762 bool awoken = false;
1763 for (;;) {
1764 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
1765
1766 // Reopen input devices if needed.
1767 if (mNeedToReopenDevices) {
1768 mNeedToReopenDevices = false;
1769
1770 ALOGI("Reopening all input devices due to a configuration change.");
1771
1772 closeAllDevicesLocked();
1773 mNeedToScanDevices = true;
1774 break; // return to the caller before we actually rescan
1775 }
1776
1777 // Report any devices that had last been added/removed.
Chris Ye989bb932020-07-04 16:18:59 -07001778 for (auto it = mClosingDevices.begin(); it != mClosingDevices.end();) {
1779 std::unique_ptr<Device> device = std::move(*it);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001780 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001781 const int32_t deviceId = (device->id == mBuiltInKeyboardId)
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001782 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
1783 : device->id;
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001784 events.push_back({
1785 .when = now,
1786 .deviceId = deviceId,
1787 .type = DEVICE_REMOVED,
1788 });
Chris Ye989bb932020-07-04 16:18:59 -07001789 it = mClosingDevices.erase(it);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001790 mNeedToSendFinishedDeviceScan = true;
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001791 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001792 break;
1793 }
1794 }
1795
1796 if (mNeedToScanDevices) {
1797 mNeedToScanDevices = false;
1798 scanDevicesLocked();
1799 mNeedToSendFinishedDeviceScan = true;
1800 }
1801
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001802 while (!mOpeningDevices.empty()) {
1803 std::unique_ptr<Device> device = std::move(*mOpeningDevices.rbegin());
1804 mOpeningDevices.pop_back();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001805 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001806 const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1807 events.push_back({
1808 .when = now,
1809 .deviceId = deviceId,
1810 .type = DEVICE_ADDED,
1811 });
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001812
1813 // Try to find a matching video device by comparing device names
1814 for (auto it = mUnattachedVideoDevices.begin(); it != mUnattachedVideoDevices.end();
1815 it++) {
1816 std::unique_ptr<TouchVideoDevice>& videoDevice = *it;
Chris Yed3fef462021-03-07 17:10:08 -08001817 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001818 // videoDevice was transferred to 'device'
1819 it = mUnattachedVideoDevices.erase(it);
1820 break;
1821 }
1822 }
1823
1824 auto [dev_it, inserted] = mDevices.insert_or_assign(device->id, std::move(device));
1825 if (!inserted) {
Chris Ye989bb932020-07-04 16:18:59 -07001826 ALOGW("Device id %d exists, replaced.", device->id);
1827 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001828 mNeedToSendFinishedDeviceScan = true;
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001829 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001830 break;
1831 }
1832 }
1833
1834 if (mNeedToSendFinishedDeviceScan) {
1835 mNeedToSendFinishedDeviceScan = false;
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001836 events.push_back({
1837 .when = now,
1838 .type = FINISHED_DEVICE_SCAN,
1839 });
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001840 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001841 break;
1842 }
1843 }
1844
1845 // Grab the next input event.
1846 bool deviceChanged = false;
1847 while (mPendingEventIndex < mPendingEventCount) {
1848 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001849 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001850 if (eventItem.events & EPOLLIN) {
1851 mPendingINotify = true;
1852 } else {
1853 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
1854 }
1855 continue;
1856 }
1857
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001858 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001859 if (eventItem.events & EPOLLIN) {
1860 ALOGV("awoken after wake()");
1861 awoken = true;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001862 char wakeReadBuffer[16];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001863 ssize_t nRead;
1864 do {
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001865 nRead = read(mWakeReadPipeFd, wakeReadBuffer, sizeof(wakeReadBuffer));
1866 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(wakeReadBuffer));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001867 } else {
1868 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001869 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001870 }
1871 continue;
1872 }
1873
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001874 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Chris Ye989bb932020-07-04 16:18:59 -07001875 if (device == nullptr) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001876 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
1877 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001878 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001879 continue;
1880 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001881 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
1882 if (eventItem.events & EPOLLIN) {
1883 size_t numFrames = device->videoDevice->readAndQueueFrames();
1884 if (numFrames == 0) {
1885 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001886 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001887 }
1888 } else if (eventItem.events & EPOLLHUP) {
1889 // TODO(b/121395353) - consider adding EPOLLRDHUP
1890 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001891 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001892 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1893 device->videoDevice = nullptr;
1894 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001895 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1896 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001897 ALOG_ASSERT(!DEBUG);
1898 }
1899 continue;
1900 }
1901 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -08001902 if (eventItem.events & EPOLLIN) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001903 int32_t readSize =
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001904 read(device->fd, readBuffer.data(),
1905 sizeof(decltype(readBuffer)::value_type) * readBuffer.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001906 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
1907 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -07001908 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001909 " capacity: %zu errno: %d)\n",
1910 device->fd, readSize, readBuffer.size(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001911 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001912 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001913 } else if (readSize < 0) {
1914 if (errno != EAGAIN && errno != EINTR) {
1915 ALOGW("could not get event (errno=%d)", errno);
1916 }
1917 } else if ((readSize % sizeof(struct input_event)) != 0) {
1918 ALOGE("could not get event (wrong size: %d)", readSize);
1919 } else {
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001920 const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001921
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001922 const size_t count = size_t(readSize) / sizeof(struct input_event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001923 for (size_t i = 0; i < count; i++) {
1924 struct input_event& iev = readBuffer[i];
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001925 events.push_back({
1926 .when = processEventTimestamp(iev),
1927 .readTime = systemTime(SYSTEM_TIME_MONOTONIC),
1928 .deviceId = deviceId,
1929 .type = iev.type,
1930 .code = iev.code,
1931 .value = iev.value,
1932 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08001933 }
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001934 if (events.size() >= EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001935 // The result buffer is full. Reset the pending event index
1936 // so we will try to read the device again on the next iteration.
1937 mPendingEventIndex -= 1;
1938 break;
1939 }
1940 }
1941 } else if (eventItem.events & EPOLLHUP) {
1942 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001943 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001944 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001945 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001946 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001947 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1948 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001949 }
1950 }
1951
1952 // readNotify() will modify the list of devices so this must be done after
1953 // processing all other events to ensure that we read all remaining events
1954 // before closing the devices.
1955 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
1956 mPendingINotify = false;
Prabir Pradhan952e65b2022-06-23 17:49:55 +00001957 const auto res = readNotifyLocked();
1958 if (!res.ok()) {
1959 ALOGW("Failed to read from inotify: %s", res.error().message().c_str());
1960 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001961 deviceChanged = true;
1962 }
1963
1964 // Report added or removed devices immediately.
1965 if (deviceChanged) {
1966 continue;
1967 }
1968
1969 // Return now if we have collected any events or if we were explicitly awoken.
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001970 if (!events.empty() || awoken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001971 break;
1972 }
1973
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001974 // Poll for events.
1975 // When a device driver has pending (unread) events, it acquires
1976 // a kernel wake lock. Once the last pending event has been read, the device
1977 // driver will release the kernel wake lock, but the epoll will hold the wakelock,
1978 // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
1979 // is called again for the same fd that produced the event.
1980 // Thus the system can only sleep if there are no events pending or
1981 // currently being processed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001982 //
1983 // The timeout is advisory only. If the device is asleep, it will not wake just to
1984 // service the timeout.
1985 mPendingEventIndex = 0;
1986
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001987 mLock.unlock(); // release lock before poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001988
1989 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1990
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001991 mLock.lock(); // reacquire lock after poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001992
1993 if (pollResult == 0) {
1994 // Timed out.
1995 mPendingEventCount = 0;
1996 break;
1997 }
1998
1999 if (pollResult < 0) {
2000 // An error occurred.
2001 mPendingEventCount = 0;
2002
2003 // Sleep after errors to avoid locking up the system.
2004 // Hopefully the error is transient.
2005 if (errno != EINTR) {
2006 ALOGW("poll failed (errno=%d)\n", errno);
2007 usleep(100000);
2008 }
2009 } else {
2010 // Some events occurred.
2011 mPendingEventCount = size_t(pollResult);
2012 }
2013 }
2014
2015 // All done, return the number of events we read.
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002016 return events;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002017}
2018
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08002019std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002020 std::scoped_lock _l(mLock);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08002021
2022 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07002023 if (device == nullptr || !device->videoDevice) {
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08002024 return {};
2025 }
2026 return device->videoDevice->consumeFrames();
2027}
2028
Michael Wrightd02c5b62014-02-10 15:10:22 -08002029void EventHub::wake() {
2030 ALOGV("wake() called");
2031
2032 ssize_t nWrite;
2033 do {
2034 nWrite = write(mWakeWritePipeFd, "W", 1);
2035 } while (nWrite == -1 && errno == EINTR);
2036
2037 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002038 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002039 }
2040}
2041
2042void EventHub::scanDevicesLocked() {
Usama Arifb27c8e62021-06-03 16:44:09 +01002043 status_t result;
2044 std::error_code errorCode;
2045
2046 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
2047 result = scanDirLocked(DEVICE_INPUT_PATH);
2048 if (result < 0) {
2049 ALOGE("scan dir failed for %s", DEVICE_INPUT_PATH);
2050 }
2051 } else {
2052 if (errorCode) {
2053 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
2054 errorCode.message().c_str());
2055 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002056 }
Philip Quinn39b81682019-01-09 22:20:39 -08002057 if (isV4lScanningEnabled()) {
Usama Arifb27c8e62021-06-03 16:44:09 +01002058 result = scanVideoDirLocked(DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08002059 if (result != OK) {
Usama Arifb27c8e62021-06-03 16:44:09 +01002060 ALOGE("scan video dir failed for %s", DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08002061 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002062 }
Chris Ye989bb932020-07-04 16:18:59 -07002063 if (mDevices.find(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) == mDevices.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002064 createVirtualKeyboardLocked();
2065 }
2066}
2067
2068// ----------------------------------------------------------------------------
2069
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002070status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002071 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002072 struct epoll_event eventItem = {};
2073 eventItem.events = EPOLLIN | EPOLLWAKEUP;
2074 eventItem.data.fd = fd;
2075 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
2076 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002077 return -errno;
2078 }
2079 return OK;
2080}
2081
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002082status_t EventHub::unregisterFdFromEpoll(int fd) {
2083 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
2084 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
2085 return -errno;
2086 }
2087 return OK;
2088}
2089
Chris Ye989bb932020-07-04 16:18:59 -07002090status_t EventHub::registerDeviceForEpollLocked(Device& device) {
2091 status_t result = registerFdForEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002092 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07002093 ALOGE("Could not add input device fd to epoll for device %" PRId32, device.id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002094 return result;
2095 }
Chris Ye989bb932020-07-04 16:18:59 -07002096 if (device.videoDevice) {
2097 registerVideoDeviceForEpollLocked(*device.videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002098 }
2099 return result;
2100}
2101
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002102void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
2103 status_t result = registerFdForEpoll(videoDevice.getFd());
2104 if (result != OK) {
2105 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
2106 }
2107}
2108
Chris Ye989bb932020-07-04 16:18:59 -07002109status_t EventHub::unregisterDeviceFromEpollLocked(Device& device) {
2110 if (device.hasValidFd()) {
2111 status_t result = unregisterFdFromEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002112 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07002113 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device.id);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002114 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002115 }
2116 }
Chris Ye989bb932020-07-04 16:18:59 -07002117 if (device.videoDevice) {
2118 unregisterVideoDeviceFromEpollLocked(*device.videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002119 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002120 return OK;
2121}
2122
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002123void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
2124 if (videoDevice.hasValidFd()) {
2125 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
2126 if (result != OK) {
2127 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002128 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002129 }
2130 }
2131}
2132
Chris Yed3fef462021-03-07 17:10:08 -08002133void EventHub::reportDeviceAddedForStatisticsLocked(const InputDeviceIdentifier& identifier,
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002134 ftl::Flags<InputDeviceClass> classes) {
Chris Ye657c2f02021-05-25 16:24:37 -07002135 SHA256_CTX ctx;
2136 SHA256_Init(&ctx);
2137 SHA256_Update(&ctx, reinterpret_cast<const uint8_t*>(identifier.uniqueId.c_str()),
2138 identifier.uniqueId.size());
2139 std::array<uint8_t, SHA256_DIGEST_LENGTH> digest;
2140 SHA256_Final(digest.data(), &ctx);
2141
2142 std::string obfuscatedId;
2143 for (size_t i = 0; i < OBFUSCATED_LENGTH; i++) {
2144 obfuscatedId += StringPrintf("%02x", digest[i]);
2145 }
2146
Chris Yed3fef462021-03-07 17:10:08 -08002147 android::util::stats_write(android::util::INPUTDEVICE_REGISTERED, identifier.name.c_str(),
2148 identifier.vendor, identifier.product, identifier.version,
Chris Ye657c2f02021-05-25 16:24:37 -07002149 identifier.bus, obfuscatedId.c_str(), classes.get());
Chris Yed3fef462021-03-07 17:10:08 -08002150}
2151
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002152void EventHub::openDeviceLocked(const std::string& devicePath) {
2153 // If an input device happens to register around the time when EventHub's constructor runs, it
2154 // is possible that the same input event node (for example, /dev/input/event3) will be noticed
2155 // in both 'inotify' callback and also in the 'scanDirLocked' pass. To prevent duplicate devices
2156 // from getting registered, ensure that this path is not already covered by an existing device.
2157 for (const auto& [deviceId, device] : mDevices) {
2158 if (device->path == devicePath) {
2159 return; // device was already registered
2160 }
2161 }
2162
Michael Wrightd02c5b62014-02-10 15:10:22 -08002163 char buffer[80];
2164
Chris Ye8594e192020-07-14 10:34:06 -07002165 ALOGV("Opening device: %s", devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002166
Chris Ye8594e192020-07-14 10:34:06 -07002167 int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002168 if (fd < 0) {
Chris Ye8594e192020-07-14 10:34:06 -07002169 ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002170 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002171 }
2172
2173 InputDeviceIdentifier identifier;
2174
2175 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002176 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Chris Ye8594e192020-07-14 10:34:06 -07002177 ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002178 } else {
2179 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002180 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002181 }
2182
2183 // Check to see if the device is on our excluded list
2184 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002185 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002186 if (identifier.name == item) {
Chris Ye8594e192020-07-14 10:34:06 -07002187 ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002188 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002189 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002190 }
2191 }
2192
2193 // Get device driver version.
2194 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002195 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Chris Ye8594e192020-07-14 10:34:06 -07002196 ALOGE("could not get driver version for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002197 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002198 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002199 }
2200
2201 // Get device identifier.
2202 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002203 if (ioctl(fd, EVIOCGID, &inputId)) {
Chris Ye8594e192020-07-14 10:34:06 -07002204 ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002205 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002206 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002207 }
2208 identifier.bus = inputId.bustype;
2209 identifier.product = inputId.product;
2210 identifier.vendor = inputId.vendor;
2211 identifier.version = inputId.version;
2212
2213 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002214 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
2215 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002216 } else {
2217 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002218 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002219 }
2220
2221 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002222 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
2223 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002224 } else {
2225 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002226 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002227 }
2228
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002229 // Attempt to get the bluetooth address of an input device from the uniqueId.
2230 if (identifier.bus == BUS_BLUETOOTH &&
2231 std::regex_match(identifier.uniqueId,
2232 std::regex("^[A-Fa-f0-9]{2}(?::[A-Fa-f0-9]{2}){5}$"))) {
2233 identifier.bluetoothAddress = identifier.uniqueId;
2234 // The Bluetooth stack requires alphabetic characters to be uppercase in a valid address.
2235 for (auto& c : *identifier.bluetoothAddress) {
2236 c = ::toupper(c);
2237 }
2238 }
2239
Michael Wrightd02c5b62014-02-10 15:10:22 -08002240 // Fill in the descriptor.
2241 assignDescriptorLocked(identifier);
2242
Michael Wrightd02c5b62014-02-10 15:10:22 -08002243 // Allocate device. (The device object takes ownership of the fd at this point.)
2244 int32_t deviceId = mNextDeviceId++;
Prabir Pradhancb42b472022-08-23 16:01:19 +00002245 std::unique_ptr<Device> device =
2246 std::make_unique<Device>(fd, deviceId, devicePath, identifier,
2247 obtainAssociatedDeviceLocked(devicePath));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002248
Chris Ye8594e192020-07-14 10:34:06 -07002249 ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002250 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002251 " vendor %04x\n"
2252 " product %04x\n"
2253 " version %04x\n",
2254 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002255 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
2256 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
2257 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
2258 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002259 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
2260 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002261
2262 // Load the configuration file for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002263 device->loadConfigurationLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002264
2265 // Figure out the kinds of events the device reports.
Chris Ye66fbac32020-07-06 20:36:43 -07002266 device->readDeviceBitMask(EVIOCGBIT(EV_KEY, 0), device->keyBitmask);
2267 device->readDeviceBitMask(EVIOCGBIT(EV_ABS, 0), device->absBitmask);
2268 device->readDeviceBitMask(EVIOCGBIT(EV_REL, 0), device->relBitmask);
2269 device->readDeviceBitMask(EVIOCGBIT(EV_SW, 0), device->swBitmask);
2270 device->readDeviceBitMask(EVIOCGBIT(EV_LED, 0), device->ledBitmask);
2271 device->readDeviceBitMask(EVIOCGBIT(EV_FF, 0), device->ffBitmask);
Chris Yef59a2f42020-10-16 12:55:26 -07002272 device->readDeviceBitMask(EVIOCGBIT(EV_MSC, 0), device->mscBitmask);
Chris Ye66fbac32020-07-06 20:36:43 -07002273 device->readDeviceBitMask(EVIOCGPROP(0), device->propBitmask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002274
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002275 // See if this is a device with keys. This could be full keyboard, or other devices like
2276 // gamepads, joysticks, and styluses with buttons that should generate key presses.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002277 bool haveKeyboardKeys =
Chris Ye66fbac32020-07-06 20:36:43 -07002278 device->keyBitmask.any(0, BTN_MISC) || device->keyBitmask.any(BTN_WHEEL, KEY_MAX + 1);
2279 bool haveGamepadButtons = device->keyBitmask.any(BTN_MISC, BTN_MOUSE) ||
2280 device->keyBitmask.any(BTN_JOYSTICK, BTN_DIGI);
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002281 bool haveStylusButtons = device->keyBitmask.test(BTN_STYLUS) ||
2282 device->keyBitmask.test(BTN_STYLUS2) || device->keyBitmask.test(BTN_STYLUS3);
2283 if (haveKeyboardKeys || haveGamepadButtons || haveStylusButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002284 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002285 }
2286
2287 // See if this is a cursor device such as a trackball or mouse.
Chris Ye66fbac32020-07-06 20:36:43 -07002288 if (device->keyBitmask.test(BTN_MOUSE) && device->relBitmask.test(REL_X) &&
2289 device->relBitmask.test(REL_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002290 device->classes |= InputDeviceClass::CURSOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002291 }
2292
Prabir Pradhana3621852022-10-14 18:57:23 +00002293 // See if the device is specially configured to be of a certain type.
Harry Cuttsf13161a2023-03-08 14:15:49 +00002294 if (device->configuration) {
2295 std::string deviceType = device->configuration->getString("device.type").value_or("");
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07002296 if (deviceType == "rotaryEncoder") {
Chris Ye1b0c7342020-07-28 21:57:03 -07002297 device->classes |= InputDeviceClass::ROTARY_ENCODER;
Prabir Pradhana3621852022-10-14 18:57:23 +00002298 } else if (deviceType == "externalStylus") {
2299 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002300 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002301 }
2302
Michael Wrightd02c5b62014-02-10 15:10:22 -08002303 // See if this is a touch pad.
2304 // Is this a new modern multi-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002305 if (device->absBitmask.test(ABS_MT_POSITION_X) && device->absBitmask.test(ABS_MT_POSITION_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002306 // Some joysticks such as the PS3 controller report axes that conflict
2307 // with the ABS_MT range. Try to confirm that the device really is
2308 // a touch screen.
Chris Ye66fbac32020-07-06 20:36:43 -07002309 if (device->keyBitmask.test(BTN_TOUCH) || !haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002310 device->classes |= (InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT);
Harry Cutts79cc9fa2022-10-28 15:32:39 +00002311 if (device->propBitmask.test(INPUT_PROP_POINTER) &&
2312 !device->keyBitmask.any(BTN_TOOL_PEN, BTN_TOOL_FINGER) && !haveStylusButtons) {
2313 device->classes |= InputDeviceClass::TOUCHPAD;
2314 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002315 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002316 // Is this an old style single-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002317 } else if (device->keyBitmask.test(BTN_TOUCH) && device->absBitmask.test(ABS_X) &&
2318 device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002319 device->classes |= InputDeviceClass::TOUCH;
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002320 // Is this a stylus that reports contact/pressure independently of touch coordinates?
Chris Ye66fbac32020-07-06 20:36:43 -07002321 } else if ((device->absBitmask.test(ABS_PRESSURE) || device->keyBitmask.test(BTN_TOUCH)) &&
2322 !device->absBitmask.test(ABS_X) && !device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002323 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002324 }
2325
2326 // See if this device is a joystick.
2327 // Assumes that joysticks always have gamepad buttons in order to distinguish them
2328 // from other devices such as accelerometers that also have absolute axes.
2329 if (haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002330 auto assumedClasses = device->classes | InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002331 for (int i = 0; i <= ABS_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002332 if (device->absBitmask.test(i) &&
Chris Ye1b0c7342020-07-28 21:57:03 -07002333 (getAbsAxisUsage(i, assumedClasses).test(InputDeviceClass::JOYSTICK))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002334 device->classes = assumedClasses;
2335 break;
2336 }
2337 }
2338 }
2339
Chris Yef59a2f42020-10-16 12:55:26 -07002340 // Check whether this device is an accelerometer.
2341 if (device->propBitmask.test(INPUT_PROP_ACCELEROMETER)) {
2342 device->classes |= InputDeviceClass::SENSOR;
2343 }
2344
Michael Wrightd02c5b62014-02-10 15:10:22 -08002345 // Check whether this device has switches.
2346 for (int i = 0; i <= SW_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002347 if (device->swBitmask.test(i)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002348 device->classes |= InputDeviceClass::SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002349 break;
2350 }
2351 }
2352
2353 // Check whether this device supports the vibrator.
Chris Ye66fbac32020-07-06 20:36:43 -07002354 if (device->ffBitmask.test(FF_RUMBLE)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002355 device->classes |= InputDeviceClass::VIBRATOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002356 }
2357
2358 // Configure virtual keys.
Chris Ye1b0c7342020-07-28 21:57:03 -07002359 if ((device->classes.test(InputDeviceClass::TOUCH))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002360 // Load the virtual keys for the touch screen, if any.
2361 // We do this now so that we can make sure to load the keymap if necessary.
Chris Ye989bb932020-07-04 16:18:59 -07002362 bool success = device->loadVirtualKeyMapLocked();
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06002363 if (success) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002364 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002365 }
2366 }
2367
2368 // Load the key map.
Chris Yef59a2f42020-10-16 12:55:26 -07002369 // We need to do this for joysticks too because the key layout may specify axes, and for
2370 // sensor as well because the key layout may specify the axes to sensor data mapping.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002371 status_t keyMapStatus = NAME_NOT_FOUND;
Chris Yef59a2f42020-10-16 12:55:26 -07002372 if (device->classes.any(InputDeviceClass::KEYBOARD | InputDeviceClass::JOYSTICK |
2373 InputDeviceClass::SENSOR)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002374 // Load the keymap for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002375 keyMapStatus = device->loadKeyMapLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002376 }
2377
2378 // Configure the keyboard, gamepad or virtual keyboard.
Chris Ye1b0c7342020-07-28 21:57:03 -07002379 if (device->classes.test(InputDeviceClass::KEYBOARD)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002380 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002381 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002382 isEligibleBuiltInKeyboard(device->identifier, device->configuration.get(),
2383 &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002384 mBuiltInKeyboardId = device->id;
2385 }
2386
2387 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
Chris Ye989bb932020-07-04 16:18:59 -07002388 if (device->hasKeycodeLocked(AKEYCODE_Q)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002389 device->classes |= InputDeviceClass::ALPHAKEY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002390 }
2391
Prabir Pradhanae10ee62023-05-12 19:44:18 +00002392 // See if this device has a D-pad.
2393 if (std::all_of(DPAD_REQUIRED_KEYCODES.begin(), DPAD_REQUIRED_KEYCODES.end(),
2394 [&](int32_t keycode) { return device->hasKeycodeLocked(keycode); })) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002395 device->classes |= InputDeviceClass::DPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002396 }
2397
2398 // See if this device has a gamepad.
Prabir Pradhanae10ee62023-05-12 19:44:18 +00002399 if (std::any_of(GAMEPAD_KEYCODES.begin(), GAMEPAD_KEYCODES.end(),
2400 [&](int32_t keycode) { return device->hasKeycodeLocked(keycode); })) {
2401 device->classes |= InputDeviceClass::GAMEPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002402 }
Prabir Pradhana3621852022-10-14 18:57:23 +00002403
2404 // See if this device has any stylus buttons that we would want to fuse with touch data.
Prabir Pradhanae10ee62023-05-12 19:44:18 +00002405 if (!device->classes.any(InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT) &&
2406 std::any_of(STYLUS_BUTTON_KEYCODES.begin(), STYLUS_BUTTON_KEYCODES.end(),
2407 [&](int32_t keycode) { return device->hasKeycodeLocked(keycode); })) {
2408 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Prabir Pradhana3621852022-10-14 18:57:23 +00002409 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002410 }
2411
2412 // If the device isn't recognized as something we handle, don't monitor it.
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002413 if (device->classes == ftl::Flags<InputDeviceClass>(0)) {
Chris Ye8594e192020-07-14 10:34:06 -07002414 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002415 device->identifier.name.c_str());
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002416 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002417 }
2418
Chris Ye3fdbfef2021-01-06 18:45:18 -08002419 // Classify InputDeviceClass::BATTERY.
Prabir Pradhan51894782022-08-23 16:29:10 +00002420 if (device->associatedDevice && !device->associatedDevice->batteryInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002421 device->classes |= InputDeviceClass::BATTERY;
2422 }
Kim Low03ea0352020-11-06 12:45:07 -08002423
Chris Ye3fdbfef2021-01-06 18:45:18 -08002424 // Classify InputDeviceClass::LIGHT.
Prabir Pradhan51894782022-08-23 16:29:10 +00002425 if (device->associatedDevice && !device->associatedDevice->lightInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002426 device->classes |= InputDeviceClass::LIGHT;
Kim Low03ea0352020-11-06 12:45:07 -08002427 }
2428
Tim Kilbourn063ff532015-04-08 10:26:18 -07002429 // Determine whether the device has a mic.
Chris Ye989bb932020-07-04 16:18:59 -07002430 if (device->deviceHasMicLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002431 device->classes |= InputDeviceClass::MIC;
Tim Kilbourn063ff532015-04-08 10:26:18 -07002432 }
2433
Michael Wrightd02c5b62014-02-10 15:10:22 -08002434 // Determine whether the device is external or internal.
Chris Ye989bb932020-07-04 16:18:59 -07002435 if (device->isExternalDeviceLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002436 device->classes |= InputDeviceClass::EXTERNAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002437 }
2438
Chris Ye1b0c7342020-07-28 21:57:03 -07002439 if (device->classes.any(InputDeviceClass::JOYSTICK | InputDeviceClass::DPAD) &&
2440 device->classes.test(InputDeviceClass::GAMEPAD)) {
Chris Ye989bb932020-07-04 16:18:59 -07002441 device->controllerNumber = getNextControllerNumberLocked(device->identifier.name);
2442 device->setLedForControllerLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002443 }
2444
Chris Ye989bb932020-07-04 16:18:59 -07002445 if (registerDeviceForEpollLocked(*device) != OK) {
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002446 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002447 }
2448
Chris Ye989bb932020-07-04 16:18:59 -07002449 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002450
Arpit Singh77140f42023-06-13 11:35:27 +00002451 // read absolute axis info for all available axes for the device
2452 populateDeviceAbsoluteAxisInfo(*device);
2453
Chris Ye1b0c7342020-07-28 21:57:03 -07002454 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=%s, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002455 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Chris Ye1b0c7342020-07-28 21:57:03 -07002456 deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(),
2457 device->classes.string().c_str(), device->configurationFile.c_str(),
2458 device->keyMap.keyLayoutFile.c_str(), device->keyMap.keyCharacterMapFile.c_str(),
2459 toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002460
Chris Ye989bb932020-07-04 16:18:59 -07002461 addDeviceLocked(std::move(device));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002462}
2463
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002464void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
2465 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
2466 if (!videoDevice) {
2467 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
2468 return;
2469 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002470 // Transfer ownership of this video device to a matching input device
Chris Ye989bb932020-07-04 16:18:59 -07002471 for (const auto& [id, device] : mDevices) {
Chris Yed3fef462021-03-07 17:10:08 -08002472 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002473 return; // 'device' now owns 'videoDevice'
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002474 }
2475 }
2476
2477 // Couldn't find a matching input device, so just add it to a temporary holding queue.
2478 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002479 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002480 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002481 mUnattachedVideoDevices.push_back(std::move(videoDevice));
2482}
2483
Chris Yed3fef462021-03-07 17:10:08 -08002484bool EventHub::tryAddVideoDeviceLocked(EventHub::Device& device,
2485 std::unique_ptr<TouchVideoDevice>& videoDevice) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002486 if (videoDevice->getName() != device.identifier.name) {
2487 return false;
2488 }
2489 device.videoDevice = std::move(videoDevice);
2490 if (device.enabled) {
2491 registerVideoDeviceForEpollLocked(*device.videoDevice);
2492 }
2493 return true;
2494}
2495
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002496bool EventHub::isDeviceEnabled(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00002497 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002498 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002499 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002500 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2501 return false;
2502 }
2503 return device->enabled;
2504}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002505
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002506status_t EventHub::enableDevice(int32_t deviceId) {
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 BAD_VALUE;
2512 }
2513 if (device->enabled) {
2514 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
2515 return OK;
2516 }
2517 status_t result = device->enable();
2518 if (result != OK) {
2519 ALOGE("Failed to enable device %" PRId32, deviceId);
2520 return result;
2521 }
2522
Chris Ye989bb932020-07-04 16:18:59 -07002523 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002524
Chris Ye989bb932020-07-04 16:18:59 -07002525 return registerDeviceForEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002526}
2527
2528status_t EventHub::disableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002529 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002530 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002531 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002532 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2533 return BAD_VALUE;
2534 }
2535 if (!device->enabled) {
2536 ALOGW("Duplicate call to %s, input device already disabled", __func__);
2537 return OK;
2538 }
Chris Ye989bb932020-07-04 16:18:59 -07002539 unregisterDeviceFromEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002540 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002541}
2542
Vaibhav Devmurari5fc7d852023-03-17 18:43:33 +00002543// TODO(b/274755573): Shift to uevent handling on native side and remove this method
2544// Currently using Java UEventObserver to trigger this which uses UEvent infrastructure that uses a
2545// NETLINK socket to observe UEvents. We can create similar infrastructure on Eventhub side to
2546// directly observe UEvents instead of triggering from Java side.
2547void EventHub::sysfsNodeChanged(const std::string& sysfsNodePath) {
2548 std::scoped_lock _l(mLock);
2549
2550 // Check in opening devices
2551 for (auto it = mOpeningDevices.begin(); it != mOpeningDevices.end(); it++) {
2552 std::unique_ptr<Device>& device = *it;
2553 if (device->associatedDevice &&
2554 sysfsNodePath.find(device->associatedDevice->sysfsRootPath.string()) !=
2555 std::string::npos &&
2556 device->associatedDevice->isChanged()) {
2557 it = mOpeningDevices.erase(it);
2558 openDeviceLocked(device->path);
2559 }
2560 }
2561
2562 // Check in already added device
2563 std::vector<Device*> devicesToReopen;
2564 for (const auto& [id, device] : mDevices) {
2565 if (device->associatedDevice &&
2566 sysfsNodePath.find(device->associatedDevice->sysfsRootPath.string()) !=
2567 std::string::npos &&
2568 device->associatedDevice->isChanged()) {
2569 devicesToReopen.push_back(device.get());
2570 }
2571 }
2572 for (const auto& device : devicesToReopen) {
2573 closeDeviceLocked(*device);
2574 openDeviceLocked(device->path);
2575 }
2576 devicesToReopen.clear();
2577}
2578
Michael Wrightd02c5b62014-02-10 15:10:22 -08002579void EventHub::createVirtualKeyboardLocked() {
2580 InputDeviceIdentifier identifier;
2581 identifier.name = "Virtual";
2582 identifier.uniqueId = "<virtual>";
2583 assignDescriptorLocked(identifier);
2584
Chris Ye989bb932020-07-04 16:18:59 -07002585 std::unique_ptr<Device> device =
2586 std::make_unique<Device>(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
Harry Cutts33476232023-01-30 19:57:29 +00002587 identifier, /*associatedDevice=*/nullptr);
Chris Ye1b0c7342020-07-28 21:57:03 -07002588 device->classes = InputDeviceClass::KEYBOARD | InputDeviceClass::ALPHAKEY |
2589 InputDeviceClass::DPAD | InputDeviceClass::VIRTUAL;
Chris Ye989bb932020-07-04 16:18:59 -07002590 device->loadKeyMapLocked();
2591 addDeviceLocked(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002592}
2593
Chris Ye989bb932020-07-04 16:18:59 -07002594void EventHub::addDeviceLocked(std::unique_ptr<Device> device) {
Chris Yed3fef462021-03-07 17:10:08 -08002595 reportDeviceAddedForStatisticsLocked(device->identifier, device->classes);
Chris Ye989bb932020-07-04 16:18:59 -07002596 mOpeningDevices.push_back(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002597}
2598
Chris Ye989bb932020-07-04 16:18:59 -07002599int32_t EventHub::getNextControllerNumberLocked(const std::string& name) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002600 if (mControllerNumbers.isFull()) {
2601 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Chris Ye989bb932020-07-04 16:18:59 -07002602 name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002603 return 0;
2604 }
2605 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
2606 // one
2607 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
2608}
2609
Chris Ye989bb932020-07-04 16:18:59 -07002610void EventHub::releaseControllerNumberLocked(int32_t num) {
2611 if (num > 0) {
2612 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002613 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002614}
2615
Chris Ye8594e192020-07-14 10:34:06 -07002616void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002617 Device* device = getDeviceByPathLocked(devicePath);
Chris Ye989bb932020-07-04 16:18:59 -07002618 if (device != nullptr) {
2619 closeDeviceLocked(*device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002620 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002621 }
Chris Ye8594e192020-07-14 10:34:06 -07002622 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002623}
2624
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002625/**
2626 * Find the video device by filename, and close it.
2627 * The video device is closed by path during an inotify event, where we don't have the
2628 * additional context about the video device fd, or the associated input device.
2629 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002630void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002631 // A video device may be owned by an existing input device, or it may be stored in
2632 // the mUnattachedVideoDevices queue. Check both locations.
Chris Ye989bb932020-07-04 16:18:59 -07002633 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002634 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002635 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002636 device->videoDevice = nullptr;
2637 return;
2638 }
2639 }
Siarhei Vishniakouf47c339e2021-12-30 11:22:26 -08002640 std::erase_if(mUnattachedVideoDevices,
2641 [&devicePath](const std::unique_ptr<TouchVideoDevice>& videoDevice) {
2642 return videoDevice->getPath() == devicePath;
2643 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08002644}
2645
2646void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002647 mUnattachedVideoDevices.clear();
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002648 while (!mDevices.empty()) {
2649 closeDeviceLocked(*(mDevices.begin()->second));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002650 }
2651}
2652
Chris Ye989bb932020-07-04 16:18:59 -07002653void EventHub::closeDeviceLocked(Device& device) {
2654 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=%s", device.path.c_str(),
2655 device.identifier.name.c_str(), device.id, device.fd, device.classes.string().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002656
Chris Ye989bb932020-07-04 16:18:59 -07002657 if (device.id == mBuiltInKeyboardId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002658 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Chris Ye989bb932020-07-04 16:18:59 -07002659 device.path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002660 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
2661 }
2662
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002663 unregisterDeviceFromEpollLocked(device);
Chris Ye989bb932020-07-04 16:18:59 -07002664 if (device.videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002665 // This must be done after the video device is removed from epoll
Chris Ye989bb932020-07-04 16:18:59 -07002666 mUnattachedVideoDevices.push_back(std::move(device.videoDevice));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002667 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002668
Chris Ye989bb932020-07-04 16:18:59 -07002669 releaseControllerNumberLocked(device.controllerNumber);
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002670 device.controllerNumber = 0;
Chris Ye989bb932020-07-04 16:18:59 -07002671 device.close();
Chris Ye989bb932020-07-04 16:18:59 -07002672 mClosingDevices.push_back(std::move(mDevices[device.id]));
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002673
Chris Ye989bb932020-07-04 16:18:59 -07002674 mDevices.erase(device.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002675}
2676
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002677base::Result<void> EventHub::readNotifyLocked() {
2678 static constexpr auto EVENT_SIZE = static_cast<ssize_t>(sizeof(inotify_event));
2679 uint8_t eventBuffer[512];
2680 ssize_t sizeRead;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002681
2682 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002683 do {
2684 sizeRead = read(mINotifyFd, eventBuffer, sizeof(eventBuffer));
2685 } while (sizeRead < 0 && errno == EINTR);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002686
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002687 if (sizeRead < EVENT_SIZE) return Errorf("could not get event, %s", strerror(errno));
2688
2689 for (ssize_t eventPos = 0; sizeRead >= EVENT_SIZE;) {
2690 const inotify_event* event;
2691 event = (const inotify_event*)(eventBuffer + eventPos);
2692 if (event->len == 0) continue;
2693
2694 handleNotifyEventLocked(*event);
2695
2696 const ssize_t eventSize = EVENT_SIZE + event->len;
2697 sizeRead -= eventSize;
2698 eventPos += eventSize;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002699 }
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002700 return {};
2701}
2702
2703void EventHub::handleNotifyEventLocked(const inotify_event& event) {
2704 if (event.wd == mDeviceInputWd) {
2705 std::string filename = std::string(DEVICE_INPUT_PATH) + "/" + event.name;
2706 if (event.mask & IN_CREATE) {
2707 openDeviceLocked(filename);
2708 } else {
2709 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
2710 closeDeviceByPathLocked(filename);
2711 }
2712 } else if (event.wd == mDeviceWd) {
2713 if (isV4lTouchNode(event.name)) {
2714 std::string filename = std::string(DEVICE_PATH) + "/" + event.name;
2715 if (event.mask & IN_CREATE) {
2716 openVideoDeviceLocked(filename);
2717 } else {
2718 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
2719 closeVideoDeviceByPathLocked(filename);
2720 }
2721 } else if (strcmp(event.name, "input") == 0 && event.mask & IN_CREATE) {
2722 addDeviceInputInotify();
2723 }
2724 } else {
2725 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event.wd);
2726 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002727}
2728
Chris Ye8594e192020-07-14 10:34:06 -07002729status_t EventHub::scanDirLocked(const std::string& dirname) {
2730 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2731 openDeviceLocked(entry.path());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002732 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002733 return 0;
2734}
2735
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002736/**
2737 * Look for all dirname/v4l-touch* devices, and open them.
2738 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002739status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Chris Ye8594e192020-07-14 10:34:06 -07002740 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2741 if (isV4lTouchNode(entry.path())) {
2742 ALOGI("Found touch video device %s", entry.path().c_str());
2743 openVideoDeviceLocked(entry.path());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002744 }
2745 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002746 return OK;
2747}
2748
Michael Wrightd02c5b62014-02-10 15:10:22 -08002749void EventHub::requestReopenDevices() {
2750 ALOGV("requestReopenDevices() called");
2751
Chris Ye87143712020-11-10 05:05:58 +00002752 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002753 mNeedToReopenDevices = true;
2754}
2755
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002756void EventHub::dump(std::string& dump) const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002757 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002758
2759 { // acquire lock
Chris Ye87143712020-11-10 05:05:58 +00002760 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002761
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002762 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002763
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002764 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002765
Chris Ye989bb932020-07-04 16:18:59 -07002766 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002767 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002768 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002769 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002770 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002771 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002772 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002773 }
Chris Ye1b0c7342020-07-28 21:57:03 -07002774 dump += StringPrintf(INDENT3 "Classes: %s\n", device->classes.string().c_str());
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002775 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002776 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002777 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
2778 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002779 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002780 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002781 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002782 "product=0x%04x, version=0x%04x, bluetoothAddress=%s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002783 device->identifier.bus, device->identifier.vendor,
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002784 device->identifier.product, device->identifier.version,
2785 toString(device->identifier.bluetoothAddress).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002786 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002787 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002788 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002789 device->keyMap.keyCharacterMapFile.c_str());
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00002790 if (device->associatedDevice && device->associatedDevice->layoutInfo) {
2791 dump += StringPrintf(INDENT3 "LanguageTag: %s\n",
2792 device->associatedDevice->layoutInfo->languageTag.c_str());
2793 dump += StringPrintf(INDENT3 "LayoutType: %s\n",
2794 device->associatedDevice->layoutInfo->layoutType.c_str());
2795 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002796 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002797 device->configurationFile.c_str());
Prabir Pradhan51894782022-08-23 16:29:10 +00002798 dump += StringPrintf(INDENT3 "VideoDevice: %s\n",
2799 device->videoDevice ? device->videoDevice->dump().c_str()
2800 : "<none>");
2801 dump += StringPrintf(INDENT3 "SysfsDevicePath: %s\n",
2802 device->associatedDevice
2803 ? device->associatedDevice->sysfsRootPath.c_str()
2804 : "<none>");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002805 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002806
2807 dump += INDENT "Unattached video devices:\n";
2808 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
2809 dump += INDENT2 + videoDevice->dump() + "\n";
2810 }
2811 if (mUnattachedVideoDevices.empty()) {
2812 dump += INDENT2 "<none>\n";
2813 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002814 } // release lock
2815}
2816
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002817void EventHub::monitor() const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002818 // Acquire and release the lock to ensure that the event hub has not deadlocked.
Chris Ye1c2e0892020-11-30 21:41:44 -08002819 std::unique_lock<std::mutex> lock(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002820}
2821
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00002822std::string EventHub::AssociatedDevice::dump() const {
2823 return StringPrintf("path=%s, numBatteries=%zu, numLight=%zu", sysfsRootPath.c_str(),
2824 batteryInfos.size(), lightInfos.size());
2825}
2826
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002827} // namespace android