blob: 3ca691efbaa4ae6b26194af5bec20de8429829e3 [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),
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000541 isVirtual(fd < 0),
542 currentFrameDropped(false) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800543
544EventHub::Device::~Device() {
545 close();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800546}
547
548void EventHub::Device::close() {
549 if (fd >= 0) {
550 ::close(fd);
551 fd = -1;
552 }
553}
554
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700555status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100556 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700557 if (fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100558 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700559 return -errno;
560 }
561 enabled = true;
562 return OK;
563}
564
565status_t EventHub::Device::disable() {
566 close();
567 enabled = false;
568 return OK;
569}
570
Chris Ye989bb932020-07-04 16:18:59 -0700571bool EventHub::Device::hasValidFd() const {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700572 return !isVirtual && enabled;
573}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800574
Chris Ye3a1e4462020-08-12 10:13:15 -0700575const std::shared_ptr<KeyCharacterMap> EventHub::Device::getKeyCharacterMap() const {
Chris Ye989bb932020-07-04 16:18:59 -0700576 return keyMap.keyCharacterMap;
577}
578
579template <std::size_t N>
580status_t EventHub::Device::readDeviceBitMask(unsigned long ioctlCode, BitArray<N>& bitArray) {
581 if (!hasValidFd()) {
582 return BAD_VALUE;
583 }
584 if ((_IOC_SIZE(ioctlCode) == 0)) {
585 ioctlCode |= _IOC(0, 0, 0, bitArray.bytes());
586 }
587
588 typename BitArray<N>::Buffer buffer;
589 status_t ret = ioctl(fd, ioctlCode, buffer.data());
590 bitArray.loadFromBuffer(buffer);
591 return ret;
592}
593
594void EventHub::Device::configureFd() {
595 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
596 if (classes.test(InputDeviceClass::KEYBOARD)) {
597 // Disable kernel key repeat since we handle it ourselves
598 unsigned int repeatRate[] = {0, 0};
599 if (ioctl(fd, EVIOCSREP, repeatRate)) {
600 ALOGW("Unable to disable kernel key repeat for %s: %s", path.c_str(), strerror(errno));
601 }
602 }
603
604 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
605 // associated with input events. This is important because the input system
606 // uses the timestamps extensively and assumes they were recorded using the monotonic
607 // clock.
608 int clockId = CLOCK_MONOTONIC;
Chris Yef59a2f42020-10-16 12:55:26 -0700609 if (classes.test(InputDeviceClass::SENSOR)) {
610 // Each new sensor event should use the same time base as
611 // SystemClock.elapsedRealtimeNanos().
612 clockId = CLOCK_BOOTTIME;
613 }
Chris Ye989bb932020-07-04 16:18:59 -0700614 bool usingClockIoctl = !ioctl(fd, EVIOCSCLOCKID, &clockId);
615 ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000616
617 // Query the initial state of keys and switches, which is tracked by EventHub.
618 readDeviceState();
619}
620
621void EventHub::Device::readDeviceState() {
622 if (readDeviceBitMask(EVIOCGKEY(0), keyState) < 0) {
623 ALOGD("Unable to query the global key state for %s: %s", path.c_str(), strerror(errno));
624 }
625 if (readDeviceBitMask(EVIOCGSW(0), swState) < 0) {
626 ALOGD("Unable to query the global switch state for %s: %s", path.c_str(), strerror(errno));
627 }
Prabir Pradhan341d0782023-07-14 19:04:10 +0000628
629 // Read absolute axis info and values for all available axes for the device.
630 populateAbsoluteAxisStates();
631}
632
633void EventHub::Device::populateAbsoluteAxisStates() {
634 absState.clear();
635
636 for (int axis = 0; axis <= ABS_MAX; axis++) {
637 if (!absBitmask.test(axis)) {
638 continue;
639 }
640 struct input_absinfo info {};
641 if (ioctl(fd, EVIOCGABS(axis), &info)) {
642 ALOGE("Error reading absolute controller %d for device %s fd %d: %s", axis,
643 identifier.name.c_str(), fd, strerror(errno));
644 continue;
645 }
Prabir Pradhan341d0782023-07-14 19:04:10 +0000646 auto& [axisInfo, value] = absState[axis];
647 axisInfo.valid = true;
648 axisInfo.minValue = info.minimum;
649 axisInfo.maxValue = info.maximum;
650 axisInfo.flat = info.flat;
651 axisInfo.fuzz = info.fuzz;
652 axisInfo.resolution = info.resolution;
653 value = info.value;
654 }
Chris Ye989bb932020-07-04 16:18:59 -0700655}
656
657bool EventHub::Device::hasKeycodeLocked(int keycode) const {
658 if (!keyMap.haveKeyLayout()) {
659 return false;
660 }
661
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700662 std::vector<int32_t> scanCodes = keyMap.keyLayoutMap->findScanCodesForKey(keycode);
Chris Ye989bb932020-07-04 16:18:59 -0700663 const size_t N = scanCodes.size();
664 for (size_t i = 0; i < N && i <= KEY_MAX; i++) {
665 int32_t sc = scanCodes[i];
666 if (sc >= 0 && sc <= KEY_MAX && keyBitmask.test(sc)) {
667 return true;
668 }
669 }
670
Charles Linaadf8d52023-03-30 13:34:54 +0800671 std::vector<int32_t> usageCodes = keyMap.keyLayoutMap->findUsageCodesForKey(keycode);
672 if (usageCodes.size() > 0 && mscBitmask.test(MSC_SCAN)) {
673 return true;
674 }
675
Chris Ye989bb932020-07-04 16:18:59 -0700676 return false;
677}
678
679void EventHub::Device::loadConfigurationLocked() {
680 configurationFile =
681 getInputDeviceConfigurationFilePathByDeviceIdentifier(identifier,
682 InputDeviceConfigurationFileType::
683 CONFIGURATION);
684 if (configurationFile.empty()) {
685 ALOGD("No input device configuration file found for device '%s'.", identifier.name.c_str());
686 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500687 android::base::Result<std::unique_ptr<PropertyMap>> propertyMap =
688 PropertyMap::load(configurationFile.c_str());
689 if (!propertyMap.ok()) {
Chris Ye989bb932020-07-04 16:18:59 -0700690 ALOGE("Error loading input device configuration file for device '%s'. "
691 "Using default configuration.",
692 identifier.name.c_str());
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500693 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500694 configuration = std::move(*propertyMap);
Chris Ye989bb932020-07-04 16:18:59 -0700695 }
696 }
697}
698
699bool EventHub::Device::loadVirtualKeyMapLocked() {
700 // The virtual key map is supplied by the kernel as a system board property file.
701 std::string propPath = "/sys/board_properties/virtualkeys.";
702 propPath += identifier.getCanonicalName();
703 if (access(propPath.c_str(), R_OK)) {
704 return false;
705 }
706 virtualKeyMap = VirtualKeyMap::load(propPath);
707 return virtualKeyMap != nullptr;
708}
709
710status_t EventHub::Device::loadKeyMapLocked() {
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500711 return keyMap.load(identifier, configuration.get());
Chris Ye989bb932020-07-04 16:18:59 -0700712}
713
714bool EventHub::Device::isExternalDeviceLocked() {
715 if (configuration) {
Harry Cuttsf13161a2023-03-08 14:15:49 +0000716 std::optional<bool> isInternal = configuration->getBool("device.internal");
717 if (isInternal.has_value()) {
718 return !isInternal.value();
Chris Ye989bb932020-07-04 16:18:59 -0700719 }
720 }
721 return identifier.bus == BUS_USB || identifier.bus == BUS_BLUETOOTH;
722}
723
724bool EventHub::Device::deviceHasMicLocked() {
725 if (configuration) {
Harry Cuttsf13161a2023-03-08 14:15:49 +0000726 std::optional<bool> hasMic = configuration->getBool("audio.mic");
727 if (hasMic.has_value()) {
728 return hasMic.value();
Chris Ye989bb932020-07-04 16:18:59 -0700729 }
730 }
731 return false;
732}
733
734void EventHub::Device::setLedStateLocked(int32_t led, bool on) {
735 int32_t sc;
736 if (hasValidFd() && mapLed(led, &sc) != NAME_NOT_FOUND) {
737 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -0700738 ev.input_event_sec = 0;
739 ev.input_event_usec = 0;
Chris Ye989bb932020-07-04 16:18:59 -0700740 ev.type = EV_LED;
741 ev.code = sc;
742 ev.value = on ? 1 : 0;
743
744 ssize_t nWrite;
745 do {
746 nWrite = write(fd, &ev, sizeof(struct input_event));
747 } while (nWrite == -1 && errno == EINTR);
748 }
749}
750
751void EventHub::Device::setLedForControllerLocked() {
752 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
753 setLedStateLocked(ALED_CONTROLLER_1 + i, controllerNumber == i + 1);
754 }
755}
756
757status_t EventHub::Device::mapLed(int32_t led, int32_t* outScanCode) const {
758 if (!keyMap.haveKeyLayout()) {
759 return NAME_NOT_FOUND;
760 }
761
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700762 std::optional<int32_t> scanCode = keyMap.keyLayoutMap->findScanCodeForLed(led);
763 if (scanCode.has_value()) {
764 if (*scanCode >= 0 && *scanCode <= LED_MAX && ledBitmask.test(*scanCode)) {
765 *outScanCode = *scanCode;
Chris Ye989bb932020-07-04 16:18:59 -0700766 return NO_ERROR;
767 }
768 }
769 return NAME_NOT_FOUND;
770}
771
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000772void EventHub::Device::trackInputEvent(const struct input_event& event) {
773 switch (event.type) {
774 case EV_KEY: {
775 LOG_ALWAYS_FATAL_IF(!currentFrameDropped &&
776 !keyState.set(static_cast<size_t>(event.code),
777 event.value != 0),
Prabir Pradhan10301422023-07-26 21:48:30 +0000778 "%s: device '%s' received invalid EV_KEY event code: %s value: %d",
779 __func__, identifier.name.c_str(),
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000780 InputEventLookup::getLinuxEvdevLabel(EV_KEY, event.code, 1)
Prabir Pradhan10301422023-07-26 21:48:30 +0000781 .code.c_str(),
782 event.value);
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000783 break;
784 }
785 case EV_SW: {
786 LOG_ALWAYS_FATAL_IF(!currentFrameDropped &&
787 !swState.set(static_cast<size_t>(event.code),
788 event.value != 0),
Prabir Pradhan10301422023-07-26 21:48:30 +0000789 "%s: device '%s' received invalid EV_SW event code: %s value: %d",
790 __func__, identifier.name.c_str(),
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000791 InputEventLookup::getLinuxEvdevLabel(EV_SW, event.code, 1)
Prabir Pradhan10301422023-07-26 21:48:30 +0000792 .code.c_str(),
793 event.value);
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000794 break;
795 }
Prabir Pradhan341d0782023-07-14 19:04:10 +0000796 case EV_ABS: {
Prabir Pradhan10301422023-07-26 21:48:30 +0000797 if (currentFrameDropped) {
798 break;
799 }
Prabir Pradhan341d0782023-07-14 19:04:10 +0000800 auto it = absState.find(event.code);
Prabir Pradhan10301422023-07-26 21:48:30 +0000801 LOG_ALWAYS_FATAL_IF(it == absState.end(),
802 "%s: device '%s' received invalid EV_ABS event code: %s value: %d",
803 __func__, identifier.name.c_str(),
Prabir Pradhan341d0782023-07-14 19:04:10 +0000804 InputEventLookup::getLinuxEvdevLabel(EV_ABS, event.code, 0)
Prabir Pradhan10301422023-07-26 21:48:30 +0000805 .code.c_str(),
806 event.value);
Prabir Pradhan341d0782023-07-14 19:04:10 +0000807 it->second.value = event.value;
808 break;
809 }
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000810 case EV_SYN: {
811 switch (event.code) {
812 case SYN_REPORT:
Arpit Singh1c3d8552024-01-08 14:16:28 +0000813 if (currentFrameDropped) {
814 // To recover after a SYN_DROPPED, we need to query the state of the device
815 // to synchronize our device state with the kernel's to account for the
816 // dropped events on receiving the next SYN_REPORT.
817 // Note we don't drop the SYN_REPORT at this point but it is used by the
818 // InputDevice to reset and repopulate mapper state
819 readDeviceState();
820 currentFrameDropped = false;
821 }
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000822 break;
823 case SYN_DROPPED:
824 // When we receive SYN_DROPPED, all events in the current frame should be
Arpit Singh1c3d8552024-01-08 14:16:28 +0000825 // dropped up to and including next SYN_REPORT
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000826 currentFrameDropped = true;
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000827 break;
828 default:
829 break;
830 }
831 break;
832 }
833 default:
834 break;
835 }
836}
837
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100838/**
839 * Get the capabilities for the current process.
840 * Crashes the system if unable to create / check / destroy the capabilities object.
841 */
842class Capabilities final {
843public:
844 explicit Capabilities() {
845 mCaps = cap_get_proc();
846 LOG_ALWAYS_FATAL_IF(mCaps == nullptr, "Could not get capabilities of the current process");
847 }
848
849 /**
850 * Check whether the current process has a specific capability
851 * in the set of effective capabilities.
852 * Return CAP_SET if the process has the requested capability
853 * Return CAP_CLEAR otherwise.
854 */
855 cap_flag_value_t checkEffectiveCapability(cap_value_t capability) {
856 cap_flag_value_t value;
857 const int result = cap_get_flag(mCaps, capability, CAP_EFFECTIVE, &value);
858 LOG_ALWAYS_FATAL_IF(result == -1, "Could not obtain the requested capability");
859 return value;
860 }
861
862 ~Capabilities() {
863 const int result = cap_free(mCaps);
864 LOG_ALWAYS_FATAL_IF(result == -1, "Could not release the capabilities structure");
865 }
866
867private:
868 cap_t mCaps;
869};
870
871static void ensureProcessCanBlockSuspend() {
872 Capabilities capabilities;
873 const bool canBlockSuspend =
874 capabilities.checkEffectiveCapability(CAP_BLOCK_SUSPEND) == CAP_SET;
875 LOG_ALWAYS_FATAL_IF(!canBlockSuspend,
876 "Input must be able to block suspend to properly process events");
877}
878
Michael Wrightd02c5b62014-02-10 15:10:22 -0800879// --- EventHub ---
880
Michael Wrightd02c5b62014-02-10 15:10:22 -0800881const int EventHub::EPOLL_MAX_EVENTS;
882
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700883EventHub::EventHub(void)
884 : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
885 mNextDeviceId(1),
886 mControllerNumbers(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800887 mNeedToSendFinishedDeviceScan(false),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700888 mNeedToReopenDevices(false),
889 mNeedToScanDevices(true),
890 mPendingEventCount(0),
891 mPendingEventIndex(0),
892 mPendingINotify(false) {
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100893 ensureProcessCanBlockSuspend();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800894
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800895 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800896 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800897
Michael Wright8e9a8562022-02-09 13:44:29 +0000898 mINotifyFd = inotify_init1(IN_CLOEXEC);
Prabir Pradhan952e65b2022-06-23 17:49:55 +0000899 LOG_ALWAYS_FATAL_IF(mINotifyFd < 0, "Could not create inotify instance: %s", strerror(errno));
Usama Arifb27c8e62021-06-03 16:44:09 +0100900
901 std::error_code errorCode;
902 bool isDeviceInotifyAdded = false;
903 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
904 addDeviceInputInotify();
Philip Quinn39b81682019-01-09 22:20:39 -0800905 } else {
Usama Arifb27c8e62021-06-03 16:44:09 +0100906 addDeviceInotify();
907 isDeviceInotifyAdded = true;
908 if (errorCode) {
909 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
910 errorCode.message().c_str());
911 }
912 }
913
914 if (isV4lScanningEnabled() && !isDeviceInotifyAdded) {
915 addDeviceInotify();
916 } else {
Philip Quinn39b81682019-01-09 22:20:39 -0800917 ALOGI("Video device scanning disabled");
918 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800919
Siarhei Vishniakou2d0e9482019-09-24 12:52:47 +0100920 struct epoll_event eventItem = {};
921 eventItem.events = EPOLLIN | EPOLLWAKEUP;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700922 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800923 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800924 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
925
926 int wakeFds[2];
Michael Wright8e9a8562022-02-09 13:44:29 +0000927 result = pipe2(wakeFds, O_CLOEXEC);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800928 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
929
930 mWakeReadPipeFd = wakeFds[0];
931 mWakeWritePipeFd = wakeFds[1];
932
933 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
934 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700935 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800936
937 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
938 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700939 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800940
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700941 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800942 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
943 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700944 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800945}
946
947EventHub::~EventHub(void) {
948 closeAllDevicesLocked();
949
Michael Wrightd02c5b62014-02-10 15:10:22 -0800950 ::close(mEpollFd);
951 ::close(mINotifyFd);
952 ::close(mWakeReadPipeFd);
953 ::close(mWakeWritePipeFd);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800954}
955
Usama Arifb27c8e62021-06-03 16:44:09 +0100956/**
957 * On devices that don't have any input devices (like some development boards), the /dev/input
958 * directory will be absent. However, the user may still plug in an input device at a later time.
959 * Add watch for contents of /dev/input only when /dev/input appears.
960 */
961void EventHub::addDeviceInputInotify() {
962 mDeviceInputWd = inotify_add_watch(mINotifyFd, DEVICE_INPUT_PATH, IN_DELETE | IN_CREATE);
963 LOG_ALWAYS_FATAL_IF(mDeviceInputWd < 0, "Could not register INotify for %s: %s",
964 DEVICE_INPUT_PATH, strerror(errno));
965}
966
967void EventHub::addDeviceInotify() {
968 mDeviceWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
969 LOG_ALWAYS_FATAL_IF(mDeviceWd < 0, "Could not register INotify for %s: %s", DEVICE_PATH,
970 strerror(errno));
971}
972
Michael Wrightd02c5b62014-02-10 15:10:22 -0800973InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000974 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800975 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700976 return device != nullptr ? device->identifier : InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800977}
978
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700979ftl::Flags<InputDeviceClass> EventHub::getDeviceClasses(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000980 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800981 Device* device = getDeviceLocked(deviceId);
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700982 return device != nullptr ? device->classes : ftl::Flags<InputDeviceClass>(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800983}
984
985int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000986 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800987 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700988 return device != nullptr ? device->controllerNumber : 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800989}
990
Harry Cuttsc34f7582023-03-07 16:23:30 +0000991std::optional<PropertyMap> EventHub::getConfiguration(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000992 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800993 Device* device = getDeviceLocked(deviceId);
Harry Cuttsc34f7582023-03-07 16:23:30 +0000994 if (device == nullptr || device->configuration == nullptr) {
995 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -0800996 }
Harry Cuttsc34f7582023-03-07 16:23:30 +0000997 return *device->configuration;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800998}
999
1000status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001001 RawAbsoluteAxisInfo* outAxisInfo) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001002 outAxisInfo->clear();
Arpit Singh77140f42023-06-13 11:35:27 +00001003 if (axis < 0 || axis > ABS_MAX) {
Prabir Pradhan341d0782023-07-14 19:04:10 +00001004 return NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001005 }
Arpit Singh77140f42023-06-13 11:35:27 +00001006 std::scoped_lock _l(mLock);
Prabir Pradhan341d0782023-07-14 19:04:10 +00001007 const Device* device = getDeviceLocked(deviceId);
Arpit Singh77140f42023-06-13 11:35:27 +00001008 if (device == nullptr) {
Prabir Pradhan341d0782023-07-14 19:04:10 +00001009 return NAME_NOT_FOUND;
Arpit Singh77140f42023-06-13 11:35:27 +00001010 }
Prabir Pradhan341d0782023-07-14 19:04:10 +00001011 // We can read the RawAbsoluteAxisInfo even if the device is disabled and doesn't have a valid
1012 // fd, because the info is populated once when the device is first opened, and it doesn't change
1013 // throughout the device lifecycle.
1014 auto it = device->absState.find(axis);
1015 if (it == device->absState.end()) {
1016 return NAME_NOT_FOUND;
Arpit Singh77140f42023-06-13 11:35:27 +00001017 }
Prabir Pradhan341d0782023-07-14 19:04:10 +00001018 *outAxisInfo = it->second.info;
Arpit Singh77140f42023-06-13 11:35:27 +00001019 return OK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001020}
1021
1022bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
1023 if (axis >= 0 && axis <= REL_MAX) {
Chris Ye87143712020-11-10 05:05:58 +00001024 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001025 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001026 return device != nullptr ? device->relBitmask.test(axis) : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001027 }
1028 return false;
1029}
1030
1031bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
Chris Ye87143712020-11-10 05:05:58 +00001032 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001033
Chris Ye989bb932020-07-04 16:18:59 -07001034 Device* device = getDeviceLocked(deviceId);
1035 return property >= 0 && property <= INPUT_PROP_MAX && device != nullptr
1036 ? device->propBitmask.test(property)
1037 : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001038}
1039
Chris Yef59a2f42020-10-16 12:55:26 -07001040bool EventHub::hasMscEvent(int32_t deviceId, int mscEvent) const {
1041 std::scoped_lock _l(mLock);
1042
1043 Device* device = getDeviceLocked(deviceId);
1044 return mscEvent >= 0 && mscEvent <= MSC_MAX && device != nullptr
1045 ? device->mscBitmask.test(mscEvent)
1046 : false;
1047}
1048
Michael Wrightd02c5b62014-02-10 15:10:22 -08001049int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001050 if (scanCode < 0 || scanCode > KEY_MAX) {
1051 return AKEY_STATE_UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001052 }
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001053 std::scoped_lock _l(mLock);
1054 const Device* device = getDeviceLocked(deviceId);
1055 if (device == nullptr || !device->hasValidFd() || !device->keyBitmask.test(scanCode)) {
1056 return AKEY_STATE_UNKNOWN;
1057 }
1058 return device->keyState.test(scanCode) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001059}
1060
1061int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
Chris Ye87143712020-11-10 05:05:58 +00001062 std::scoped_lock _l(mLock);
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001063 const Device* device = getDeviceLocked(deviceId);
1064 if (device == nullptr || !device->hasValidFd() || !device->keyMap.haveKeyLayout()) {
1065 return AKEY_STATE_UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001066 }
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001067 const std::vector<int32_t> scanCodes =
1068 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode);
1069 if (scanCodes.empty()) {
1070 return AKEY_STATE_UNKNOWN;
1071 }
1072 return std::any_of(scanCodes.begin(), scanCodes.end(),
1073 [&device](const int32_t sc) {
1074 return sc >= 0 && sc <= KEY_MAX && device->keyState.test(sc);
1075 })
1076 ? AKEY_STATE_DOWN
1077 : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001078}
1079
Philip Junker4af3b3d2021-12-14 10:36:55 +01001080int32_t EventHub::getKeyCodeForKeyLocation(int32_t deviceId, int32_t locationKeyCode) const {
1081 std::scoped_lock _l(mLock);
1082
1083 Device* device = getDeviceLocked(deviceId);
1084 if (device == nullptr || !device->hasValidFd() || device->keyMap.keyCharacterMap == nullptr ||
1085 device->keyMap.keyLayoutMap == nullptr) {
1086 return AKEYCODE_UNKNOWN;
1087 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001088 std::vector<int32_t> scanCodes =
1089 device->keyMap.keyLayoutMap->findScanCodesForKey(locationKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +01001090 if (scanCodes.empty()) {
1091 ALOGW("Failed to get key code for key location: no scan code maps to key code %d for input"
1092 "device %d",
1093 locationKeyCode, deviceId);
1094 return AKEYCODE_UNKNOWN;
1095 }
1096 if (scanCodes.size() > 1) {
1097 ALOGW("Multiple scan codes map to the same key code %d, returning only the first match",
1098 locationKeyCode);
1099 }
1100 int32_t outKeyCode;
1101 status_t mapKeyRes =
Harry Cutts33476232023-01-30 19:57:29 +00001102 device->getKeyCharacterMap()->mapKey(scanCodes[0], /*usageCode=*/0, &outKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +01001103 switch (mapKeyRes) {
1104 case OK:
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001105 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +01001106 case NAME_NOT_FOUND:
1107 // key character map doesn't re-map this scanCode, hence the keyCode remains the same
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001108 outKeyCode = locationKeyCode;
1109 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +01001110 default:
1111 ALOGW("Failed to get key code for key location: Key character map returned error %s",
1112 statusToString(mapKeyRes).c_str());
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001113 outKeyCode = AKEYCODE_UNKNOWN;
1114 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +01001115 }
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001116 // Remap if there is a Key remapping added to the KCM and return the remapped key
1117 return device->getKeyCharacterMap()->applyKeyRemapping(outKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +01001118}
1119
Michael Wrightd02c5b62014-02-10 15:10:22 -08001120int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001121 if (sw < 0 || sw > SW_MAX) {
1122 return AKEY_STATE_UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001123 }
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001124 std::scoped_lock _l(mLock);
1125 const Device* device = getDeviceLocked(deviceId);
1126 if (device == nullptr || !device->hasValidFd() || !device->swBitmask.test(sw)) {
1127 return AKEY_STATE_UNKNOWN;
1128 }
1129 return device->swState.test(sw) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001130}
1131
1132status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
1133 *outValue = 0;
Prabir Pradhan341d0782023-07-14 19:04:10 +00001134 if (axis < 0 || axis > ABS_MAX) {
1135 return NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001136 }
Prabir Pradhan341d0782023-07-14 19:04:10 +00001137 std::scoped_lock _l(mLock);
1138 const Device* device = getDeviceLocked(deviceId);
1139 if (device == nullptr || !device->hasValidFd()) {
1140 return NAME_NOT_FOUND;
1141 }
1142 const auto it = device->absState.find(axis);
1143 if (it == device->absState.end()) {
1144 return NAME_NOT_FOUND;
1145 }
1146 *outValue = it->second.value;
1147 return OK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001148}
1149
Arpit Singh4b4a4572023-11-24 18:19:56 +00001150base::Result<std::vector<int32_t>> EventHub::getMtSlotValues(int32_t deviceId, int32_t axis,
1151 size_t slotCount) const {
1152 std::scoped_lock _l(mLock);
1153 const Device* device = getDeviceLocked(deviceId);
1154 if (device == nullptr || !device->hasValidFd() || !device->absBitmask.test(axis)) {
1155 return base::ResultError("device problem or axis not supported", NAME_NOT_FOUND);
1156 }
1157 std::vector<int32_t> outValues(slotCount + 1);
1158 outValues[0] = axis;
1159 const size_t bufferSize = outValues.size() * sizeof(int32_t);
1160 if (ioctl(device->fd, EVIOCGMTSLOTS(bufferSize), outValues.data()) != OK) {
1161 return base::ErrnoError();
1162 }
1163 return std::move(outValues);
1164}
1165
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001166bool EventHub::markSupportedKeyCodes(int32_t deviceId, const std::vector<int32_t>& keyCodes,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001167 uint8_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +00001168 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001169
1170 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001171 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001172 for (size_t codeIndex = 0; codeIndex < keyCodes.size(); codeIndex++) {
Sergej Salnikove5420e72023-05-11 11:52:54 +00001173 if (device->hasKeycodeLocked(keyCodes[codeIndex])) {
1174 outFlags[codeIndex] = 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001175 }
1176 }
1177 return true;
1178 }
1179 return false;
1180}
1181
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001182void EventHub::addKeyRemapping(int32_t deviceId, int32_t fromKeyCode, int32_t toKeyCode) const {
1183 std::scoped_lock _l(mLock);
1184 Device* device = getDeviceLocked(deviceId);
1185 if (device == nullptr) {
1186 return;
1187 }
1188 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
1189 if (kcm) {
1190 kcm->addKeyRemapping(fromKeyCode, toKeyCode);
1191 }
1192}
1193
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001194status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
1195 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +00001196 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001197 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001198 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001199
Chris Ye66fbac32020-07-06 20:36:43 -07001200 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001201 // Check the key character map first.
Chris Ye3a1e4462020-08-12 10:13:15 -07001202 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
1203 if (kcm) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001204 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
1205 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001206 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001207 }
1208 }
1209
1210 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001211 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -08001212 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001213 status = NO_ERROR;
1214 }
1215 }
1216
1217 if (status == NO_ERROR) {
Chris Ye3a1e4462020-08-12 10:13:15 -07001218 if (kcm) {
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001219 // Remap keys based on user-defined key remappings and key behavior defined in the
1220 // corresponding kcm file
1221 *outKeycode = kcm->applyKeyRemapping(*outKeycode);
1222
1223 // Remap keys based on Key behavior defined in KCM file
1224 std::tie(*outKeycode, *outMetaState) =
1225 kcm->applyKeyBehavior(*outKeycode, metaState);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001226 } else {
1227 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228 }
1229 }
1230 }
1231
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001232 if (status != NO_ERROR) {
1233 *outKeycode = 0;
1234 *outFlags = 0;
1235 *outMetaState = metaState;
1236 }
1237
1238 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001239}
1240
1241status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
Chris Ye87143712020-11-10 05:05:58 +00001242 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243 Device* device = getDeviceLocked(deviceId);
1244
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001245 if (device == nullptr || !device->keyMap.haveKeyLayout()) {
1246 return NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001247 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001248 std::optional<AxisInfo> info = device->keyMap.keyLayoutMap->mapAxis(scanCode);
1249 if (!info.has_value()) {
1250 return NAME_NOT_FOUND;
1251 }
1252 *outAxisInfo = *info;
1253 return NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001254}
1255
Chris Yef59a2f42020-10-16 12:55:26 -07001256base::Result<std::pair<InputDeviceSensorType, int32_t>> EventHub::mapSensor(int32_t deviceId,
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001257 int32_t absCode) const {
Chris Yef59a2f42020-10-16 12:55:26 -07001258 std::scoped_lock _l(mLock);
1259 Device* device = getDeviceLocked(deviceId);
1260
1261 if (device != nullptr && device->keyMap.haveKeyLayout()) {
1262 return device->keyMap.keyLayoutMap->mapSensor(absCode);
1263 }
1264 return Errorf("Device not found or device has no key layout.");
1265}
1266
Chris Yee2b1e5c2021-03-10 22:45:12 -08001267// Gets the battery info map from battery ID to RawBatteryInfo of the miscellaneous device
1268// associated with the device ID. Returns an empty map if no miscellaneous device found.
1269const std::unordered_map<int32_t, RawBatteryInfo>& EventHub::getBatteryInfoLocked(
1270 int32_t deviceId) const {
1271 static const std::unordered_map<int32_t, RawBatteryInfo> EMPTY_BATTERY_INFO = {};
1272 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001273 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001274 return EMPTY_BATTERY_INFO;
1275 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001276 return device->associatedDevice->batteryInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001277}
1278
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001279std::vector<int32_t> EventHub::getRawBatteryIds(int32_t deviceId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001280 std::scoped_lock _l(mLock);
1281 std::vector<int32_t> batteryIds;
1282
Prabir Pradhan51894782022-08-23 16:29:10 +00001283 for (const auto& [id, info] : getBatteryInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001284 batteryIds.push_back(id);
1285 }
1286
1287 return batteryIds;
1288}
1289
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001290std::optional<RawBatteryInfo> EventHub::getRawBatteryInfo(int32_t deviceId,
1291 int32_t batteryId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001292 std::scoped_lock _l(mLock);
1293
1294 const auto infos = getBatteryInfoLocked(deviceId);
1295
1296 auto it = infos.find(batteryId);
1297 if (it != infos.end()) {
1298 return it->second;
1299 }
1300
1301 return std::nullopt;
1302}
1303
1304// Gets the light info map from light ID to RawLightInfo of the miscellaneous device associated
Prabir Pradhan51894782022-08-23 16:29:10 +00001305// with the device ID. Returns an empty map if no miscellaneous device found.
Chris Yee2b1e5c2021-03-10 22:45:12 -08001306const std::unordered_map<int32_t, RawLightInfo>& EventHub::getLightInfoLocked(
1307 int32_t deviceId) const {
1308 static const std::unordered_map<int32_t, RawLightInfo> EMPTY_LIGHT_INFO = {};
1309 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001310 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001311 return EMPTY_LIGHT_INFO;
1312 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001313 return device->associatedDevice->lightInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001314}
1315
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001316std::vector<int32_t> EventHub::getRawLightIds(int32_t deviceId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001317 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001318 std::vector<int32_t> lightIds;
1319
Prabir Pradhan51894782022-08-23 16:29:10 +00001320 for (const auto& [id, info] : getLightInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001321 lightIds.push_back(id);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001322 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001323
Chris Ye3fdbfef2021-01-06 18:45:18 -08001324 return lightIds;
1325}
1326
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001327std::optional<RawLightInfo> EventHub::getRawLightInfo(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001328 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001329
Chris Yee2b1e5c2021-03-10 22:45:12 -08001330 const auto infos = getLightInfoLocked(deviceId);
1331
1332 auto it = infos.find(lightId);
1333 if (it != infos.end()) {
1334 return it->second;
Chris Ye3fdbfef2021-01-06 18:45:18 -08001335 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001336
Chris Ye3fdbfef2021-01-06 18:45:18 -08001337 return std::nullopt;
1338}
1339
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001340std::optional<int32_t> EventHub::getLightBrightness(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001341 std::scoped_lock _l(mLock);
1342
Chris Yee2b1e5c2021-03-10 22:45:12 -08001343 const auto infos = getLightInfoLocked(deviceId);
1344 auto it = infos.find(lightId);
1345 if (it == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001346 return std::nullopt;
1347 }
1348 std::string buffer;
1349 if (!base::ReadFileToString(it->second.path / LIGHT_NODES.at(InputLightClass::BRIGHTNESS),
1350 &buffer)) {
1351 return std::nullopt;
1352 }
1353 return std::stoi(buffer);
1354}
1355
1356std::optional<std::unordered_map<LightColor, int32_t>> EventHub::getLightIntensities(
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001357 int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001358 std::scoped_lock _l(mLock);
1359
Chris Yee2b1e5c2021-03-10 22:45:12 -08001360 const auto infos = getLightInfoLocked(deviceId);
1361 auto lightIt = infos.find(lightId);
1362 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001363 return std::nullopt;
1364 }
1365
1366 auto ret =
1367 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1368
1369 if (!ret.has_value()) {
1370 return std::nullopt;
1371 }
1372 std::array<LightColor, COLOR_NUM> colors = ret.value();
1373
1374 std::string intensityStr;
1375 if (!base::ReadFileToString(lightIt->second.path /
1376 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY),
1377 &intensityStr)) {
1378 return std::nullopt;
1379 }
1380
1381 // Intensity node outputs 3 color values
1382 std::regex intensityPattern("([0-9]+)\\s([0-9]+)\\s([0-9]+)[\\n]");
1383 std::smatch results;
1384
1385 if (!std::regex_match(intensityStr, results, intensityPattern)) {
1386 return std::nullopt;
1387 }
1388 std::unordered_map<LightColor, int32_t> intensities;
1389 for (size_t i = 1; i < results.size(); i++) {
1390 int value = std::stoi(results[i].str());
1391 intensities.emplace(colors[i - 1], value);
1392 }
1393 return intensities;
1394}
1395
1396void EventHub::setLightBrightness(int32_t deviceId, int32_t lightId, int32_t brightness) {
1397 std::scoped_lock _l(mLock);
1398
Chris Yee2b1e5c2021-03-10 22:45:12 -08001399 const auto infos = getLightInfoLocked(deviceId);
1400 auto lightIt = infos.find(lightId);
1401 if (lightIt == infos.end()) {
1402 ALOGE("%s lightId %d not found ", __func__, lightId);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001403 return;
1404 }
1405
1406 if (!base::WriteStringToFile(std::to_string(brightness),
1407 lightIt->second.path /
1408 LIGHT_NODES.at(InputLightClass::BRIGHTNESS))) {
1409 ALOGE("Can not write to file, error: %s", strerror(errno));
1410 }
1411}
1412
1413void EventHub::setLightIntensities(int32_t deviceId, int32_t lightId,
1414 std::unordered_map<LightColor, int32_t> intensities) {
1415 std::scoped_lock _l(mLock);
1416
Chris Yee2b1e5c2021-03-10 22:45:12 -08001417 const auto infos = getLightInfoLocked(deviceId);
1418 auto lightIt = infos.find(lightId);
1419 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001420 ALOGE("Light Id %d does not exist.", lightId);
1421 return;
1422 }
1423
1424 auto ret =
1425 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1426
1427 if (!ret.has_value()) {
1428 return;
1429 }
1430 std::array<LightColor, COLOR_NUM> colors = ret.value();
1431
1432 std::string rgbStr;
1433 for (size_t i = 0; i < COLOR_NUM; i++) {
1434 auto it = intensities.find(colors[i]);
1435 if (it != intensities.end()) {
1436 rgbStr += std::to_string(it->second);
1437 // Insert space between colors
1438 if (i < COLOR_NUM - 1) {
1439 rgbStr += " ";
1440 }
1441 }
1442 }
1443 // Append new line
1444 rgbStr += "\n";
1445
1446 if (!base::WriteStringToFile(rgbStr,
1447 lightIt->second.path /
1448 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY))) {
1449 ALOGE("Can not write to file, error: %s", strerror(errno));
1450 }
1451}
1452
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001453std::optional<RawLayoutInfo> EventHub::getRawLayoutInfo(int32_t deviceId) const {
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001454 std::scoped_lock _l(mLock);
1455 Device* device = getDeviceLocked(deviceId);
1456 if (device == nullptr || !device->associatedDevice) {
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001457 return std::nullopt;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001458 }
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001459 return device->associatedDevice->layoutInfo;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001460}
1461
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001462void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Chris Ye87143712020-11-10 05:05:58 +00001463 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001464
1465 mExcludedDevices = devices;
1466}
1467
1468bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
Chris Ye87143712020-11-10 05:05:58 +00001469 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001470 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001471 if (device != nullptr && scanCode >= 0 && scanCode <= KEY_MAX) {
1472 return device->keyBitmask.test(scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001473 }
1474 return false;
1475}
1476
Arthur Hungcb40a002021-08-03 14:31:01 +00001477bool EventHub::hasKeyCode(int32_t deviceId, int32_t keyCode) const {
1478 std::scoped_lock _l(mLock);
1479 Device* device = getDeviceLocked(deviceId);
1480 if (device != nullptr) {
1481 return device->hasKeycodeLocked(keyCode);
1482 }
1483 return false;
1484}
1485
Michael Wrightd02c5b62014-02-10 15:10:22 -08001486bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
Chris Ye87143712020-11-10 05:05:58 +00001487 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001488 Device* device = getDeviceLocked(deviceId);
1489 int32_t sc;
Chris Ye989bb932020-07-04 16:18:59 -07001490 if (device != nullptr && device->mapLed(led, &sc) == NO_ERROR) {
Chris Ye66fbac32020-07-06 20:36:43 -07001491 return device->ledBitmask.test(sc);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001492 }
1493 return false;
1494}
1495
1496void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
Chris Ye87143712020-11-10 05:05:58 +00001497 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001498 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -07001499 if (device != nullptr && device->hasValidFd()) {
1500 device->setLedStateLocked(led, on);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001501 }
1502}
1503
1504void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001505 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001506 outVirtualKeys.clear();
1507
Chris Ye87143712020-11-10 05:05:58 +00001508 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001509 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001510 if (device != nullptr && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001511 const std::vector<VirtualKeyDefinition> virtualKeys =
1512 device->virtualKeyMap->getVirtualKeys();
1513 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001514 }
1515}
1516
Chris Ye3a1e4462020-08-12 10:13:15 -07001517const std::shared_ptr<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001518 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001519 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001520 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001521 return device->getKeyCharacterMap();
1522 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001523 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001524}
1525
Vaibhav Devmurari23e8ae92022-12-29 12:07:56 +00001526// If provided map is null, it will reset key character map to default KCM.
Chris Ye3a1e4462020-08-12 10:13:15 -07001527bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, std::shared_ptr<KeyCharacterMap> map) {
Chris Ye87143712020-11-10 05:05:58 +00001528 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001529 Device* device = getDeviceLocked(deviceId);
Vaibhav Devmurari23e8ae92022-12-29 12:07:56 +00001530 if (device == nullptr || device->keyMap.keyCharacterMap == nullptr) {
Philip Junker90bc9492021-12-10 18:39:42 +01001531 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001532 }
Vaibhav Devmurari23e8ae92022-12-29 12:07:56 +00001533 if (map == nullptr) {
1534 device->keyMap.keyCharacterMap->clearLayoutOverlay();
1535 return true;
1536 }
Philip Junker90bc9492021-12-10 18:39:42 +01001537 device->keyMap.keyCharacterMap->combine(*map);
1538 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001539}
1540
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001541static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
1542 std::string rawDescriptor;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001543 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001544 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001545 if (!identifier.uniqueId.empty()) {
1546 rawDescriptor += "uniqueId:";
1547 rawDescriptor += identifier.uniqueId;
Josh Bartel938632f2022-07-19 15:34:22 -05001548 }
1549 if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001550 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001551 }
1552
1553 if (identifier.vendor == 0 && identifier.product == 0) {
1554 // If we don't know the vendor and product id, then the device is probably
1555 // built-in so we need to rely on other information to uniquely identify
1556 // the input device. Usually we try to avoid relying on the device name or
1557 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001558 if (!identifier.name.empty()) {
1559 rawDescriptor += "name:";
1560 rawDescriptor += identifier.name;
1561 } else if (!identifier.location.empty()) {
1562 rawDescriptor += "location:";
1563 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001564 }
1565 }
1566 identifier.descriptor = sha1(rawDescriptor);
1567 return rawDescriptor;
1568}
1569
1570void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
1571 // Compute a device descriptor that uniquely identifies the device.
1572 // The descriptor is assumed to be a stable identifier. Its value should not
1573 // change between reboots, reconnections, firmware updates or new releases
1574 // of Android. In practice we sometimes get devices that cannot be uniquely
1575 // identified. In this case we enforce uniqueness between connected devices.
1576 // Ideally, we also want the descriptor to be short and relatively opaque.
Josh Bartel938632f2022-07-19 15:34:22 -05001577 // Note that we explicitly do not use the path or location for external devices
1578 // as their path or location will change as they are plugged/unplugged or moved
1579 // to different ports. We do fallback to using name and location in the case of
1580 // internal devices which are detected by the vendor and product being 0 in
1581 // generateDescriptor. If two identical descriptors are detected we will fallback
1582 // to using a 'nonce' and incrementing it until the new descriptor no longer has
1583 // a match with any existing descriptors.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001584
1585 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001586 std::string rawDescriptor = generateDescriptor(identifier);
Josh Bartel938632f2022-07-19 15:34:22 -05001587 // Enforce that the generated descriptor is unique.
1588 while (hasDeviceWithDescriptorLocked(identifier.descriptor)) {
1589 identifier.nonce++;
1590 rawDescriptor = generateDescriptor(identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001591 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001592 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001593 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001594}
1595
Prabir Pradhancb42b472022-08-23 16:01:19 +00001596std::shared_ptr<const EventHub::AssociatedDevice> EventHub::obtainAssociatedDeviceLocked(
1597 const std::filesystem::path& devicePath) const {
1598 const std::optional<std::filesystem::path> sysfsRootPathOpt =
1599 getSysfsRootPath(devicePath.c_str());
1600 if (!sysfsRootPathOpt) {
1601 return nullptr;
1602 }
1603
1604 const auto& path = *sysfsRootPathOpt;
Prabir Pradhancb42b472022-08-23 16:01:19 +00001605
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00001606 std::shared_ptr<const AssociatedDevice> associatedDevice = std::make_shared<AssociatedDevice>(
Prabir Pradhancb42b472022-08-23 16:01:19 +00001607 AssociatedDevice{.sysfsRootPath = path,
1608 .batteryInfos = readBatteryConfiguration(path),
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001609 .lightInfos = readLightsConfiguration(path),
1610 .layoutInfo = readLayoutConfiguration(path)});
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00001611
1612 bool associatedDeviceChanged = false;
1613 for (const auto& [id, dev] : mDevices) {
1614 if (dev->associatedDevice && dev->associatedDevice->sysfsRootPath == path) {
1615 if (*associatedDevice != *dev->associatedDevice) {
1616 associatedDeviceChanged = true;
1617 dev->associatedDevice = associatedDevice;
1618 }
1619 associatedDevice = dev->associatedDevice;
1620 }
1621 }
1622 ALOGI_IF(associatedDeviceChanged,
1623 "The AssociatedDevice changed for path '%s'. Using new AssociatedDevice: %s",
1624 path.c_str(), associatedDevice->dump().c_str());
1625
1626 return associatedDevice;
Prabir Pradhancb42b472022-08-23 16:01:19 +00001627}
1628
Vaibhav Devmurari5fc7d852023-03-17 18:43:33 +00001629bool EventHub::AssociatedDevice::isChanged() const {
1630 std::unordered_map<int32_t, RawBatteryInfo> newBatteryInfos =
1631 readBatteryConfiguration(sysfsRootPath);
1632 std::unordered_map<int32_t, RawLightInfo> newLightInfos =
1633 readLightsConfiguration(sysfsRootPath);
1634 std::optional<RawLayoutInfo> newLayoutInfo = readLayoutConfiguration(sysfsRootPath);
1635
1636 if (newBatteryInfos == batteryInfos && newLightInfos == lightInfos &&
1637 newLayoutInfo == layoutInfo) {
1638 return false;
1639 }
1640 return true;
1641}
1642
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001643void EventHub::vibrate(int32_t deviceId, const VibrationElement& element) {
Chris Ye87143712020-11-10 05:05:58 +00001644 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001645 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001646 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001647 ff_effect effect;
1648 memset(&effect, 0, sizeof(effect));
1649 effect.type = FF_RUMBLE;
1650 effect.id = device->ffEffectId;
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001651 // evdev FF_RUMBLE effect only supports two channels of vibration.
Chris Ye6393a262020-08-04 19:41:36 -07001652 effect.u.rumble.strong_magnitude = element.getMagnitude(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1653 effect.u.rumble.weak_magnitude = element.getMagnitude(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001654 effect.replay.length = element.duration.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001655 effect.replay.delay = 0;
1656 if (ioctl(device->fd, EVIOCSFF, &effect)) {
1657 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001658 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001659 return;
1660 }
1661 device->ffEffectId = effect.id;
1662
1663 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -07001664 ev.input_event_sec = 0;
1665 ev.input_event_usec = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001666 ev.type = EV_FF;
1667 ev.code = device->ffEffectId;
1668 ev.value = 1;
1669 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1670 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001671 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001672 return;
1673 }
1674 device->ffEffectPlaying = true;
1675 }
1676}
1677
1678void EventHub::cancelVibrate(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001679 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001680 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001681 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001682 if (device->ffEffectPlaying) {
1683 device->ffEffectPlaying = false;
1684
1685 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -07001686 ev.input_event_sec = 0;
1687 ev.input_event_usec = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001688 ev.type = EV_FF;
1689 ev.code = device->ffEffectId;
1690 ev.value = 0;
1691 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1692 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001693 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001694 return;
1695 }
1696 }
1697 }
1698}
1699
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001700std::vector<int32_t> EventHub::getVibratorIds(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001701 std::scoped_lock _l(mLock);
1702 std::vector<int32_t> vibrators;
1703 Device* device = getDeviceLocked(deviceId);
1704 if (device != nullptr && device->hasValidFd() &&
1705 device->classes.test(InputDeviceClass::VIBRATOR)) {
1706 vibrators.push_back(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1707 vibrators.push_back(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
1708 }
1709 return vibrators;
1710}
1711
Josh Bartel938632f2022-07-19 15:34:22 -05001712/**
1713 * Checks both mDevices and mOpeningDevices for a device with the descriptor passed.
1714 */
1715bool EventHub::hasDeviceWithDescriptorLocked(const std::string& descriptor) const {
1716 for (const auto& device : mOpeningDevices) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001717 if (descriptor == device->identifier.descriptor) {
Josh Bartel938632f2022-07-19 15:34:22 -05001718 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001719 }
1720 }
Josh Bartel938632f2022-07-19 15:34:22 -05001721
1722 for (const auto& [id, device] : mDevices) {
1723 if (descriptor == device->identifier.descriptor) {
1724 return true;
1725 }
1726 }
1727 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001728}
1729
1730EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001731 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001732 deviceId = mBuiltInKeyboardId;
1733 }
Chris Ye989bb932020-07-04 16:18:59 -07001734 const auto& it = mDevices.find(deviceId);
1735 return it != mDevices.end() ? it->second.get() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001736}
1737
Chris Ye8594e192020-07-14 10:34:06 -07001738EventHub::Device* EventHub::getDeviceByPathLocked(const std::string& devicePath) const {
Chris Ye989bb932020-07-04 16:18:59 -07001739 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001740 if (device->path == devicePath) {
Chris Ye989bb932020-07-04 16:18:59 -07001741 return device.get();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001742 }
1743 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001744 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001745}
1746
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001747/**
1748 * The file descriptor could be either input device, or a video device (associated with a
1749 * specific input device). Check both cases here, and return the device that this event
1750 * belongs to. Caller can compare the fd's once more to determine event type.
1751 * Looks through all input devices, and only attached video devices. Unattached video
1752 * devices are ignored.
1753 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001754EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
Chris Ye989bb932020-07-04 16:18:59 -07001755 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001756 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001757 // This is an input device event
Chris Ye989bb932020-07-04 16:18:59 -07001758 return device.get();
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001759 }
1760 if (device->videoDevice && device->videoDevice->getFd() == fd) {
1761 // This is a video device event
Chris Ye989bb932020-07-04 16:18:59 -07001762 return device.get();
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001763 }
1764 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001765 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
1766 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001767 return nullptr;
1768}
1769
Chris Yee2b1e5c2021-03-10 22:45:12 -08001770std::optional<int32_t> EventHub::getBatteryCapacity(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001771 std::filesystem::path batteryPath;
1772 {
1773 // Do not read the sysfs node to get the battery state while holding
1774 // the EventHub lock. For some peripheral devices, reading battery state
1775 // can be broken and take 5+ seconds. Holding the lock in this case would
1776 // block all other event processing during this time. For now, we assume this
1777 // call never happens on the InputReader thread and read the sysfs node outside
1778 // the lock to prevent event processing from being blocked by this call.
1779 std::scoped_lock _l(mLock);
Kim Low03ea0352020-11-06 12:45:07 -08001780
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001781 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001782 auto it = infos.find(batteryId);
1783 if (it == infos.end()) {
1784 return std::nullopt;
1785 }
1786 batteryPath = it->second.path;
1787 } // release lock
1788
Chris Yee2b1e5c2021-03-10 22:45:12 -08001789 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001790
1791 // Some devices report battery capacity as an integer through the "capacity" file
Andy Chenf9f1a022022-08-29 20:07:10 -04001792 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001793 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001794 return std::stoi(base::Trim(buffer));
Kim Low03ea0352020-11-06 12:45:07 -08001795 }
1796
1797 // Other devices report capacity as an enum value POWER_SUPPLY_CAPACITY_LEVEL_XXX
1798 // These values are taken from kernel source code include/linux/power_supply.h
Andy Chenf9f1a022022-08-29 20:07:10 -04001799 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY_LEVEL),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001800 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001801 // Remove any white space such as trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001802 const auto levelIt = BATTERY_LEVEL.find(base::Trim(buffer));
1803 if (levelIt != BATTERY_LEVEL.end()) {
1804 return levelIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001805 }
1806 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001807
Kim Low03ea0352020-11-06 12:45:07 -08001808 return std::nullopt;
1809}
1810
Chris Yee2b1e5c2021-03-10 22:45:12 -08001811std::optional<int32_t> EventHub::getBatteryStatus(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001812 std::filesystem::path batteryPath;
1813 {
1814 // Do not read the sysfs node to get the battery state while holding
1815 // the EventHub lock. For some peripheral devices, reading battery state
1816 // can be broken and take 5+ seconds. Holding the lock in this case would
1817 // block all other event processing during this time. For now, we assume this
1818 // call never happens on the InputReader thread and read the sysfs node outside
1819 // the lock to prevent event processing from being blocked by this call.
1820 std::scoped_lock _l(mLock);
1821
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001822 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001823 auto it = infos.find(batteryId);
1824 if (it == infos.end()) {
1825 return std::nullopt;
1826 }
1827 batteryPath = it->second.path;
1828 } // release lock
1829
Chris Yee2b1e5c2021-03-10 22:45:12 -08001830 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001831
Andy Chenf9f1a022022-08-29 20:07:10 -04001832 if (!base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::STATUS),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001833 &buffer)) {
Kim Low03ea0352020-11-06 12:45:07 -08001834 ALOGE("Failed to read sysfs battery info: %s", strerror(errno));
1835 return std::nullopt;
1836 }
1837
Chris Yed1936772021-02-22 10:30:40 -08001838 // Remove white space like trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001839 const auto statusIt = BATTERY_STATUS.find(base::Trim(buffer));
1840 if (statusIt != BATTERY_STATUS.end()) {
1841 return statusIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001842 }
1843
1844 return std::nullopt;
1845}
1846
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001847std::vector<RawEvent> EventHub::getEvents(int timeoutMillis) {
Chris Ye87143712020-11-10 05:05:58 +00001848 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001849
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001850 std::array<input_event, EVENT_BUFFER_SIZE> readBuffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001851
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001852 std::vector<RawEvent> events;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001853 bool awoken = false;
1854 for (;;) {
1855 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
1856
1857 // Reopen input devices if needed.
1858 if (mNeedToReopenDevices) {
1859 mNeedToReopenDevices = false;
1860
1861 ALOGI("Reopening all input devices due to a configuration change.");
1862
1863 closeAllDevicesLocked();
1864 mNeedToScanDevices = true;
1865 break; // return to the caller before we actually rescan
1866 }
1867
1868 // Report any devices that had last been added/removed.
Chris Ye989bb932020-07-04 16:18:59 -07001869 for (auto it = mClosingDevices.begin(); it != mClosingDevices.end();) {
1870 std::unique_ptr<Device> device = std::move(*it);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001871 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001872 const int32_t deviceId = (device->id == mBuiltInKeyboardId)
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001873 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
1874 : device->id;
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001875 events.push_back({
1876 .when = now,
1877 .deviceId = deviceId,
1878 .type = DEVICE_REMOVED,
1879 });
Chris Ye989bb932020-07-04 16:18:59 -07001880 it = mClosingDevices.erase(it);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001881 mNeedToSendFinishedDeviceScan = true;
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001882 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001883 break;
1884 }
1885 }
1886
1887 if (mNeedToScanDevices) {
1888 mNeedToScanDevices = false;
1889 scanDevicesLocked();
1890 mNeedToSendFinishedDeviceScan = true;
1891 }
1892
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001893 while (!mOpeningDevices.empty()) {
1894 std::unique_ptr<Device> device = std::move(*mOpeningDevices.rbegin());
1895 mOpeningDevices.pop_back();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001896 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001897 const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1898 events.push_back({
1899 .when = now,
1900 .deviceId = deviceId,
1901 .type = DEVICE_ADDED,
1902 });
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001903
1904 // Try to find a matching video device by comparing device names
1905 for (auto it = mUnattachedVideoDevices.begin(); it != mUnattachedVideoDevices.end();
1906 it++) {
1907 std::unique_ptr<TouchVideoDevice>& videoDevice = *it;
Chris Yed3fef462021-03-07 17:10:08 -08001908 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001909 // videoDevice was transferred to 'device'
1910 it = mUnattachedVideoDevices.erase(it);
1911 break;
1912 }
1913 }
1914
1915 auto [dev_it, inserted] = mDevices.insert_or_assign(device->id, std::move(device));
1916 if (!inserted) {
Chris Ye989bb932020-07-04 16:18:59 -07001917 ALOGW("Device id %d exists, replaced.", device->id);
1918 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001919 mNeedToSendFinishedDeviceScan = true;
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001920 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001921 break;
1922 }
1923 }
1924
1925 if (mNeedToSendFinishedDeviceScan) {
1926 mNeedToSendFinishedDeviceScan = false;
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001927 events.push_back({
1928 .when = now,
1929 .type = FINISHED_DEVICE_SCAN,
1930 });
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001931 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001932 break;
1933 }
1934 }
1935
1936 // Grab the next input event.
1937 bool deviceChanged = false;
1938 while (mPendingEventIndex < mPendingEventCount) {
1939 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001940 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001941 if (eventItem.events & EPOLLIN) {
1942 mPendingINotify = true;
1943 } else {
1944 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
1945 }
1946 continue;
1947 }
1948
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001949 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001950 if (eventItem.events & EPOLLIN) {
1951 ALOGV("awoken after wake()");
1952 awoken = true;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001953 char wakeReadBuffer[16];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001954 ssize_t nRead;
1955 do {
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001956 nRead = read(mWakeReadPipeFd, wakeReadBuffer, sizeof(wakeReadBuffer));
1957 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(wakeReadBuffer));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001958 } else {
1959 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001960 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001961 }
1962 continue;
1963 }
1964
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001965 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Chris Ye989bb932020-07-04 16:18:59 -07001966 if (device == nullptr) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001967 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
1968 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001969 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001970 continue;
1971 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001972 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
1973 if (eventItem.events & EPOLLIN) {
1974 size_t numFrames = device->videoDevice->readAndQueueFrames();
1975 if (numFrames == 0) {
1976 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001977 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001978 }
1979 } else if (eventItem.events & EPOLLHUP) {
1980 // TODO(b/121395353) - consider adding EPOLLRDHUP
1981 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001982 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001983 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1984 device->videoDevice = nullptr;
1985 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001986 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1987 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001988 ALOG_ASSERT(!DEBUG);
1989 }
1990 continue;
1991 }
1992 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -08001993 if (eventItem.events & EPOLLIN) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001994 int32_t readSize =
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001995 read(device->fd, readBuffer.data(),
1996 sizeof(decltype(readBuffer)::value_type) * readBuffer.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001997 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
1998 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -07001999 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07002000 " capacity: %zu errno: %d)\n",
2001 device->fd, readSize, readBuffer.size(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002002 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07002003 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002004 } else if (readSize < 0) {
2005 if (errno != EAGAIN && errno != EINTR) {
2006 ALOGW("could not get event (errno=%d)", errno);
2007 }
2008 } else if ((readSize % sizeof(struct input_event)) != 0) {
2009 ALOGE("could not get event (wrong size: %d)", readSize);
2010 } else {
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002011 const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002012
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002013 const size_t count = size_t(readSize) / sizeof(struct input_event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002014 for (size_t i = 0; i < count; i++) {
2015 struct input_event& iev = readBuffer[i];
Prabir Pradhan9762ac92023-07-13 21:45:12 +00002016 device->trackInputEvent(iev);
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002017 events.push_back({
2018 .when = processEventTimestamp(iev),
2019 .readTime = systemTime(SYSTEM_TIME_MONOTONIC),
2020 .deviceId = deviceId,
2021 .type = iev.type,
2022 .code = iev.code,
2023 .value = iev.value,
2024 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08002025 }
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07002026 if (events.size() >= EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002027 // The result buffer is full. Reset the pending event index
2028 // so we will try to read the device again on the next iteration.
2029 mPendingEventIndex -= 1;
2030 break;
2031 }
2032 }
2033 } else if (eventItem.events & EPOLLHUP) {
2034 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002035 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002036 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07002037 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002038 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002039 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
2040 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002041 }
2042 }
2043
2044 // readNotify() will modify the list of devices so this must be done after
2045 // processing all other events to ensure that we read all remaining events
2046 // before closing the devices.
2047 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
2048 mPendingINotify = false;
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002049 const auto res = readNotifyLocked();
2050 if (!res.ok()) {
2051 ALOGW("Failed to read from inotify: %s", res.error().message().c_str());
2052 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002053 deviceChanged = true;
2054 }
2055
2056 // Report added or removed devices immediately.
2057 if (deviceChanged) {
2058 continue;
2059 }
2060
2061 // Return now if we have collected any events or if we were explicitly awoken.
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002062 if (!events.empty() || awoken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002063 break;
2064 }
2065
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01002066 // Poll for events.
2067 // When a device driver has pending (unread) events, it acquires
2068 // a kernel wake lock. Once the last pending event has been read, the device
2069 // driver will release the kernel wake lock, but the epoll will hold the wakelock,
2070 // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
2071 // is called again for the same fd that produced the event.
2072 // Thus the system can only sleep if there are no events pending or
2073 // currently being processed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002074 //
2075 // The timeout is advisory only. If the device is asleep, it will not wake just to
2076 // service the timeout.
2077 mPendingEventIndex = 0;
2078
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01002079 mLock.unlock(); // release lock before poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08002080
2081 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
2082
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01002083 mLock.lock(); // reacquire lock after poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08002084
2085 if (pollResult == 0) {
2086 // Timed out.
2087 mPendingEventCount = 0;
2088 break;
2089 }
2090
2091 if (pollResult < 0) {
2092 // An error occurred.
2093 mPendingEventCount = 0;
2094
2095 // Sleep after errors to avoid locking up the system.
2096 // Hopefully the error is transient.
2097 if (errno != EINTR) {
2098 ALOGW("poll failed (errno=%d)\n", errno);
2099 usleep(100000);
2100 }
2101 } else {
2102 // Some events occurred.
2103 mPendingEventCount = size_t(pollResult);
2104 }
2105 }
2106
2107 // All done, return the number of events we read.
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002108 return events;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002109}
2110
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08002111std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002112 std::scoped_lock _l(mLock);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08002113
2114 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07002115 if (device == nullptr || !device->videoDevice) {
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08002116 return {};
2117 }
2118 return device->videoDevice->consumeFrames();
2119}
2120
Michael Wrightd02c5b62014-02-10 15:10:22 -08002121void EventHub::wake() {
2122 ALOGV("wake() called");
2123
2124 ssize_t nWrite;
2125 do {
2126 nWrite = write(mWakeWritePipeFd, "W", 1);
2127 } while (nWrite == -1 && errno == EINTR);
2128
2129 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002130 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002131 }
2132}
2133
2134void EventHub::scanDevicesLocked() {
Usama Arifb27c8e62021-06-03 16:44:09 +01002135 status_t result;
2136 std::error_code errorCode;
2137
2138 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
2139 result = scanDirLocked(DEVICE_INPUT_PATH);
2140 if (result < 0) {
2141 ALOGE("scan dir failed for %s", DEVICE_INPUT_PATH);
2142 }
2143 } else {
2144 if (errorCode) {
2145 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
2146 errorCode.message().c_str());
2147 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002148 }
Philip Quinn39b81682019-01-09 22:20:39 -08002149 if (isV4lScanningEnabled()) {
Usama Arifb27c8e62021-06-03 16:44:09 +01002150 result = scanVideoDirLocked(DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08002151 if (result != OK) {
Usama Arifb27c8e62021-06-03 16:44:09 +01002152 ALOGE("scan video dir failed for %s", DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08002153 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002154 }
Chris Ye989bb932020-07-04 16:18:59 -07002155 if (mDevices.find(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) == mDevices.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002156 createVirtualKeyboardLocked();
2157 }
2158}
2159
2160// ----------------------------------------------------------------------------
2161
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002162status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002163 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002164 struct epoll_event eventItem = {};
2165 eventItem.events = EPOLLIN | EPOLLWAKEUP;
2166 eventItem.data.fd = fd;
2167 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
2168 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002169 return -errno;
2170 }
2171 return OK;
2172}
2173
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002174status_t EventHub::unregisterFdFromEpoll(int fd) {
2175 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
2176 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
2177 return -errno;
2178 }
2179 return OK;
2180}
2181
Chris Ye989bb932020-07-04 16:18:59 -07002182status_t EventHub::registerDeviceForEpollLocked(Device& device) {
2183 status_t result = registerFdForEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002184 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07002185 ALOGE("Could not add input device fd to epoll for device %" PRId32, device.id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002186 return result;
2187 }
Chris Ye989bb932020-07-04 16:18:59 -07002188 if (device.videoDevice) {
2189 registerVideoDeviceForEpollLocked(*device.videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002190 }
2191 return result;
2192}
2193
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002194void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
2195 status_t result = registerFdForEpoll(videoDevice.getFd());
2196 if (result != OK) {
2197 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
2198 }
2199}
2200
Chris Ye989bb932020-07-04 16:18:59 -07002201status_t EventHub::unregisterDeviceFromEpollLocked(Device& device) {
2202 if (device.hasValidFd()) {
2203 status_t result = unregisterFdFromEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002204 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07002205 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device.id);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002206 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002207 }
2208 }
Chris Ye989bb932020-07-04 16:18:59 -07002209 if (device.videoDevice) {
2210 unregisterVideoDeviceFromEpollLocked(*device.videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002211 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002212 return OK;
2213}
2214
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002215void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
2216 if (videoDevice.hasValidFd()) {
2217 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
2218 if (result != OK) {
2219 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002220 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002221 }
2222 }
2223}
2224
Chris Yed3fef462021-03-07 17:10:08 -08002225void EventHub::reportDeviceAddedForStatisticsLocked(const InputDeviceIdentifier& identifier,
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002226 ftl::Flags<InputDeviceClass> classes) {
Chris Ye657c2f02021-05-25 16:24:37 -07002227 SHA256_CTX ctx;
2228 SHA256_Init(&ctx);
2229 SHA256_Update(&ctx, reinterpret_cast<const uint8_t*>(identifier.uniqueId.c_str()),
2230 identifier.uniqueId.size());
2231 std::array<uint8_t, SHA256_DIGEST_LENGTH> digest;
2232 SHA256_Final(digest.data(), &ctx);
2233
2234 std::string obfuscatedId;
2235 for (size_t i = 0; i < OBFUSCATED_LENGTH; i++) {
2236 obfuscatedId += StringPrintf("%02x", digest[i]);
2237 }
2238
Chris Yed3fef462021-03-07 17:10:08 -08002239 android::util::stats_write(android::util::INPUTDEVICE_REGISTERED, identifier.name.c_str(),
2240 identifier.vendor, identifier.product, identifier.version,
Chris Ye657c2f02021-05-25 16:24:37 -07002241 identifier.bus, obfuscatedId.c_str(), classes.get());
Chris Yed3fef462021-03-07 17:10:08 -08002242}
2243
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002244void EventHub::openDeviceLocked(const std::string& devicePath) {
2245 // If an input device happens to register around the time when EventHub's constructor runs, it
2246 // is possible that the same input event node (for example, /dev/input/event3) will be noticed
2247 // in both 'inotify' callback and also in the 'scanDirLocked' pass. To prevent duplicate devices
2248 // from getting registered, ensure that this path is not already covered by an existing device.
2249 for (const auto& [deviceId, device] : mDevices) {
2250 if (device->path == devicePath) {
2251 return; // device was already registered
2252 }
2253 }
2254
Michael Wrightd02c5b62014-02-10 15:10:22 -08002255 char buffer[80];
2256
Chris Ye8594e192020-07-14 10:34:06 -07002257 ALOGV("Opening device: %s", devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002258
Chris Ye8594e192020-07-14 10:34:06 -07002259 int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002260 if (fd < 0) {
Chris Ye8594e192020-07-14 10:34:06 -07002261 ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002262 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002263 }
2264
2265 InputDeviceIdentifier identifier;
2266
2267 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002268 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Chris Ye8594e192020-07-14 10:34:06 -07002269 ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002270 } else {
2271 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002272 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002273 }
2274
2275 // Check to see if the device is on our excluded list
2276 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002277 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002278 if (identifier.name == item) {
Chris Ye8594e192020-07-14 10:34:06 -07002279 ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002280 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002281 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002282 }
2283 }
2284
2285 // Get device driver version.
2286 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002287 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Chris Ye8594e192020-07-14 10:34:06 -07002288 ALOGE("could not get driver version for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002289 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002290 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002291 }
2292
2293 // Get device identifier.
2294 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002295 if (ioctl(fd, EVIOCGID, &inputId)) {
Chris Ye8594e192020-07-14 10:34:06 -07002296 ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002297 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002298 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002299 }
2300 identifier.bus = inputId.bustype;
2301 identifier.product = inputId.product;
2302 identifier.vendor = inputId.vendor;
2303 identifier.version = inputId.version;
2304
2305 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002306 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
2307 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002308 } else {
2309 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002310 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002311 }
2312
2313 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002314 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
2315 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002316 } else {
2317 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002318 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002319 }
2320
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002321 // Attempt to get the bluetooth address of an input device from the uniqueId.
2322 if (identifier.bus == BUS_BLUETOOTH &&
2323 std::regex_match(identifier.uniqueId,
2324 std::regex("^[A-Fa-f0-9]{2}(?::[A-Fa-f0-9]{2}){5}$"))) {
2325 identifier.bluetoothAddress = identifier.uniqueId;
2326 // The Bluetooth stack requires alphabetic characters to be uppercase in a valid address.
2327 for (auto& c : *identifier.bluetoothAddress) {
2328 c = ::toupper(c);
2329 }
2330 }
2331
Michael Wrightd02c5b62014-02-10 15:10:22 -08002332 // Fill in the descriptor.
2333 assignDescriptorLocked(identifier);
2334
Michael Wrightd02c5b62014-02-10 15:10:22 -08002335 // Allocate device. (The device object takes ownership of the fd at this point.)
2336 int32_t deviceId = mNextDeviceId++;
Prabir Pradhancb42b472022-08-23 16:01:19 +00002337 std::unique_ptr<Device> device =
2338 std::make_unique<Device>(fd, deviceId, devicePath, identifier,
2339 obtainAssociatedDeviceLocked(devicePath));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002340
Chris Ye8594e192020-07-14 10:34:06 -07002341 ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002342 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002343 " vendor %04x\n"
2344 " product %04x\n"
2345 " version %04x\n",
2346 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002347 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
2348 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
2349 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
2350 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002351 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
2352 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002353
2354 // Load the configuration file for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002355 device->loadConfigurationLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002356
2357 // Figure out the kinds of events the device reports.
Chris Ye66fbac32020-07-06 20:36:43 -07002358 device->readDeviceBitMask(EVIOCGBIT(EV_KEY, 0), device->keyBitmask);
2359 device->readDeviceBitMask(EVIOCGBIT(EV_ABS, 0), device->absBitmask);
2360 device->readDeviceBitMask(EVIOCGBIT(EV_REL, 0), device->relBitmask);
2361 device->readDeviceBitMask(EVIOCGBIT(EV_SW, 0), device->swBitmask);
2362 device->readDeviceBitMask(EVIOCGBIT(EV_LED, 0), device->ledBitmask);
2363 device->readDeviceBitMask(EVIOCGBIT(EV_FF, 0), device->ffBitmask);
Chris Yef59a2f42020-10-16 12:55:26 -07002364 device->readDeviceBitMask(EVIOCGBIT(EV_MSC, 0), device->mscBitmask);
Chris Ye66fbac32020-07-06 20:36:43 -07002365 device->readDeviceBitMask(EVIOCGPROP(0), device->propBitmask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002366
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002367 // See if this is a device with keys. This could be full keyboard, or other devices like
2368 // gamepads, joysticks, and styluses with buttons that should generate key presses.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002369 bool haveKeyboardKeys =
Chris Ye66fbac32020-07-06 20:36:43 -07002370 device->keyBitmask.any(0, BTN_MISC) || device->keyBitmask.any(BTN_WHEEL, KEY_MAX + 1);
2371 bool haveGamepadButtons = device->keyBitmask.any(BTN_MISC, BTN_MOUSE) ||
2372 device->keyBitmask.any(BTN_JOYSTICK, BTN_DIGI);
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002373 bool haveStylusButtons = device->keyBitmask.test(BTN_STYLUS) ||
2374 device->keyBitmask.test(BTN_STYLUS2) || device->keyBitmask.test(BTN_STYLUS3);
2375 if (haveKeyboardKeys || haveGamepadButtons || haveStylusButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002376 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002377 }
2378
2379 // See if this is a cursor device such as a trackball or mouse.
Chris Ye66fbac32020-07-06 20:36:43 -07002380 if (device->keyBitmask.test(BTN_MOUSE) && device->relBitmask.test(REL_X) &&
2381 device->relBitmask.test(REL_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002382 device->classes |= InputDeviceClass::CURSOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002383 }
2384
Prabir Pradhana3621852022-10-14 18:57:23 +00002385 // See if the device is specially configured to be of a certain type.
Harry Cuttsf13161a2023-03-08 14:15:49 +00002386 if (device->configuration) {
2387 std::string deviceType = device->configuration->getString("device.type").value_or("");
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07002388 if (deviceType == "rotaryEncoder") {
Chris Ye1b0c7342020-07-28 21:57:03 -07002389 device->classes |= InputDeviceClass::ROTARY_ENCODER;
Prabir Pradhana3621852022-10-14 18:57:23 +00002390 } else if (deviceType == "externalStylus") {
2391 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002392 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002393 }
2394
Michael Wrightd02c5b62014-02-10 15:10:22 -08002395 // See if this is a touch pad.
2396 // Is this a new modern multi-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002397 if (device->absBitmask.test(ABS_MT_POSITION_X) && device->absBitmask.test(ABS_MT_POSITION_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002398 // Some joysticks such as the PS3 controller report axes that conflict
2399 // with the ABS_MT range. Try to confirm that the device really is
2400 // a touch screen.
Chris Ye66fbac32020-07-06 20:36:43 -07002401 if (device->keyBitmask.test(BTN_TOUCH) || !haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002402 device->classes |= (InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT);
Harry Cutts79cc9fa2022-10-28 15:32:39 +00002403 if (device->propBitmask.test(INPUT_PROP_POINTER) &&
2404 !device->keyBitmask.any(BTN_TOOL_PEN, BTN_TOOL_FINGER) && !haveStylusButtons) {
2405 device->classes |= InputDeviceClass::TOUCHPAD;
2406 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002407 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002408 // Is this an old style single-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002409 } else if (device->keyBitmask.test(BTN_TOUCH) && device->absBitmask.test(ABS_X) &&
2410 device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002411 device->classes |= InputDeviceClass::TOUCH;
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002412 // Is this a stylus that reports contact/pressure independently of touch coordinates?
Chris Ye66fbac32020-07-06 20:36:43 -07002413 } else if ((device->absBitmask.test(ABS_PRESSURE) || device->keyBitmask.test(BTN_TOUCH)) &&
2414 !device->absBitmask.test(ABS_X) && !device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002415 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002416 }
2417
2418 // See if this device is a joystick.
2419 // Assumes that joysticks always have gamepad buttons in order to distinguish them
2420 // from other devices such as accelerometers that also have absolute axes.
2421 if (haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002422 auto assumedClasses = device->classes | InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002423 for (int i = 0; i <= ABS_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002424 if (device->absBitmask.test(i) &&
Chris Ye1b0c7342020-07-28 21:57:03 -07002425 (getAbsAxisUsage(i, assumedClasses).test(InputDeviceClass::JOYSTICK))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002426 device->classes = assumedClasses;
2427 break;
2428 }
2429 }
2430 }
2431
Chris Yef59a2f42020-10-16 12:55:26 -07002432 // Check whether this device is an accelerometer.
2433 if (device->propBitmask.test(INPUT_PROP_ACCELEROMETER)) {
2434 device->classes |= InputDeviceClass::SENSOR;
2435 }
2436
Michael Wrightd02c5b62014-02-10 15:10:22 -08002437 // Check whether this device has switches.
2438 for (int i = 0; i <= SW_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002439 if (device->swBitmask.test(i)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002440 device->classes |= InputDeviceClass::SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002441 break;
2442 }
2443 }
2444
2445 // Check whether this device supports the vibrator.
Chris Ye66fbac32020-07-06 20:36:43 -07002446 if (device->ffBitmask.test(FF_RUMBLE)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002447 device->classes |= InputDeviceClass::VIBRATOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002448 }
2449
2450 // Configure virtual keys.
Chris Ye1b0c7342020-07-28 21:57:03 -07002451 if ((device->classes.test(InputDeviceClass::TOUCH))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002452 // Load the virtual keys for the touch screen, if any.
2453 // We do this now so that we can make sure to load the keymap if necessary.
Chris Ye989bb932020-07-04 16:18:59 -07002454 bool success = device->loadVirtualKeyMapLocked();
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06002455 if (success) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002456 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002457 }
2458 }
2459
2460 // Load the key map.
Chris Yef59a2f42020-10-16 12:55:26 -07002461 // We need to do this for joysticks too because the key layout may specify axes, and for
2462 // sensor as well because the key layout may specify the axes to sensor data mapping.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002463 status_t keyMapStatus = NAME_NOT_FOUND;
Chris Yef59a2f42020-10-16 12:55:26 -07002464 if (device->classes.any(InputDeviceClass::KEYBOARD | InputDeviceClass::JOYSTICK |
2465 InputDeviceClass::SENSOR)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002466 // Load the keymap for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002467 keyMapStatus = device->loadKeyMapLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002468 }
2469
2470 // Configure the keyboard, gamepad or virtual keyboard.
Chris Ye1b0c7342020-07-28 21:57:03 -07002471 if (device->classes.test(InputDeviceClass::KEYBOARD)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002472 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002473 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002474 isEligibleBuiltInKeyboard(device->identifier, device->configuration.get(),
2475 &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002476 mBuiltInKeyboardId = device->id;
2477 }
2478
2479 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
Chris Ye989bb932020-07-04 16:18:59 -07002480 if (device->hasKeycodeLocked(AKEYCODE_Q)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002481 device->classes |= InputDeviceClass::ALPHAKEY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002482 }
2483
Prabir Pradhanae10ee62023-05-12 19:44:18 +00002484 // See if this device has a D-pad.
2485 if (std::all_of(DPAD_REQUIRED_KEYCODES.begin(), DPAD_REQUIRED_KEYCODES.end(),
2486 [&](int32_t keycode) { return device->hasKeycodeLocked(keycode); })) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002487 device->classes |= InputDeviceClass::DPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002488 }
2489
2490 // See if this device has a gamepad.
Prabir Pradhanae10ee62023-05-12 19:44:18 +00002491 if (std::any_of(GAMEPAD_KEYCODES.begin(), GAMEPAD_KEYCODES.end(),
2492 [&](int32_t keycode) { return device->hasKeycodeLocked(keycode); })) {
2493 device->classes |= InputDeviceClass::GAMEPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002494 }
Prabir Pradhana3621852022-10-14 18:57:23 +00002495
2496 // See if this device has any stylus buttons that we would want to fuse with touch data.
Prabir Pradhanae10ee62023-05-12 19:44:18 +00002497 if (!device->classes.any(InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT) &&
Prabir Pradhan3c28b942023-08-18 20:02:01 +00002498 !device->classes.any(InputDeviceClass::ALPHAKEY) &&
Prabir Pradhanae10ee62023-05-12 19:44:18 +00002499 std::any_of(STYLUS_BUTTON_KEYCODES.begin(), STYLUS_BUTTON_KEYCODES.end(),
2500 [&](int32_t keycode) { return device->hasKeycodeLocked(keycode); })) {
2501 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Prabir Pradhana3621852022-10-14 18:57:23 +00002502 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002503 }
2504
2505 // If the device isn't recognized as something we handle, don't monitor it.
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002506 if (device->classes == ftl::Flags<InputDeviceClass>(0)) {
Chris Ye8594e192020-07-14 10:34:06 -07002507 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002508 device->identifier.name.c_str());
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002509 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002510 }
2511
Chris Ye3fdbfef2021-01-06 18:45:18 -08002512 // Classify InputDeviceClass::BATTERY.
Prabir Pradhan51894782022-08-23 16:29:10 +00002513 if (device->associatedDevice && !device->associatedDevice->batteryInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002514 device->classes |= InputDeviceClass::BATTERY;
2515 }
Kim Low03ea0352020-11-06 12:45:07 -08002516
Chris Ye3fdbfef2021-01-06 18:45:18 -08002517 // Classify InputDeviceClass::LIGHT.
Prabir Pradhan51894782022-08-23 16:29:10 +00002518 if (device->associatedDevice && !device->associatedDevice->lightInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002519 device->classes |= InputDeviceClass::LIGHT;
Kim Low03ea0352020-11-06 12:45:07 -08002520 }
2521
Tim Kilbourn063ff532015-04-08 10:26:18 -07002522 // Determine whether the device has a mic.
Chris Ye989bb932020-07-04 16:18:59 -07002523 if (device->deviceHasMicLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002524 device->classes |= InputDeviceClass::MIC;
Tim Kilbourn063ff532015-04-08 10:26:18 -07002525 }
2526
Michael Wrightd02c5b62014-02-10 15:10:22 -08002527 // Determine whether the device is external or internal.
Chris Ye989bb932020-07-04 16:18:59 -07002528 if (device->isExternalDeviceLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002529 device->classes |= InputDeviceClass::EXTERNAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002530 }
2531
Chris Ye1b0c7342020-07-28 21:57:03 -07002532 if (device->classes.any(InputDeviceClass::JOYSTICK | InputDeviceClass::DPAD) &&
2533 device->classes.test(InputDeviceClass::GAMEPAD)) {
Chris Ye989bb932020-07-04 16:18:59 -07002534 device->controllerNumber = getNextControllerNumberLocked(device->identifier.name);
2535 device->setLedForControllerLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002536 }
2537
Chris Ye989bb932020-07-04 16:18:59 -07002538 if (registerDeviceForEpollLocked(*device) != OK) {
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002539 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002540 }
2541
Chris Ye989bb932020-07-04 16:18:59 -07002542 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002543
Chris Ye1b0c7342020-07-28 21:57:03 -07002544 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=%s, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002545 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Chris Ye1b0c7342020-07-28 21:57:03 -07002546 deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(),
2547 device->classes.string().c_str(), device->configurationFile.c_str(),
2548 device->keyMap.keyLayoutFile.c_str(), device->keyMap.keyCharacterMapFile.c_str(),
2549 toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002550
Chris Ye989bb932020-07-04 16:18:59 -07002551 addDeviceLocked(std::move(device));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002552}
2553
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002554void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
2555 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
2556 if (!videoDevice) {
2557 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
2558 return;
2559 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002560 // Transfer ownership of this video device to a matching input device
Chris Ye989bb932020-07-04 16:18:59 -07002561 for (const auto& [id, device] : mDevices) {
Chris Yed3fef462021-03-07 17:10:08 -08002562 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002563 return; // 'device' now owns 'videoDevice'
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002564 }
2565 }
2566
2567 // Couldn't find a matching input device, so just add it to a temporary holding queue.
2568 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002569 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002570 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002571 mUnattachedVideoDevices.push_back(std::move(videoDevice));
2572}
2573
Chris Yed3fef462021-03-07 17:10:08 -08002574bool EventHub::tryAddVideoDeviceLocked(EventHub::Device& device,
2575 std::unique_ptr<TouchVideoDevice>& videoDevice) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002576 if (videoDevice->getName() != device.identifier.name) {
2577 return false;
2578 }
2579 device.videoDevice = std::move(videoDevice);
2580 if (device.enabled) {
2581 registerVideoDeviceForEpollLocked(*device.videoDevice);
2582 }
2583 return true;
2584}
2585
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002586bool EventHub::isDeviceEnabled(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00002587 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002588 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002589 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002590 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2591 return false;
2592 }
2593 return device->enabled;
2594}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002595
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002596status_t EventHub::enableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002597 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002598 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002599 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002600 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2601 return BAD_VALUE;
2602 }
2603 if (device->enabled) {
2604 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
2605 return OK;
2606 }
2607 status_t result = device->enable();
2608 if (result != OK) {
2609 ALOGE("Failed to enable device %" PRId32, deviceId);
2610 return result;
2611 }
2612
Chris Ye989bb932020-07-04 16:18:59 -07002613 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002614
Chris Ye989bb932020-07-04 16:18:59 -07002615 return registerDeviceForEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002616}
2617
2618status_t EventHub::disableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002619 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002620 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002621 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002622 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2623 return BAD_VALUE;
2624 }
2625 if (!device->enabled) {
2626 ALOGW("Duplicate call to %s, input device already disabled", __func__);
2627 return OK;
2628 }
Chris Ye989bb932020-07-04 16:18:59 -07002629 unregisterDeviceFromEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002630 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002631}
2632
Vaibhav Devmurari5fc7d852023-03-17 18:43:33 +00002633// TODO(b/274755573): Shift to uevent handling on native side and remove this method
2634// Currently using Java UEventObserver to trigger this which uses UEvent infrastructure that uses a
2635// NETLINK socket to observe UEvents. We can create similar infrastructure on Eventhub side to
2636// directly observe UEvents instead of triggering from Java side.
2637void EventHub::sysfsNodeChanged(const std::string& sysfsNodePath) {
2638 std::scoped_lock _l(mLock);
2639
2640 // Check in opening devices
2641 for (auto it = mOpeningDevices.begin(); it != mOpeningDevices.end(); it++) {
2642 std::unique_ptr<Device>& device = *it;
2643 if (device->associatedDevice &&
2644 sysfsNodePath.find(device->associatedDevice->sysfsRootPath.string()) !=
2645 std::string::npos &&
2646 device->associatedDevice->isChanged()) {
2647 it = mOpeningDevices.erase(it);
2648 openDeviceLocked(device->path);
2649 }
2650 }
2651
2652 // Check in already added device
2653 std::vector<Device*> devicesToReopen;
2654 for (const auto& [id, device] : mDevices) {
2655 if (device->associatedDevice &&
2656 sysfsNodePath.find(device->associatedDevice->sysfsRootPath.string()) !=
2657 std::string::npos &&
2658 device->associatedDevice->isChanged()) {
2659 devicesToReopen.push_back(device.get());
2660 }
2661 }
2662 for (const auto& device : devicesToReopen) {
2663 closeDeviceLocked(*device);
2664 openDeviceLocked(device->path);
2665 }
2666 devicesToReopen.clear();
2667}
2668
Michael Wrightd02c5b62014-02-10 15:10:22 -08002669void EventHub::createVirtualKeyboardLocked() {
2670 InputDeviceIdentifier identifier;
2671 identifier.name = "Virtual";
2672 identifier.uniqueId = "<virtual>";
2673 assignDescriptorLocked(identifier);
2674
Chris Ye989bb932020-07-04 16:18:59 -07002675 std::unique_ptr<Device> device =
2676 std::make_unique<Device>(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
Harry Cutts33476232023-01-30 19:57:29 +00002677 identifier, /*associatedDevice=*/nullptr);
Chris Ye1b0c7342020-07-28 21:57:03 -07002678 device->classes = InputDeviceClass::KEYBOARD | InputDeviceClass::ALPHAKEY |
2679 InputDeviceClass::DPAD | InputDeviceClass::VIRTUAL;
Chris Ye989bb932020-07-04 16:18:59 -07002680 device->loadKeyMapLocked();
2681 addDeviceLocked(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002682}
2683
Chris Ye989bb932020-07-04 16:18:59 -07002684void EventHub::addDeviceLocked(std::unique_ptr<Device> device) {
Chris Yed3fef462021-03-07 17:10:08 -08002685 reportDeviceAddedForStatisticsLocked(device->identifier, device->classes);
Chris Ye989bb932020-07-04 16:18:59 -07002686 mOpeningDevices.push_back(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002687}
2688
Chris Ye989bb932020-07-04 16:18:59 -07002689int32_t EventHub::getNextControllerNumberLocked(const std::string& name) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002690 if (mControllerNumbers.isFull()) {
2691 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Chris Ye989bb932020-07-04 16:18:59 -07002692 name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002693 return 0;
2694 }
2695 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
2696 // one
2697 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
2698}
2699
Chris Ye989bb932020-07-04 16:18:59 -07002700void EventHub::releaseControllerNumberLocked(int32_t num) {
2701 if (num > 0) {
2702 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002703 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002704}
2705
Chris Ye8594e192020-07-14 10:34:06 -07002706void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002707 Device* device = getDeviceByPathLocked(devicePath);
Chris Ye989bb932020-07-04 16:18:59 -07002708 if (device != nullptr) {
2709 closeDeviceLocked(*device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002710 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002711 }
Chris Ye8594e192020-07-14 10:34:06 -07002712 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002713}
2714
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002715/**
2716 * Find the video device by filename, and close it.
2717 * The video device is closed by path during an inotify event, where we don't have the
2718 * additional context about the video device fd, or the associated input device.
2719 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002720void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002721 // A video device may be owned by an existing input device, or it may be stored in
2722 // the mUnattachedVideoDevices queue. Check both locations.
Chris Ye989bb932020-07-04 16:18:59 -07002723 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002724 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002725 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002726 device->videoDevice = nullptr;
2727 return;
2728 }
2729 }
Siarhei Vishniakouf47c339e2021-12-30 11:22:26 -08002730 std::erase_if(mUnattachedVideoDevices,
2731 [&devicePath](const std::unique_ptr<TouchVideoDevice>& videoDevice) {
2732 return videoDevice->getPath() == devicePath;
2733 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08002734}
2735
2736void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002737 mUnattachedVideoDevices.clear();
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002738 while (!mDevices.empty()) {
2739 closeDeviceLocked(*(mDevices.begin()->second));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002740 }
2741}
2742
Chris Ye989bb932020-07-04 16:18:59 -07002743void EventHub::closeDeviceLocked(Device& device) {
2744 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=%s", device.path.c_str(),
2745 device.identifier.name.c_str(), device.id, device.fd, device.classes.string().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002746
Chris Ye989bb932020-07-04 16:18:59 -07002747 if (device.id == mBuiltInKeyboardId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002748 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Chris Ye989bb932020-07-04 16:18:59 -07002749 device.path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002750 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
2751 }
2752
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002753 unregisterDeviceFromEpollLocked(device);
Chris Ye989bb932020-07-04 16:18:59 -07002754 if (device.videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002755 // This must be done after the video device is removed from epoll
Chris Ye989bb932020-07-04 16:18:59 -07002756 mUnattachedVideoDevices.push_back(std::move(device.videoDevice));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002757 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002758
Chris Ye989bb932020-07-04 16:18:59 -07002759 releaseControllerNumberLocked(device.controllerNumber);
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002760 device.controllerNumber = 0;
Chris Ye989bb932020-07-04 16:18:59 -07002761 device.close();
Chris Ye989bb932020-07-04 16:18:59 -07002762 mClosingDevices.push_back(std::move(mDevices[device.id]));
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002763
Chris Ye989bb932020-07-04 16:18:59 -07002764 mDevices.erase(device.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002765}
2766
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002767base::Result<void> EventHub::readNotifyLocked() {
2768 static constexpr auto EVENT_SIZE = static_cast<ssize_t>(sizeof(inotify_event));
2769 uint8_t eventBuffer[512];
2770 ssize_t sizeRead;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002771
2772 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002773 do {
2774 sizeRead = read(mINotifyFd, eventBuffer, sizeof(eventBuffer));
2775 } while (sizeRead < 0 && errno == EINTR);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002776
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002777 if (sizeRead < EVENT_SIZE) return Errorf("could not get event, %s", strerror(errno));
2778
2779 for (ssize_t eventPos = 0; sizeRead >= EVENT_SIZE;) {
2780 const inotify_event* event;
2781 event = (const inotify_event*)(eventBuffer + eventPos);
2782 if (event->len == 0) continue;
2783
2784 handleNotifyEventLocked(*event);
2785
2786 const ssize_t eventSize = EVENT_SIZE + event->len;
2787 sizeRead -= eventSize;
2788 eventPos += eventSize;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002789 }
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002790 return {};
2791}
2792
2793void EventHub::handleNotifyEventLocked(const inotify_event& event) {
2794 if (event.wd == mDeviceInputWd) {
2795 std::string filename = std::string(DEVICE_INPUT_PATH) + "/" + event.name;
2796 if (event.mask & IN_CREATE) {
2797 openDeviceLocked(filename);
2798 } else {
2799 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
2800 closeDeviceByPathLocked(filename);
2801 }
2802 } else if (event.wd == mDeviceWd) {
2803 if (isV4lTouchNode(event.name)) {
2804 std::string filename = std::string(DEVICE_PATH) + "/" + event.name;
2805 if (event.mask & IN_CREATE) {
2806 openVideoDeviceLocked(filename);
2807 } else {
2808 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
2809 closeVideoDeviceByPathLocked(filename);
2810 }
2811 } else if (strcmp(event.name, "input") == 0 && event.mask & IN_CREATE) {
2812 addDeviceInputInotify();
2813 }
2814 } else {
2815 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event.wd);
2816 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002817}
2818
Chris Ye8594e192020-07-14 10:34:06 -07002819status_t EventHub::scanDirLocked(const std::string& dirname) {
2820 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2821 openDeviceLocked(entry.path());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002822 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002823 return 0;
2824}
2825
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002826/**
2827 * Look for all dirname/v4l-touch* devices, and open them.
2828 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002829status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Chris Ye8594e192020-07-14 10:34:06 -07002830 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2831 if (isV4lTouchNode(entry.path())) {
2832 ALOGI("Found touch video device %s", entry.path().c_str());
2833 openVideoDeviceLocked(entry.path());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002834 }
2835 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002836 return OK;
2837}
2838
Michael Wrightd02c5b62014-02-10 15:10:22 -08002839void EventHub::requestReopenDevices() {
2840 ALOGV("requestReopenDevices() called");
2841
Chris Ye87143712020-11-10 05:05:58 +00002842 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002843 mNeedToReopenDevices = true;
2844}
2845
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002846void EventHub::dump(std::string& dump) const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002847 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002848
2849 { // acquire lock
Chris Ye87143712020-11-10 05:05:58 +00002850 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002851
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002852 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002853
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002854 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002855
Chris Ye989bb932020-07-04 16:18:59 -07002856 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002857 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002858 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002859 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002860 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002861 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002862 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002863 }
Chris Ye1b0c7342020-07-28 21:57:03 -07002864 dump += StringPrintf(INDENT3 "Classes: %s\n", device->classes.string().c_str());
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002865 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002866 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002867 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
2868 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002869 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002870 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002871 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002872 "product=0x%04x, version=0x%04x, bluetoothAddress=%s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002873 device->identifier.bus, device->identifier.vendor,
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002874 device->identifier.product, device->identifier.version,
2875 toString(device->identifier.bluetoothAddress).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002876 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002877 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002878 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002879 device->keyMap.keyCharacterMapFile.c_str());
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00002880 if (device->associatedDevice && device->associatedDevice->layoutInfo) {
2881 dump += StringPrintf(INDENT3 "LanguageTag: %s\n",
2882 device->associatedDevice->layoutInfo->languageTag.c_str());
2883 dump += StringPrintf(INDENT3 "LayoutType: %s\n",
2884 device->associatedDevice->layoutInfo->layoutType.c_str());
2885 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002886 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002887 device->configurationFile.c_str());
Prabir Pradhan51894782022-08-23 16:29:10 +00002888 dump += StringPrintf(INDENT3 "VideoDevice: %s\n",
2889 device->videoDevice ? device->videoDevice->dump().c_str()
2890 : "<none>");
2891 dump += StringPrintf(INDENT3 "SysfsDevicePath: %s\n",
2892 device->associatedDevice
2893 ? device->associatedDevice->sysfsRootPath.c_str()
2894 : "<none>");
Prabir Pradhan955b6132023-07-14 19:44:34 +00002895 if (device->keyBitmask.any(0, KEY_MAX + 1)) {
2896 const auto pressedKeys = device->keyState.dumpSetIndices(", ", [](int i) {
2897 return InputEventLookup::getLinuxEvdevLabel(EV_KEY, i, 1).code;
2898 });
2899 dump += StringPrintf(INDENT3 "KeyState (pressed): %s\n", pressedKeys.c_str());
2900 }
2901 if (device->swBitmask.any(0, SW_MAX + 1)) {
2902 const auto pressedSwitches = device->swState.dumpSetIndices(", ", [](int i) {
2903 return InputEventLookup::getLinuxEvdevLabel(EV_SW, i, 1).code;
2904 });
2905 dump += StringPrintf(INDENT3 "SwState (pressed): %s\n", pressedSwitches.c_str());
2906 }
2907 if (!device->absState.empty()) {
2908 std::string axisValues;
2909 for (const auto& [axis, state] : device->absState) {
2910 if (!axisValues.empty()) {
2911 axisValues += ", ";
2912 }
2913 axisValues += StringPrintf("%s=%d",
2914 InputEventLookup::getLinuxEvdevLabel(EV_ABS, axis, 0)
2915 .code.c_str(),
2916 state.value);
2917 }
2918 dump += INDENT3 "AbsState: " + axisValues + "\n";
2919 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002920 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002921
2922 dump += INDENT "Unattached video devices:\n";
2923 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
2924 dump += INDENT2 + videoDevice->dump() + "\n";
2925 }
2926 if (mUnattachedVideoDevices.empty()) {
2927 dump += INDENT2 "<none>\n";
2928 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002929 } // release lock
2930}
2931
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002932void EventHub::monitor() const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002933 // Acquire and release the lock to ensure that the event hub has not deadlocked.
Chris Ye1c2e0892020-11-30 21:41:44 -08002934 std::unique_lock<std::mutex> lock(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002935}
2936
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00002937std::string EventHub::AssociatedDevice::dump() const {
2938 return StringPrintf("path=%s, numBatteries=%zu, numLight=%zu", sysfsRootPath.c_str(),
2939 batteryInfos.size(), lightInfos.size());
2940}
2941
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002942} // namespace android