blob: 7095928d5b187a69aec51af7a5020a683e08df42 [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},
DingYong99f2c3c2023-12-20 15:46:06 +0800126 {"kbd_backlight", InputLightClass::KEYBOARD_BACKLIGHT},
127 {"mic_mute", InputLightClass::KEYBOARD_MIC_MUTE}};
Chris Ye3fdbfef2021-01-06 18:45:18 -0800128
129// Mapping for input multicolor led class node names.
130// https://www.kernel.org/doc/html/latest/leds/leds-class-multicolor.html
131static const std::unordered_map<InputLightClass, std::string> LIGHT_NODES =
132 {{InputLightClass::BRIGHTNESS, "brightness"},
133 {InputLightClass::MULTI_INDEX, "multi_index"},
134 {InputLightClass::MULTI_INTENSITY, "multi_intensity"}};
135
136// Mapping for light color name and the light color
137const std::unordered_map<std::string, LightColor> LIGHT_COLORS = {{"red", LightColor::RED},
138 {"green", LightColor::GREEN},
139 {"blue", LightColor::BLUE}};
140
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000141// Mapping for country code to Layout info.
142// See bCountryCode in 6.2.1 of https://usb.org/sites/default/files/hid1_11.pdf.
143const std::unordered_map<std::int32_t, RawLayoutInfo> LAYOUT_INFOS =
144 {{0, RawLayoutInfo{.languageTag = "", .layoutType = ""}}, // NOT_SUPPORTED
145 {1, RawLayoutInfo{.languageTag = "ar-Arab", .layoutType = ""}}, // ARABIC
146 {2, RawLayoutInfo{.languageTag = "fr-BE", .layoutType = ""}}, // BELGIAN
147 {3, RawLayoutInfo{.languageTag = "fr-CA", .layoutType = ""}}, // CANADIAN_BILINGUAL
148 {4, RawLayoutInfo{.languageTag = "fr-CA", .layoutType = ""}}, // CANADIAN_FRENCH
149 {5, RawLayoutInfo{.languageTag = "cs", .layoutType = ""}}, // CZECH_REPUBLIC
150 {6, RawLayoutInfo{.languageTag = "da", .layoutType = ""}}, // DANISH
151 {7, RawLayoutInfo{.languageTag = "fi", .layoutType = ""}}, // FINNISH
152 {8, RawLayoutInfo{.languageTag = "fr-FR", .layoutType = ""}}, // FRENCH
153 {9, RawLayoutInfo{.languageTag = "de", .layoutType = ""}}, // GERMAN
154 {10, RawLayoutInfo{.languageTag = "el", .layoutType = ""}}, // GREEK
155 {11, RawLayoutInfo{.languageTag = "iw", .layoutType = ""}}, // HEBREW
156 {12, RawLayoutInfo{.languageTag = "hu", .layoutType = ""}}, // HUNGARY
157 {13, RawLayoutInfo{.languageTag = "en", .layoutType = "extended"}}, // INTERNATIONAL (ISO)
158 {14, RawLayoutInfo{.languageTag = "it", .layoutType = ""}}, // ITALIAN
159 {15, RawLayoutInfo{.languageTag = "ja", .layoutType = ""}}, // JAPAN
160 {16, RawLayoutInfo{.languageTag = "ko", .layoutType = ""}}, // KOREAN
161 {17, RawLayoutInfo{.languageTag = "es-419", .layoutType = ""}}, // LATIN_AMERICA
162 {18, RawLayoutInfo{.languageTag = "nl", .layoutType = ""}}, // DUTCH
163 {19, RawLayoutInfo{.languageTag = "nb", .layoutType = ""}}, // NORWEGIAN
164 {20, RawLayoutInfo{.languageTag = "fa", .layoutType = ""}}, // PERSIAN
165 {21, RawLayoutInfo{.languageTag = "pl", .layoutType = ""}}, // POLAND
166 {22, RawLayoutInfo{.languageTag = "pt", .layoutType = ""}}, // PORTUGUESE
167 {23, RawLayoutInfo{.languageTag = "ru", .layoutType = ""}}, // RUSSIA
168 {24, RawLayoutInfo{.languageTag = "sk", .layoutType = ""}}, // SLOVAKIA
169 {25, RawLayoutInfo{.languageTag = "es-ES", .layoutType = ""}}, // SPANISH
170 {26, RawLayoutInfo{.languageTag = "sv", .layoutType = ""}}, // SWEDISH
171 {27, RawLayoutInfo{.languageTag = "fr-CH", .layoutType = ""}}, // SWISS_FRENCH
172 {28, RawLayoutInfo{.languageTag = "de-CH", .layoutType = ""}}, // SWISS_GERMAN
173 {29, RawLayoutInfo{.languageTag = "de-CH", .layoutType = ""}}, // SWITZERLAND
174 {30, RawLayoutInfo{.languageTag = "zh-TW", .layoutType = ""}}, // TAIWAN
175 {31, RawLayoutInfo{.languageTag = "tr", .layoutType = "turkish_q"}}, // TURKISH_Q
176 {32, RawLayoutInfo{.languageTag = "en-GB", .layoutType = ""}}, // UK
177 {33, RawLayoutInfo{.languageTag = "en-US", .layoutType = ""}}, // US
178 {34, RawLayoutInfo{.languageTag = "", .layoutType = ""}}, // YUGOSLAVIA
179 {35, RawLayoutInfo{.languageTag = "tr", .layoutType = "turkish_f"}}}; // TURKISH_F
180
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100181static std::string sha1(const std::string& in) {
Dan Albert677d87e2014-06-16 17:31:28 -0700182 SHA_CTX ctx;
183 SHA1_Init(&ctx);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100184 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
Dan Albert677d87e2014-06-16 17:31:28 -0700185 u_char digest[SHA_DIGEST_LENGTH];
186 SHA1_Final(digest, &ctx);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800187
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100188 std::string out;
Dan Albert677d87e2014-06-16 17:31:28 -0700189 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100190 out += StringPrintf("%02x", digest[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800191 }
192 return out;
193}
194
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800195/**
196 * Return true if name matches "v4l-touch*"
197 */
Chris Ye8594e192020-07-14 10:34:06 -0700198static bool isV4lTouchNode(std::string name) {
199 return name.find("v4l-touch") != std::string::npos;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800200}
201
Philip Quinn39b81682019-01-09 22:20:39 -0800202/**
203 * Returns true if V4L devices should be scanned.
204 *
205 * The system property ro.input.video_enabled can be used to control whether
206 * EventHub scans and opens V4L devices. As V4L does not support multiple
207 * clients, EventHub effectively blocks access to these devices when it opens
Siarhei Vishniakou29f88492019-04-05 14:11:43 -0700208 * them.
209 *
210 * Setting this to "false" would prevent any video devices from being discovered and
211 * associated with input devices.
212 *
213 * This property can be used as follows:
214 * 1. To turn off features that are dependent on video device presence.
215 * 2. During testing and development, to allow other clients to read video devices
216 * directly from /dev.
Philip Quinn39b81682019-01-09 22:20:39 -0800217 */
218static bool isV4lScanningEnabled() {
Harry Cutts33476232023-01-30 19:57:29 +0000219 return property_get_bool("ro.input.video_enabled", /*default_value=*/true);
Philip Quinn39b81682019-01-09 22:20:39 -0800220}
221
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800222static nsecs_t processEventTimestamp(const struct input_event& event) {
223 // Use the time specified in the event instead of the current time
224 // so that downstream code can get more accurate estimates of
225 // event dispatch latency from the time the event is enqueued onto
226 // the evdev client buffer.
227 //
228 // The event's timestamp fortuitously uses the same monotonic clock
229 // time base as the rest of Android. The kernel event device driver
230 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
231 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
232 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
233 // system call that also queries ktime_get_ts().
234
Colin Cross5b799302022-10-18 21:52:41 -0700235 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.input_event_sec) +
236 microseconds_to_nanoseconds(event.input_event_usec);
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800237 return inputEventTime;
238}
239
Kim Low03ea0352020-11-06 12:45:07 -0800240/**
Prabir Pradhancb42b472022-08-23 16:01:19 +0000241 * Returns the sysfs root path of the input device.
Kim Low03ea0352020-11-06 12:45:07 -0800242 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800243static std::optional<std::filesystem::path> getSysfsRootPath(const char* devicePath) {
Kim Low03ea0352020-11-06 12:45:07 -0800244 std::error_code errorCode;
245
246 // Stat the device path to get the major and minor number of the character file
247 struct stat statbuf;
248 if (stat(devicePath, &statbuf) == -1) {
249 ALOGE("Could not stat device %s due to error: %s.", devicePath, std::strerror(errno));
Chris Ye3fdbfef2021-01-06 18:45:18 -0800250 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800251 }
252
253 unsigned int major_num = major(statbuf.st_rdev);
254 unsigned int minor_num = minor(statbuf.st_rdev);
255
256 // Realpath "/sys/dev/char/{major}:{minor}" to get the sysfs path to the input event
257 auto sysfsPath = std::filesystem::path("/sys/dev/char/");
258 sysfsPath /= std::to_string(major_num) + ":" + std::to_string(minor_num);
259 sysfsPath = std::filesystem::canonical(sysfsPath, errorCode);
260
261 // Make sure nothing went wrong in call to canonical()
262 if (errorCode) {
263 ALOGW("Could not run filesystem::canonical() due to error %d : %s.", errorCode.value(),
264 errorCode.message().c_str());
Chris Ye3fdbfef2021-01-06 18:45:18 -0800265 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800266 }
267
268 // Continue to go up a directory until we reach a directory named "input"
269 while (sysfsPath != "/" && sysfsPath.filename() != "input") {
270 sysfsPath = sysfsPath.parent_path();
271 }
272
273 // Then go up one more and you will be at the sysfs root of the device
274 sysfsPath = sysfsPath.parent_path();
275
276 // Make sure we didn't reach root path and that directory actually exists
277 if (sysfsPath == "/" || !std::filesystem::exists(sysfsPath, errorCode)) {
278 if (errorCode) {
279 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
280 errorCode.message().c_str());
281 }
282
283 // Not found
Chris Ye3fdbfef2021-01-06 18:45:18 -0800284 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800285 }
286
287 return sysfsPath;
288}
289
290/**
Chris Ye3fdbfef2021-01-06 18:45:18 -0800291 * Returns the list of files under a specified path.
Kim Low03ea0352020-11-06 12:45:07 -0800292 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800293static std::vector<std::filesystem::path> allFilesInPath(const std::filesystem::path& path) {
294 std::vector<std::filesystem::path> nodes;
295 std::error_code errorCode;
296 auto iter = std::filesystem::directory_iterator(path, errorCode);
297 while (!errorCode && iter != std::filesystem::directory_iterator()) {
298 nodes.push_back(iter->path());
299 iter++;
300 }
301 return nodes;
302}
303
304/**
305 * Returns the list of files under a specified directory in a sysfs path.
306 * Example:
307 * findSysfsNodes(sysfsRootPath, SysfsClass::LEDS) will return all led nodes under "leds" directory
308 * in the sysfs path.
309 */
310static std::vector<std::filesystem::path> findSysfsNodes(const std::filesystem::path& sysfsRoot,
311 SysfsClass clazz) {
Dominik Laskowski75788452021-02-09 18:51:25 -0800312 std::string nodeStr = ftl::enum_string(clazz);
Chris Ye3fdbfef2021-01-06 18:45:18 -0800313 std::for_each(nodeStr.begin(), nodeStr.end(),
314 [](char& c) { c = std::tolower(static_cast<unsigned char>(c)); });
315 std::vector<std::filesystem::path> nodes;
316 for (auto path = sysfsRoot; path != "/" && nodes.empty(); path = path.parent_path()) {
317 nodes = allFilesInPath(path / nodeStr);
318 }
319 return nodes;
320}
321
322static std::optional<std::array<LightColor, COLOR_NUM>> getColorIndexArray(
323 std::filesystem::path path) {
324 std::string indexStr;
325 if (!base::ReadFileToString(path, &indexStr)) {
326 return std::nullopt;
327 }
328
329 // Parse the multi color LED index file, refer to kernel docs
330 // leds/leds-class-multicolor.html
331 std::regex indexPattern("(red|green|blue)\\s(red|green|blue)\\s(red|green|blue)[\\n]");
332 std::smatch results;
333 std::array<LightColor, COLOR_NUM> colors;
334 if (!std::regex_match(indexStr, results, indexPattern)) {
335 return std::nullopt;
336 }
337
338 for (size_t i = 1; i < results.size(); i++) {
339 const auto it = LIGHT_COLORS.find(results[i].str());
340 if (it != LIGHT_COLORS.end()) {
341 // intensities.emplace(it->second, 0);
342 colors[i - 1] = it->second;
Kim Low03ea0352020-11-06 12:45:07 -0800343 }
344 }
Chris Ye3fdbfef2021-01-06 18:45:18 -0800345 return colors;
Kim Low03ea0352020-11-06 12:45:07 -0800346}
347
Prabir Pradhancb42b472022-08-23 16:01:19 +0000348/**
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000349 * Read country code information exposed through the sysfs path and convert it to Layout info.
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000350 */
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000351static std::optional<RawLayoutInfo> readLayoutConfiguration(
352 const std::filesystem::path& sysfsRootPath) {
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000353 // Check the sysfs root path
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000354 int32_t hidCountryCode = -1;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000355 std::string str;
356 if (base::ReadFileToString(sysfsRootPath / "country", &str)) {
357 hidCountryCode = std::stoi(str, nullptr, 16);
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000358 // Update this condition if new supported country codes are added to HID spec.
Vaibhav Devmurari990ff7b2022-12-22 18:23:21 +0000359 if (hidCountryCode > 35 || hidCountryCode < 0) {
360 ALOGE("HID country code should be in range [0, 35], but for sysfs path %s it was %d",
361 sysfsRootPath.c_str(), hidCountryCode);
Vaibhav Devmurari990ff7b2022-12-22 18:23:21 +0000362 }
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000363 }
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000364 const auto it = LAYOUT_INFOS.find(hidCountryCode);
365 if (it != LAYOUT_INFOS.end()) {
366 return it->second;
367 }
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000368
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000369 return std::nullopt;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000370}
371
372/**
Prabir Pradhancb42b472022-08-23 16:01:19 +0000373 * Read information about batteries exposed through the sysfs path.
374 */
375static std::unordered_map<int32_t /*batteryId*/, RawBatteryInfo> readBatteryConfiguration(
376 const std::filesystem::path& sysfsRootPath) {
377 std::unordered_map<int32_t, RawBatteryInfo> batteryInfos;
378 int32_t nextBatteryId = 0;
379 // Check if device has any battery.
380 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::POWER_SUPPLY);
381 for (const auto& nodePath : paths) {
382 RawBatteryInfo info;
383 info.id = ++nextBatteryId;
384 info.path = nodePath;
385 info.name = nodePath.filename();
386
387 // Scan the path for all the files
388 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
389 const auto& files = allFilesInPath(nodePath);
390 for (const auto& file : files) {
391 const auto it = BATTERY_CLASSES.find(file.filename().string());
392 if (it != BATTERY_CLASSES.end()) {
393 info.flags |= it->second;
394 }
395 }
396 batteryInfos.insert_or_assign(info.id, info);
397 ALOGD("configureBatteryLocked rawBatteryId %d name %s", info.id, info.name.c_str());
398 }
399 return batteryInfos;
400}
401
402/**
403 * Read information about lights exposed through the sysfs path.
404 */
405static std::unordered_map<int32_t /*lightId*/, RawLightInfo> readLightsConfiguration(
406 const std::filesystem::path& sysfsRootPath) {
407 std::unordered_map<int32_t, RawLightInfo> lightInfos;
408 int32_t nextLightId = 0;
409 // Check if device has any lights.
410 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::LEDS);
411 for (const auto& nodePath : paths) {
412 RawLightInfo info;
413 info.id = ++nextLightId;
414 info.path = nodePath;
415 info.name = nodePath.filename();
416 info.maxBrightness = std::nullopt;
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000417
418 // Light name should follow the naming pattern <name>:<color>:<function>
419 // Refer kernel docs /leds/leds-class.html for valid supported LED names.
420 std::regex indexPattern("([a-zA-Z0-9_.:]*:)?([a-zA-Z0-9_.]*):([a-zA-Z0-9_.]*)");
421 std::smatch results;
422
423 if (std::regex_match(info.name, results, indexPattern)) {
424 // regex_match will return full match at index 0 and <name> at index 1. For RawLightInfo
425 // we only care about sections <color> and <function> which will be at index 2 and 3.
426 for (int i = 2; i <= 3; i++) {
427 const auto it = LIGHT_CLASSES.find(results.str(i));
428 if (it != LIGHT_CLASSES.end()) {
429 info.flags |= it->second;
430 }
Prabir Pradhancb42b472022-08-23 16:01:19 +0000431 }
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000432
433 // Set name of the raw light to <function> which represents playerIDs for LEDs that
434 // turn on/off based on the current player ID (Refer to PeripheralController.cpp for
435 // player ID logic)
436 info.name = results.str(3);
Prabir Pradhancb42b472022-08-23 16:01:19 +0000437 }
438 // Scan the path for all the files
439 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
440 const auto& files = allFilesInPath(nodePath);
441 for (const auto& file : files) {
442 const auto it = LIGHT_CLASSES.find(file.filename().string());
443 if (it != LIGHT_CLASSES.end()) {
444 info.flags |= it->second;
445 // If the node has maximum brightness, read it
446 if (it->second == InputLightClass::MAX_BRIGHTNESS) {
447 std::string str;
448 if (base::ReadFileToString(file, &str)) {
449 info.maxBrightness = std::stoi(str);
450 }
451 }
452 }
453 }
454 lightInfos.insert_or_assign(info.id, info);
455 ALOGD("configureLightsLocked rawLightId %d name %s", info.id, info.name.c_str());
456 }
457 return lightInfos;
458}
459
Michael Wrightd02c5b62014-02-10 15:10:22 -0800460// --- Global Functions ---
461
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700462ftl::Flags<InputDeviceClass> getAbsAxisUsage(int32_t axis,
463 ftl::Flags<InputDeviceClass> deviceClasses) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800464 // Touch devices get dibs on touch-related axes.
Chris Ye1b0c7342020-07-28 21:57:03 -0700465 if (deviceClasses.test(InputDeviceClass::TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800466 switch (axis) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700467 case ABS_X:
468 case ABS_Y:
469 case ABS_PRESSURE:
470 case ABS_TOOL_WIDTH:
471 case ABS_DISTANCE:
472 case ABS_TILT_X:
473 case ABS_TILT_Y:
474 case ABS_MT_SLOT:
475 case ABS_MT_TOUCH_MAJOR:
476 case ABS_MT_TOUCH_MINOR:
477 case ABS_MT_WIDTH_MAJOR:
478 case ABS_MT_WIDTH_MINOR:
479 case ABS_MT_ORIENTATION:
480 case ABS_MT_POSITION_X:
481 case ABS_MT_POSITION_Y:
482 case ABS_MT_TOOL_TYPE:
483 case ABS_MT_BLOB_ID:
484 case ABS_MT_TRACKING_ID:
485 case ABS_MT_PRESSURE:
486 case ABS_MT_DISTANCE:
Chris Ye1b0c7342020-07-28 21:57:03 -0700487 return InputDeviceClass::TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800488 }
489 }
490
Chris Yef59a2f42020-10-16 12:55:26 -0700491 if (deviceClasses.test(InputDeviceClass::SENSOR)) {
492 switch (axis) {
493 case ABS_X:
494 case ABS_Y:
495 case ABS_Z:
496 case ABS_RX:
497 case ABS_RY:
498 case ABS_RZ:
499 return InputDeviceClass::SENSOR;
500 }
501 }
502
Michael Wright842500e2015-03-13 17:32:02 -0700503 // External stylus gets the pressure axis
Chris Ye1b0c7342020-07-28 21:57:03 -0700504 if (deviceClasses.test(InputDeviceClass::EXTERNAL_STYLUS)) {
Michael Wright842500e2015-03-13 17:32:02 -0700505 if (axis == ABS_PRESSURE) {
Chris Ye1b0c7342020-07-28 21:57:03 -0700506 return InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -0700507 }
508 }
509
Michael Wrightd02c5b62014-02-10 15:10:22 -0800510 // Joystick devices get the rest.
Chris Ye1b0c7342020-07-28 21:57:03 -0700511 return deviceClasses & InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800512}
513
Harry Cuttsea73eaa2023-01-16 17:55:46 +0000514// --- RawAbsoluteAxisInfo ---
515
Harry Cutts67e1ae62024-06-26 10:45:56 +0000516std::ostream& operator<<(std::ostream& out, const std::optional<RawAbsoluteAxisInfo>& info) {
517 if (info) {
518 out << "min=" << info->minValue << ", max=" << info->maxValue << ", flat=" << info->flat
519 << ", fuzz=" << info->fuzz << ", resolution=" << info->resolution;
Harry Cuttsea73eaa2023-01-16 17:55:46 +0000520 } else {
521 out << "unknown range";
522 }
523 return out;
524}
525
Michael Wrightd02c5b62014-02-10 15:10:22 -0800526// --- EventHub::Device ---
527
Prabir Pradhancb42b472022-08-23 16:01:19 +0000528EventHub::Device::Device(int fd, int32_t id, std::string path, InputDeviceIdentifier identifier,
529 std::shared_ptr<const AssociatedDevice> assocDev)
Chris Ye989bb932020-07-04 16:18:59 -0700530 : fd(fd),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700531 id(id),
Prabir Pradhancb42b472022-08-23 16:01:19 +0000532 path(std::move(path)),
533 identifier(std::move(identifier)),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700534 classes(0),
535 configuration(nullptr),
536 virtualKeyMap(nullptr),
537 ffEffectPlaying(false),
538 ffEffectId(-1),
Prabir Pradhancb42b472022-08-23 16:01:19 +0000539 associatedDevice(std::move(assocDev)),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700540 controllerNumber(0),
541 enabled(true),
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000542 isVirtual(fd < 0),
543 currentFrameDropped(false) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800544
545EventHub::Device::~Device() {
546 close();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800547}
548
549void EventHub::Device::close() {
550 if (fd >= 0) {
551 ::close(fd);
552 fd = -1;
553 }
554}
555
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700556status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100557 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700558 if (fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100559 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700560 return -errno;
561 }
562 enabled = true;
563 return OK;
564}
565
566status_t EventHub::Device::disable() {
567 close();
568 enabled = false;
569 return OK;
570}
571
Chris Ye989bb932020-07-04 16:18:59 -0700572bool EventHub::Device::hasValidFd() const {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700573 return !isVirtual && enabled;
574}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800575
Chris Ye3a1e4462020-08-12 10:13:15 -0700576const std::shared_ptr<KeyCharacterMap> EventHub::Device::getKeyCharacterMap() const {
Chris Ye989bb932020-07-04 16:18:59 -0700577 return keyMap.keyCharacterMap;
578}
579
580template <std::size_t N>
581status_t EventHub::Device::readDeviceBitMask(unsigned long ioctlCode, BitArray<N>& bitArray) {
582 if (!hasValidFd()) {
583 return BAD_VALUE;
584 }
585 if ((_IOC_SIZE(ioctlCode) == 0)) {
586 ioctlCode |= _IOC(0, 0, 0, bitArray.bytes());
587 }
588
589 typename BitArray<N>::Buffer buffer;
590 status_t ret = ioctl(fd, ioctlCode, buffer.data());
591 bitArray.loadFromBuffer(buffer);
592 return ret;
593}
594
595void EventHub::Device::configureFd() {
596 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
597 if (classes.test(InputDeviceClass::KEYBOARD)) {
598 // Disable kernel key repeat since we handle it ourselves
599 unsigned int repeatRate[] = {0, 0};
600 if (ioctl(fd, EVIOCSREP, repeatRate)) {
601 ALOGW("Unable to disable kernel key repeat for %s: %s", path.c_str(), strerror(errno));
602 }
603 }
604
605 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
606 // associated with input events. This is important because the input system
607 // uses the timestamps extensively and assumes they were recorded using the monotonic
608 // clock.
609 int clockId = CLOCK_MONOTONIC;
Chris Yef59a2f42020-10-16 12:55:26 -0700610 if (classes.test(InputDeviceClass::SENSOR)) {
611 // Each new sensor event should use the same time base as
612 // SystemClock.elapsedRealtimeNanos().
613 clockId = CLOCK_BOOTTIME;
614 }
Chris Ye989bb932020-07-04 16:18:59 -0700615 bool usingClockIoctl = !ioctl(fd, EVIOCSCLOCKID, &clockId);
616 ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000617
618 // Query the initial state of keys and switches, which is tracked by EventHub.
619 readDeviceState();
620}
621
622void EventHub::Device::readDeviceState() {
623 if (readDeviceBitMask(EVIOCGKEY(0), keyState) < 0) {
624 ALOGD("Unable to query the global key state for %s: %s", path.c_str(), strerror(errno));
625 }
626 if (readDeviceBitMask(EVIOCGSW(0), swState) < 0) {
627 ALOGD("Unable to query the global switch state for %s: %s", path.c_str(), strerror(errno));
628 }
Prabir Pradhan341d0782023-07-14 19:04:10 +0000629
630 // Read absolute axis info and values for all available axes for the device.
631 populateAbsoluteAxisStates();
632}
633
634void EventHub::Device::populateAbsoluteAxisStates() {
635 absState.clear();
636
637 for (int axis = 0; axis <= ABS_MAX; axis++) {
638 if (!absBitmask.test(axis)) {
639 continue;
640 }
641 struct input_absinfo info {};
642 if (ioctl(fd, EVIOCGABS(axis), &info)) {
643 ALOGE("Error reading absolute controller %d for device %s fd %d: %s", axis,
644 identifier.name.c_str(), fd, strerror(errno));
645 continue;
646 }
Prabir Pradhan341d0782023-07-14 19:04:10 +0000647 auto& [axisInfo, value] = absState[axis];
Prabir Pradhan341d0782023-07-14 19:04:10 +0000648 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
Harry Cutts207674d2024-06-06 18:53:41 +00001000std::optional<RawAbsoluteAxisInfo> EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis) const {
Arpit Singh77140f42023-06-13 11:35:27 +00001001 if (axis < 0 || axis > ABS_MAX) {
Harry Cutts207674d2024-06-06 18:53:41 +00001002 return std::nullopt;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001003 }
Arpit Singh77140f42023-06-13 11:35:27 +00001004 std::scoped_lock _l(mLock);
Prabir Pradhan341d0782023-07-14 19:04:10 +00001005 const Device* device = getDeviceLocked(deviceId);
Arpit Singh77140f42023-06-13 11:35:27 +00001006 if (device == nullptr) {
Harry Cutts207674d2024-06-06 18:53:41 +00001007 return std::nullopt;
Arpit Singh77140f42023-06-13 11:35:27 +00001008 }
Prabir Pradhan341d0782023-07-14 19:04:10 +00001009 // We can read the RawAbsoluteAxisInfo even if the device is disabled and doesn't have a valid
1010 // fd, because the info is populated once when the device is first opened, and it doesn't change
1011 // throughout the device lifecycle.
1012 auto it = device->absState.find(axis);
1013 if (it == device->absState.end()) {
Harry Cutts207674d2024-06-06 18:53:41 +00001014 return std::nullopt;
Arpit Singh77140f42023-06-13 11:35:27 +00001015 }
Harry Cutts207674d2024-06-06 18:53:41 +00001016 return it->second.info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001017}
1018
1019bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
1020 if (axis >= 0 && axis <= REL_MAX) {
Chris Ye87143712020-11-10 05:05:58 +00001021 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001022 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001023 return device != nullptr ? device->relBitmask.test(axis) : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001024 }
1025 return false;
1026}
1027
1028bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
Chris Ye87143712020-11-10 05:05:58 +00001029 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001030
Chris Ye989bb932020-07-04 16:18:59 -07001031 Device* device = getDeviceLocked(deviceId);
1032 return property >= 0 && property <= INPUT_PROP_MAX && device != nullptr
1033 ? device->propBitmask.test(property)
1034 : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001035}
1036
Chris Yef59a2f42020-10-16 12:55:26 -07001037bool EventHub::hasMscEvent(int32_t deviceId, int mscEvent) const {
1038 std::scoped_lock _l(mLock);
1039
1040 Device* device = getDeviceLocked(deviceId);
1041 return mscEvent >= 0 && mscEvent <= MSC_MAX && device != nullptr
1042 ? device->mscBitmask.test(mscEvent)
1043 : false;
1044}
1045
Michael Wrightd02c5b62014-02-10 15:10:22 -08001046int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001047 if (scanCode < 0 || scanCode > KEY_MAX) {
1048 return AKEY_STATE_UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001049 }
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001050 std::scoped_lock _l(mLock);
1051 const Device* device = getDeviceLocked(deviceId);
1052 if (device == nullptr || !device->hasValidFd() || !device->keyBitmask.test(scanCode)) {
1053 return AKEY_STATE_UNKNOWN;
1054 }
1055 return device->keyState.test(scanCode) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001056}
1057
1058int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
Chris Ye87143712020-11-10 05:05:58 +00001059 std::scoped_lock _l(mLock);
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001060 const Device* device = getDeviceLocked(deviceId);
1061 if (device == nullptr || !device->hasValidFd() || !device->keyMap.haveKeyLayout()) {
1062 return AKEY_STATE_UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001063 }
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001064 const std::vector<int32_t> scanCodes =
1065 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode);
1066 if (scanCodes.empty()) {
1067 return AKEY_STATE_UNKNOWN;
1068 }
1069 return std::any_of(scanCodes.begin(), scanCodes.end(),
1070 [&device](const int32_t sc) {
1071 return sc >= 0 && sc <= KEY_MAX && device->keyState.test(sc);
1072 })
1073 ? AKEY_STATE_DOWN
1074 : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001075}
1076
Philip Junker4af3b3d2021-12-14 10:36:55 +01001077int32_t EventHub::getKeyCodeForKeyLocation(int32_t deviceId, int32_t locationKeyCode) const {
1078 std::scoped_lock _l(mLock);
1079
1080 Device* device = getDeviceLocked(deviceId);
1081 if (device == nullptr || !device->hasValidFd() || device->keyMap.keyCharacterMap == nullptr ||
1082 device->keyMap.keyLayoutMap == nullptr) {
1083 return AKEYCODE_UNKNOWN;
1084 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001085 std::vector<int32_t> scanCodes =
1086 device->keyMap.keyLayoutMap->findScanCodesForKey(locationKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +01001087 if (scanCodes.empty()) {
1088 ALOGW("Failed to get key code for key location: no scan code maps to key code %d for input"
1089 "device %d",
1090 locationKeyCode, deviceId);
1091 return AKEYCODE_UNKNOWN;
1092 }
1093 if (scanCodes.size() > 1) {
1094 ALOGW("Multiple scan codes map to the same key code %d, returning only the first match",
1095 locationKeyCode);
1096 }
1097 int32_t outKeyCode;
1098 status_t mapKeyRes =
Harry Cutts33476232023-01-30 19:57:29 +00001099 device->getKeyCharacterMap()->mapKey(scanCodes[0], /*usageCode=*/0, &outKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +01001100 switch (mapKeyRes) {
1101 case OK:
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001102 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +01001103 case NAME_NOT_FOUND:
1104 // key character map doesn't re-map this scanCode, hence the keyCode remains the same
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001105 outKeyCode = locationKeyCode;
1106 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +01001107 default:
1108 ALOGW("Failed to get key code for key location: Key character map returned error %s",
1109 statusToString(mapKeyRes).c_str());
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001110 outKeyCode = AKEYCODE_UNKNOWN;
1111 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +01001112 }
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001113 // Remap if there is a Key remapping added to the KCM and return the remapped key
1114 return device->getKeyCharacterMap()->applyKeyRemapping(outKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +01001115}
1116
Michael Wrightd02c5b62014-02-10 15:10:22 -08001117int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001118 if (sw < 0 || sw > SW_MAX) {
1119 return AKEY_STATE_UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001120 }
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001121 std::scoped_lock _l(mLock);
1122 const Device* device = getDeviceLocked(deviceId);
1123 if (device == nullptr || !device->hasValidFd() || !device->swBitmask.test(sw)) {
1124 return AKEY_STATE_UNKNOWN;
1125 }
1126 return device->swState.test(sw) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001127}
1128
Harry Cuttse2c5e202024-06-21 17:08:48 +00001129std::optional<int32_t> EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis) const {
Prabir Pradhan341d0782023-07-14 19:04:10 +00001130 if (axis < 0 || axis > ABS_MAX) {
Harry Cuttse2c5e202024-06-21 17:08:48 +00001131 return std::nullopt;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001132 }
Prabir Pradhan341d0782023-07-14 19:04:10 +00001133 std::scoped_lock _l(mLock);
1134 const Device* device = getDeviceLocked(deviceId);
1135 if (device == nullptr || !device->hasValidFd()) {
Harry Cuttse2c5e202024-06-21 17:08:48 +00001136 return std::nullopt;
Prabir Pradhan341d0782023-07-14 19:04:10 +00001137 }
1138 const auto it = device->absState.find(axis);
1139 if (it == device->absState.end()) {
Harry Cuttse2c5e202024-06-21 17:08:48 +00001140 return std::nullopt;
Prabir Pradhan341d0782023-07-14 19:04:10 +00001141 }
Harry Cuttse2c5e202024-06-21 17:08:48 +00001142 return it->second.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001143}
1144
Arpit Singh4b4a4572023-11-24 18:19:56 +00001145base::Result<std::vector<int32_t>> EventHub::getMtSlotValues(int32_t deviceId, int32_t axis,
1146 size_t slotCount) const {
1147 std::scoped_lock _l(mLock);
1148 const Device* device = getDeviceLocked(deviceId);
1149 if (device == nullptr || !device->hasValidFd() || !device->absBitmask.test(axis)) {
1150 return base::ResultError("device problem or axis not supported", NAME_NOT_FOUND);
1151 }
1152 std::vector<int32_t> outValues(slotCount + 1);
1153 outValues[0] = axis;
1154 const size_t bufferSize = outValues.size() * sizeof(int32_t);
1155 if (ioctl(device->fd, EVIOCGMTSLOTS(bufferSize), outValues.data()) != OK) {
1156 return base::ErrnoError();
1157 }
1158 return std::move(outValues);
1159}
1160
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001161bool EventHub::markSupportedKeyCodes(int32_t deviceId, const std::vector<int32_t>& keyCodes,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001162 uint8_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +00001163 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001164
1165 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001166 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001167 for (size_t codeIndex = 0; codeIndex < keyCodes.size(); codeIndex++) {
Sergej Salnikove5420e72023-05-11 11:52:54 +00001168 if (device->hasKeycodeLocked(keyCodes[codeIndex])) {
1169 outFlags[codeIndex] = 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001170 }
1171 }
1172 return true;
1173 }
1174 return false;
1175}
1176
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001177void EventHub::addKeyRemapping(int32_t deviceId, int32_t fromKeyCode, int32_t toKeyCode) const {
1178 std::scoped_lock _l(mLock);
1179 Device* device = getDeviceLocked(deviceId);
1180 if (device == nullptr) {
1181 return;
1182 }
1183 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
1184 if (kcm) {
1185 kcm->addKeyRemapping(fromKeyCode, toKeyCode);
1186 }
1187}
1188
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001189status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
1190 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +00001191 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001192 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001193 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194
Chris Ye66fbac32020-07-06 20:36:43 -07001195 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001196 // Check the key character map first.
Chris Ye3a1e4462020-08-12 10:13:15 -07001197 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
1198 if (kcm) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001199 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
1200 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001201 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001202 }
1203 }
1204
1205 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001206 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -08001207 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001208 status = NO_ERROR;
1209 }
1210 }
1211
1212 if (status == NO_ERROR) {
Chris Ye3a1e4462020-08-12 10:13:15 -07001213 if (kcm) {
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001214 // Remap keys based on user-defined key remappings and key behavior defined in the
1215 // corresponding kcm file
1216 *outKeycode = kcm->applyKeyRemapping(*outKeycode);
1217
1218 // Remap keys based on Key behavior defined in KCM file
1219 std::tie(*outKeycode, *outMetaState) =
1220 kcm->applyKeyBehavior(*outKeycode, metaState);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001221 } else {
1222 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001223 }
1224 }
1225 }
1226
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001227 if (status != NO_ERROR) {
1228 *outKeycode = 0;
1229 *outFlags = 0;
1230 *outMetaState = metaState;
1231 }
1232
1233 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001234}
1235
1236status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
Chris Ye87143712020-11-10 05:05:58 +00001237 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001238 Device* device = getDeviceLocked(deviceId);
1239
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001240 if (device == nullptr || !device->keyMap.haveKeyLayout()) {
1241 return NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001242 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001243 std::optional<AxisInfo> info = device->keyMap.keyLayoutMap->mapAxis(scanCode);
1244 if (!info.has_value()) {
1245 return NAME_NOT_FOUND;
1246 }
1247 *outAxisInfo = *info;
1248 return NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001249}
1250
Chris Yef59a2f42020-10-16 12:55:26 -07001251base::Result<std::pair<InputDeviceSensorType, int32_t>> EventHub::mapSensor(int32_t deviceId,
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001252 int32_t absCode) const {
Chris Yef59a2f42020-10-16 12:55:26 -07001253 std::scoped_lock _l(mLock);
1254 Device* device = getDeviceLocked(deviceId);
1255
1256 if (device != nullptr && device->keyMap.haveKeyLayout()) {
1257 return device->keyMap.keyLayoutMap->mapSensor(absCode);
1258 }
1259 return Errorf("Device not found or device has no key layout.");
1260}
1261
Chris Yee2b1e5c2021-03-10 22:45:12 -08001262// Gets the battery info map from battery ID to RawBatteryInfo of the miscellaneous device
1263// associated with the device ID. Returns an empty map if no miscellaneous device found.
1264const std::unordered_map<int32_t, RawBatteryInfo>& EventHub::getBatteryInfoLocked(
1265 int32_t deviceId) const {
1266 static const std::unordered_map<int32_t, RawBatteryInfo> EMPTY_BATTERY_INFO = {};
1267 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001268 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001269 return EMPTY_BATTERY_INFO;
1270 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001271 return device->associatedDevice->batteryInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001272}
1273
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001274std::vector<int32_t> EventHub::getRawBatteryIds(int32_t deviceId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001275 std::scoped_lock _l(mLock);
1276 std::vector<int32_t> batteryIds;
1277
Prabir Pradhan51894782022-08-23 16:29:10 +00001278 for (const auto& [id, info] : getBatteryInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001279 batteryIds.push_back(id);
1280 }
1281
1282 return batteryIds;
1283}
1284
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001285std::optional<RawBatteryInfo> EventHub::getRawBatteryInfo(int32_t deviceId,
1286 int32_t batteryId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001287 std::scoped_lock _l(mLock);
1288
1289 const auto infos = getBatteryInfoLocked(deviceId);
1290
1291 auto it = infos.find(batteryId);
1292 if (it != infos.end()) {
1293 return it->second;
1294 }
1295
1296 return std::nullopt;
1297}
1298
1299// Gets the light info map from light ID to RawLightInfo of the miscellaneous device associated
Prabir Pradhan51894782022-08-23 16:29:10 +00001300// with the device ID. Returns an empty map if no miscellaneous device found.
Chris Yee2b1e5c2021-03-10 22:45:12 -08001301const std::unordered_map<int32_t, RawLightInfo>& EventHub::getLightInfoLocked(
1302 int32_t deviceId) const {
1303 static const std::unordered_map<int32_t, RawLightInfo> EMPTY_LIGHT_INFO = {};
1304 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001305 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001306 return EMPTY_LIGHT_INFO;
1307 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001308 return device->associatedDevice->lightInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001309}
1310
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001311std::vector<int32_t> EventHub::getRawLightIds(int32_t deviceId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001312 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001313 std::vector<int32_t> lightIds;
1314
Prabir Pradhan51894782022-08-23 16:29:10 +00001315 for (const auto& [id, info] : getLightInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001316 lightIds.push_back(id);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001317 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001318
Chris Ye3fdbfef2021-01-06 18:45:18 -08001319 return lightIds;
1320}
1321
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001322std::optional<RawLightInfo> EventHub::getRawLightInfo(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001323 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001324
Chris Yee2b1e5c2021-03-10 22:45:12 -08001325 const auto infos = getLightInfoLocked(deviceId);
1326
1327 auto it = infos.find(lightId);
1328 if (it != infos.end()) {
1329 return it->second;
Chris Ye3fdbfef2021-01-06 18:45:18 -08001330 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001331
Chris Ye3fdbfef2021-01-06 18:45:18 -08001332 return std::nullopt;
1333}
1334
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001335std::optional<int32_t> EventHub::getLightBrightness(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001336 std::scoped_lock _l(mLock);
1337
Chris Yee2b1e5c2021-03-10 22:45:12 -08001338 const auto infos = getLightInfoLocked(deviceId);
1339 auto it = infos.find(lightId);
1340 if (it == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001341 return std::nullopt;
1342 }
1343 std::string buffer;
1344 if (!base::ReadFileToString(it->second.path / LIGHT_NODES.at(InputLightClass::BRIGHTNESS),
1345 &buffer)) {
1346 return std::nullopt;
1347 }
1348 return std::stoi(buffer);
1349}
1350
1351std::optional<std::unordered_map<LightColor, int32_t>> EventHub::getLightIntensities(
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001352 int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001353 std::scoped_lock _l(mLock);
1354
Chris Yee2b1e5c2021-03-10 22:45:12 -08001355 const auto infos = getLightInfoLocked(deviceId);
1356 auto lightIt = infos.find(lightId);
1357 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001358 return std::nullopt;
1359 }
1360
1361 auto ret =
1362 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1363
1364 if (!ret.has_value()) {
1365 return std::nullopt;
1366 }
1367 std::array<LightColor, COLOR_NUM> colors = ret.value();
1368
1369 std::string intensityStr;
1370 if (!base::ReadFileToString(lightIt->second.path /
1371 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY),
1372 &intensityStr)) {
1373 return std::nullopt;
1374 }
1375
1376 // Intensity node outputs 3 color values
1377 std::regex intensityPattern("([0-9]+)\\s([0-9]+)\\s([0-9]+)[\\n]");
1378 std::smatch results;
1379
1380 if (!std::regex_match(intensityStr, results, intensityPattern)) {
1381 return std::nullopt;
1382 }
1383 std::unordered_map<LightColor, int32_t> intensities;
1384 for (size_t i = 1; i < results.size(); i++) {
1385 int value = std::stoi(results[i].str());
1386 intensities.emplace(colors[i - 1], value);
1387 }
1388 return intensities;
1389}
1390
1391void EventHub::setLightBrightness(int32_t deviceId, int32_t lightId, int32_t brightness) {
1392 std::scoped_lock _l(mLock);
1393
Chris Yee2b1e5c2021-03-10 22:45:12 -08001394 const auto infos = getLightInfoLocked(deviceId);
1395 auto lightIt = infos.find(lightId);
1396 if (lightIt == infos.end()) {
1397 ALOGE("%s lightId %d not found ", __func__, lightId);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001398 return;
1399 }
1400
1401 if (!base::WriteStringToFile(std::to_string(brightness),
1402 lightIt->second.path /
1403 LIGHT_NODES.at(InputLightClass::BRIGHTNESS))) {
1404 ALOGE("Can not write to file, error: %s", strerror(errno));
1405 }
1406}
1407
1408void EventHub::setLightIntensities(int32_t deviceId, int32_t lightId,
1409 std::unordered_map<LightColor, int32_t> intensities) {
1410 std::scoped_lock _l(mLock);
1411
Chris Yee2b1e5c2021-03-10 22:45:12 -08001412 const auto infos = getLightInfoLocked(deviceId);
1413 auto lightIt = infos.find(lightId);
1414 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001415 ALOGE("Light Id %d does not exist.", lightId);
1416 return;
1417 }
1418
1419 auto ret =
1420 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1421
1422 if (!ret.has_value()) {
1423 return;
1424 }
1425 std::array<LightColor, COLOR_NUM> colors = ret.value();
1426
1427 std::string rgbStr;
1428 for (size_t i = 0; i < COLOR_NUM; i++) {
1429 auto it = intensities.find(colors[i]);
1430 if (it != intensities.end()) {
1431 rgbStr += std::to_string(it->second);
1432 // Insert space between colors
1433 if (i < COLOR_NUM - 1) {
1434 rgbStr += " ";
1435 }
1436 }
1437 }
1438 // Append new line
1439 rgbStr += "\n";
1440
1441 if (!base::WriteStringToFile(rgbStr,
1442 lightIt->second.path /
1443 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY))) {
1444 ALOGE("Can not write to file, error: %s", strerror(errno));
1445 }
1446}
1447
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001448std::optional<RawLayoutInfo> EventHub::getRawLayoutInfo(int32_t deviceId) const {
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001449 std::scoped_lock _l(mLock);
1450 Device* device = getDeviceLocked(deviceId);
1451 if (device == nullptr || !device->associatedDevice) {
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001452 return std::nullopt;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001453 }
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001454 return device->associatedDevice->layoutInfo;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001455}
1456
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001457void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Chris Ye87143712020-11-10 05:05:58 +00001458 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001459
1460 mExcludedDevices = devices;
1461}
1462
1463bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
Chris Ye87143712020-11-10 05:05:58 +00001464 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001465 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001466 if (device != nullptr && scanCode >= 0 && scanCode <= KEY_MAX) {
1467 return device->keyBitmask.test(scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001468 }
1469 return false;
1470}
1471
Arthur Hungcb40a002021-08-03 14:31:01 +00001472bool EventHub::hasKeyCode(int32_t deviceId, int32_t keyCode) const {
1473 std::scoped_lock _l(mLock);
1474 Device* device = getDeviceLocked(deviceId);
1475 if (device != nullptr) {
1476 return device->hasKeycodeLocked(keyCode);
1477 }
1478 return false;
1479}
1480
Michael Wrightd02c5b62014-02-10 15:10:22 -08001481bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
Chris Ye87143712020-11-10 05:05:58 +00001482 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001483 Device* device = getDeviceLocked(deviceId);
1484 int32_t sc;
Chris Ye989bb932020-07-04 16:18:59 -07001485 if (device != nullptr && device->mapLed(led, &sc) == NO_ERROR) {
Chris Ye66fbac32020-07-06 20:36:43 -07001486 return device->ledBitmask.test(sc);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001487 }
1488 return false;
1489}
1490
1491void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
Chris Ye87143712020-11-10 05:05:58 +00001492 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001493 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -07001494 if (device != nullptr && device->hasValidFd()) {
1495 device->setLedStateLocked(led, on);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001496 }
1497}
1498
1499void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001500 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001501 outVirtualKeys.clear();
1502
Chris Ye87143712020-11-10 05:05:58 +00001503 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001504 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001505 if (device != nullptr && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001506 const std::vector<VirtualKeyDefinition> virtualKeys =
1507 device->virtualKeyMap->getVirtualKeys();
1508 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001509 }
1510}
1511
Chris Ye3a1e4462020-08-12 10:13:15 -07001512const std::shared_ptr<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001513 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001514 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001515 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001516 return device->getKeyCharacterMap();
1517 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001518 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001519}
1520
Vaibhav Devmurari23e8ae92022-12-29 12:07:56 +00001521// If provided map is null, it will reset key character map to default KCM.
Chris Ye3a1e4462020-08-12 10:13:15 -07001522bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, std::shared_ptr<KeyCharacterMap> map) {
Chris Ye87143712020-11-10 05:05:58 +00001523 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001524 Device* device = getDeviceLocked(deviceId);
Vaibhav Devmurari23e8ae92022-12-29 12:07:56 +00001525 if (device == nullptr || device->keyMap.keyCharacterMap == nullptr) {
Philip Junker90bc9492021-12-10 18:39:42 +01001526 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001527 }
Vaibhav Devmurari23e8ae92022-12-29 12:07:56 +00001528 if (map == nullptr) {
1529 device->keyMap.keyCharacterMap->clearLayoutOverlay();
1530 return true;
1531 }
Philip Junker90bc9492021-12-10 18:39:42 +01001532 device->keyMap.keyCharacterMap->combine(*map);
1533 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001534}
1535
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001536static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
1537 std::string rawDescriptor;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001538 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001539 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001540 if (!identifier.uniqueId.empty()) {
1541 rawDescriptor += "uniqueId:";
1542 rawDescriptor += identifier.uniqueId;
Josh Bartel938632f2022-07-19 15:34:22 -05001543 }
1544 if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001545 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001546 }
1547
1548 if (identifier.vendor == 0 && identifier.product == 0) {
1549 // If we don't know the vendor and product id, then the device is probably
1550 // built-in so we need to rely on other information to uniquely identify
1551 // the input device. Usually we try to avoid relying on the device name or
1552 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001553 if (!identifier.name.empty()) {
1554 rawDescriptor += "name:";
1555 rawDescriptor += identifier.name;
1556 } else if (!identifier.location.empty()) {
1557 rawDescriptor += "location:";
1558 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001559 }
1560 }
1561 identifier.descriptor = sha1(rawDescriptor);
1562 return rawDescriptor;
1563}
1564
1565void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
1566 // Compute a device descriptor that uniquely identifies the device.
1567 // The descriptor is assumed to be a stable identifier. Its value should not
1568 // change between reboots, reconnections, firmware updates or new releases
1569 // of Android. In practice we sometimes get devices that cannot be uniquely
1570 // identified. In this case we enforce uniqueness between connected devices.
1571 // Ideally, we also want the descriptor to be short and relatively opaque.
Josh Bartel938632f2022-07-19 15:34:22 -05001572 // Note that we explicitly do not use the path or location for external devices
1573 // as their path or location will change as they are plugged/unplugged or moved
1574 // to different ports. We do fallback to using name and location in the case of
1575 // internal devices which are detected by the vendor and product being 0 in
1576 // generateDescriptor. If two identical descriptors are detected we will fallback
1577 // to using a 'nonce' and incrementing it until the new descriptor no longer has
1578 // a match with any existing descriptors.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001579
1580 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001581 std::string rawDescriptor = generateDescriptor(identifier);
Josh Bartel938632f2022-07-19 15:34:22 -05001582 // Enforce that the generated descriptor is unique.
1583 while (hasDeviceWithDescriptorLocked(identifier.descriptor)) {
1584 identifier.nonce++;
1585 rawDescriptor = generateDescriptor(identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001586 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001587 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001588 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001589}
1590
Prabir Pradhancb42b472022-08-23 16:01:19 +00001591std::shared_ptr<const EventHub::AssociatedDevice> EventHub::obtainAssociatedDeviceLocked(
1592 const std::filesystem::path& devicePath) const {
1593 const std::optional<std::filesystem::path> sysfsRootPathOpt =
1594 getSysfsRootPath(devicePath.c_str());
1595 if (!sysfsRootPathOpt) {
1596 return nullptr;
1597 }
1598
1599 const auto& path = *sysfsRootPathOpt;
Prabir Pradhancb42b472022-08-23 16:01:19 +00001600
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00001601 std::shared_ptr<const AssociatedDevice> associatedDevice = std::make_shared<AssociatedDevice>(
Prabir Pradhancb42b472022-08-23 16:01:19 +00001602 AssociatedDevice{.sysfsRootPath = path,
1603 .batteryInfos = readBatteryConfiguration(path),
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001604 .lightInfos = readLightsConfiguration(path),
1605 .layoutInfo = readLayoutConfiguration(path)});
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00001606
1607 bool associatedDeviceChanged = false;
1608 for (const auto& [id, dev] : mDevices) {
1609 if (dev->associatedDevice && dev->associatedDevice->sysfsRootPath == path) {
1610 if (*associatedDevice != *dev->associatedDevice) {
1611 associatedDeviceChanged = true;
1612 dev->associatedDevice = associatedDevice;
1613 }
1614 associatedDevice = dev->associatedDevice;
1615 }
1616 }
1617 ALOGI_IF(associatedDeviceChanged,
1618 "The AssociatedDevice changed for path '%s'. Using new AssociatedDevice: %s",
1619 path.c_str(), associatedDevice->dump().c_str());
1620
1621 return associatedDevice;
Prabir Pradhancb42b472022-08-23 16:01:19 +00001622}
1623
Vaibhav Devmurari5fc7d852023-03-17 18:43:33 +00001624bool EventHub::AssociatedDevice::isChanged() const {
1625 std::unordered_map<int32_t, RawBatteryInfo> newBatteryInfos =
1626 readBatteryConfiguration(sysfsRootPath);
1627 std::unordered_map<int32_t, RawLightInfo> newLightInfos =
1628 readLightsConfiguration(sysfsRootPath);
1629 std::optional<RawLayoutInfo> newLayoutInfo = readLayoutConfiguration(sysfsRootPath);
1630
1631 if (newBatteryInfos == batteryInfos && newLightInfos == lightInfos &&
1632 newLayoutInfo == layoutInfo) {
1633 return false;
1634 }
1635 return true;
1636}
1637
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001638void EventHub::vibrate(int32_t deviceId, const VibrationElement& element) {
Chris Ye87143712020-11-10 05:05:58 +00001639 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001640 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001641 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001642 ff_effect effect;
1643 memset(&effect, 0, sizeof(effect));
1644 effect.type = FF_RUMBLE;
1645 effect.id = device->ffEffectId;
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001646 // evdev FF_RUMBLE effect only supports two channels of vibration.
Chris Ye6393a262020-08-04 19:41:36 -07001647 effect.u.rumble.strong_magnitude = element.getMagnitude(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1648 effect.u.rumble.weak_magnitude = element.getMagnitude(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001649 effect.replay.length = element.duration.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001650 effect.replay.delay = 0;
1651 if (ioctl(device->fd, EVIOCSFF, &effect)) {
1652 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001653 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001654 return;
1655 }
1656 device->ffEffectId = effect.id;
1657
1658 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -07001659 ev.input_event_sec = 0;
1660 ev.input_event_usec = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001661 ev.type = EV_FF;
1662 ev.code = device->ffEffectId;
1663 ev.value = 1;
1664 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1665 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001666 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001667 return;
1668 }
1669 device->ffEffectPlaying = true;
1670 }
1671}
1672
1673void EventHub::cancelVibrate(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001674 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001675 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001676 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001677 if (device->ffEffectPlaying) {
1678 device->ffEffectPlaying = false;
1679
1680 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -07001681 ev.input_event_sec = 0;
1682 ev.input_event_usec = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001683 ev.type = EV_FF;
1684 ev.code = device->ffEffectId;
1685 ev.value = 0;
1686 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1687 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001688 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001689 return;
1690 }
1691 }
1692 }
1693}
1694
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001695std::vector<int32_t> EventHub::getVibratorIds(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001696 std::scoped_lock _l(mLock);
1697 std::vector<int32_t> vibrators;
1698 Device* device = getDeviceLocked(deviceId);
1699 if (device != nullptr && device->hasValidFd() &&
1700 device->classes.test(InputDeviceClass::VIBRATOR)) {
1701 vibrators.push_back(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1702 vibrators.push_back(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
1703 }
1704 return vibrators;
1705}
1706
Josh Bartel938632f2022-07-19 15:34:22 -05001707/**
1708 * Checks both mDevices and mOpeningDevices for a device with the descriptor passed.
1709 */
1710bool EventHub::hasDeviceWithDescriptorLocked(const std::string& descriptor) const {
1711 for (const auto& device : mOpeningDevices) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001712 if (descriptor == device->identifier.descriptor) {
Josh Bartel938632f2022-07-19 15:34:22 -05001713 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001714 }
1715 }
Josh Bartel938632f2022-07-19 15:34:22 -05001716
1717 for (const auto& [id, device] : mDevices) {
1718 if (descriptor == device->identifier.descriptor) {
1719 return true;
1720 }
1721 }
1722 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001723}
1724
1725EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001726 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001727 deviceId = mBuiltInKeyboardId;
1728 }
Chris Ye989bb932020-07-04 16:18:59 -07001729 const auto& it = mDevices.find(deviceId);
1730 return it != mDevices.end() ? it->second.get() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001731}
1732
Chris Ye8594e192020-07-14 10:34:06 -07001733EventHub::Device* EventHub::getDeviceByPathLocked(const std::string& devicePath) const {
Chris Ye989bb932020-07-04 16:18:59 -07001734 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001735 if (device->path == devicePath) {
Chris Ye989bb932020-07-04 16:18:59 -07001736 return device.get();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001737 }
1738 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001739 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001740}
1741
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001742/**
1743 * The file descriptor could be either input device, or a video device (associated with a
1744 * specific input device). Check both cases here, and return the device that this event
1745 * belongs to. Caller can compare the fd's once more to determine event type.
1746 * Looks through all input devices, and only attached video devices. Unattached video
1747 * devices are ignored.
1748 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001749EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
Chris Ye989bb932020-07-04 16:18:59 -07001750 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001751 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001752 // This is an input device event
Chris Ye989bb932020-07-04 16:18:59 -07001753 return device.get();
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001754 }
1755 if (device->videoDevice && device->videoDevice->getFd() == fd) {
1756 // This is a video device event
Chris Ye989bb932020-07-04 16:18:59 -07001757 return device.get();
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001758 }
1759 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001760 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
1761 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001762 return nullptr;
1763}
1764
Chris Yee2b1e5c2021-03-10 22:45:12 -08001765std::optional<int32_t> EventHub::getBatteryCapacity(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001766 std::filesystem::path batteryPath;
1767 {
1768 // Do not read the sysfs node to get the battery state while holding
1769 // the EventHub lock. For some peripheral devices, reading battery state
1770 // can be broken and take 5+ seconds. Holding the lock in this case would
1771 // block all other event processing during this time. For now, we assume this
1772 // call never happens on the InputReader thread and read the sysfs node outside
1773 // the lock to prevent event processing from being blocked by this call.
1774 std::scoped_lock _l(mLock);
Kim Low03ea0352020-11-06 12:45:07 -08001775
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001776 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001777 auto it = infos.find(batteryId);
1778 if (it == infos.end()) {
1779 return std::nullopt;
1780 }
1781 batteryPath = it->second.path;
1782 } // release lock
1783
Chris Yee2b1e5c2021-03-10 22:45:12 -08001784 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001785
1786 // Some devices report battery capacity as an integer through the "capacity" file
Andy Chenf9f1a022022-08-29 20:07:10 -04001787 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001788 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001789 return std::stoi(base::Trim(buffer));
Kim Low03ea0352020-11-06 12:45:07 -08001790 }
1791
1792 // Other devices report capacity as an enum value POWER_SUPPLY_CAPACITY_LEVEL_XXX
1793 // These values are taken from kernel source code include/linux/power_supply.h
Andy Chenf9f1a022022-08-29 20:07:10 -04001794 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY_LEVEL),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001795 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001796 // Remove any white space such as trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001797 const auto levelIt = BATTERY_LEVEL.find(base::Trim(buffer));
1798 if (levelIt != BATTERY_LEVEL.end()) {
1799 return levelIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001800 }
1801 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001802
Kim Low03ea0352020-11-06 12:45:07 -08001803 return std::nullopt;
1804}
1805
Chris Yee2b1e5c2021-03-10 22:45:12 -08001806std::optional<int32_t> EventHub::getBatteryStatus(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001807 std::filesystem::path batteryPath;
1808 {
1809 // Do not read the sysfs node to get the battery state while holding
1810 // the EventHub lock. For some peripheral devices, reading battery state
1811 // can be broken and take 5+ seconds. Holding the lock in this case would
1812 // block all other event processing during this time. For now, we assume this
1813 // call never happens on the InputReader thread and read the sysfs node outside
1814 // the lock to prevent event processing from being blocked by this call.
1815 std::scoped_lock _l(mLock);
1816
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001817 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001818 auto it = infos.find(batteryId);
1819 if (it == infos.end()) {
1820 return std::nullopt;
1821 }
1822 batteryPath = it->second.path;
1823 } // release lock
1824
Chris Yee2b1e5c2021-03-10 22:45:12 -08001825 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001826
Andy Chenf9f1a022022-08-29 20:07:10 -04001827 if (!base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::STATUS),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001828 &buffer)) {
Kim Low03ea0352020-11-06 12:45:07 -08001829 ALOGE("Failed to read sysfs battery info: %s", strerror(errno));
1830 return std::nullopt;
1831 }
1832
Chris Yed1936772021-02-22 10:30:40 -08001833 // Remove white space like trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001834 const auto statusIt = BATTERY_STATUS.find(base::Trim(buffer));
1835 if (statusIt != BATTERY_STATUS.end()) {
1836 return statusIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001837 }
1838
1839 return std::nullopt;
1840}
1841
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001842std::vector<RawEvent> EventHub::getEvents(int timeoutMillis) {
Chris Ye87143712020-11-10 05:05:58 +00001843 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001844
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001845 std::array<input_event, EVENT_BUFFER_SIZE> readBuffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001846
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001847 std::vector<RawEvent> events;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001848 bool awoken = false;
1849 for (;;) {
1850 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
1851
1852 // Reopen input devices if needed.
1853 if (mNeedToReopenDevices) {
1854 mNeedToReopenDevices = false;
1855
1856 ALOGI("Reopening all input devices due to a configuration change.");
1857
1858 closeAllDevicesLocked();
1859 mNeedToScanDevices = true;
1860 break; // return to the caller before we actually rescan
1861 }
1862
1863 // Report any devices that had last been added/removed.
Chris Ye989bb932020-07-04 16:18:59 -07001864 for (auto it = mClosingDevices.begin(); it != mClosingDevices.end();) {
1865 std::unique_ptr<Device> device = std::move(*it);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001866 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001867 const int32_t deviceId = (device->id == mBuiltInKeyboardId)
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001868 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
1869 : device->id;
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001870 events.push_back({
1871 .when = now,
1872 .deviceId = deviceId,
1873 .type = DEVICE_REMOVED,
1874 });
Chris Ye989bb932020-07-04 16:18:59 -07001875 it = mClosingDevices.erase(it);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001876 mNeedToSendFinishedDeviceScan = true;
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001877 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001878 break;
1879 }
1880 }
1881
1882 if (mNeedToScanDevices) {
1883 mNeedToScanDevices = false;
1884 scanDevicesLocked();
1885 mNeedToSendFinishedDeviceScan = true;
1886 }
1887
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001888 while (!mOpeningDevices.empty()) {
1889 std::unique_ptr<Device> device = std::move(*mOpeningDevices.rbegin());
1890 mOpeningDevices.pop_back();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001891 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001892 const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1893 events.push_back({
1894 .when = now,
1895 .deviceId = deviceId,
1896 .type = DEVICE_ADDED,
1897 });
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001898
1899 // Try to find a matching video device by comparing device names
1900 for (auto it = mUnattachedVideoDevices.begin(); it != mUnattachedVideoDevices.end();
1901 it++) {
1902 std::unique_ptr<TouchVideoDevice>& videoDevice = *it;
Chris Yed3fef462021-03-07 17:10:08 -08001903 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001904 // videoDevice was transferred to 'device'
1905 it = mUnattachedVideoDevices.erase(it);
1906 break;
1907 }
1908 }
1909
1910 auto [dev_it, inserted] = mDevices.insert_or_assign(device->id, std::move(device));
1911 if (!inserted) {
Chris Ye989bb932020-07-04 16:18:59 -07001912 ALOGW("Device id %d exists, replaced.", device->id);
1913 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001914 mNeedToSendFinishedDeviceScan = true;
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001915 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001916 break;
1917 }
1918 }
1919
1920 if (mNeedToSendFinishedDeviceScan) {
1921 mNeedToSendFinishedDeviceScan = false;
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001922 events.push_back({
1923 .when = now,
1924 .type = FINISHED_DEVICE_SCAN,
1925 });
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001926 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001927 break;
1928 }
1929 }
1930
1931 // Grab the next input event.
1932 bool deviceChanged = false;
1933 while (mPendingEventIndex < mPendingEventCount) {
1934 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001935 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001936 if (eventItem.events & EPOLLIN) {
1937 mPendingINotify = true;
1938 } else {
1939 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
1940 }
1941 continue;
1942 }
1943
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001944 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001945 if (eventItem.events & EPOLLIN) {
1946 ALOGV("awoken after wake()");
1947 awoken = true;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001948 char wakeReadBuffer[16];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001949 ssize_t nRead;
1950 do {
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001951 nRead = read(mWakeReadPipeFd, wakeReadBuffer, sizeof(wakeReadBuffer));
1952 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(wakeReadBuffer));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001953 } else {
1954 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001955 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001956 }
1957 continue;
1958 }
1959
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001960 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Chris Ye989bb932020-07-04 16:18:59 -07001961 if (device == nullptr) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001962 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
1963 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001964 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001965 continue;
1966 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001967 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
1968 if (eventItem.events & EPOLLIN) {
1969 size_t numFrames = device->videoDevice->readAndQueueFrames();
1970 if (numFrames == 0) {
1971 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001972 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001973 }
1974 } else if (eventItem.events & EPOLLHUP) {
1975 // TODO(b/121395353) - consider adding EPOLLRDHUP
1976 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001977 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001978 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1979 device->videoDevice = nullptr;
1980 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001981 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1982 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001983 ALOG_ASSERT(!DEBUG);
1984 }
1985 continue;
1986 }
1987 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -08001988 if (eventItem.events & EPOLLIN) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001989 int32_t readSize =
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001990 read(device->fd, readBuffer.data(),
1991 sizeof(decltype(readBuffer)::value_type) * readBuffer.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001992 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
1993 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -07001994 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001995 " capacity: %zu errno: %d)\n",
1996 device->fd, readSize, readBuffer.size(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001997 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001998 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001999 } else if (readSize < 0) {
2000 if (errno != EAGAIN && errno != EINTR) {
2001 ALOGW("could not get event (errno=%d)", errno);
2002 }
2003 } else if ((readSize % sizeof(struct input_event)) != 0) {
2004 ALOGE("could not get event (wrong size: %d)", readSize);
2005 } else {
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002006 const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002007
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002008 const size_t count = size_t(readSize) / sizeof(struct input_event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002009 for (size_t i = 0; i < count; i++) {
2010 struct input_event& iev = readBuffer[i];
Prabir Pradhan9762ac92023-07-13 21:45:12 +00002011 device->trackInputEvent(iev);
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002012 events.push_back({
2013 .when = processEventTimestamp(iev),
2014 .readTime = systemTime(SYSTEM_TIME_MONOTONIC),
2015 .deviceId = deviceId,
2016 .type = iev.type,
2017 .code = iev.code,
2018 .value = iev.value,
2019 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08002020 }
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07002021 if (events.size() >= EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002022 // The result buffer is full. Reset the pending event index
2023 // so we will try to read the device again on the next iteration.
2024 mPendingEventIndex -= 1;
2025 break;
2026 }
2027 }
2028 } else if (eventItem.events & EPOLLHUP) {
2029 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002030 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002031 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07002032 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002033 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002034 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
2035 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002036 }
2037 }
2038
2039 // readNotify() will modify the list of devices so this must be done after
2040 // processing all other events to ensure that we read all remaining events
2041 // before closing the devices.
2042 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
2043 mPendingINotify = false;
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002044 const auto res = readNotifyLocked();
2045 if (!res.ok()) {
2046 ALOGW("Failed to read from inotify: %s", res.error().message().c_str());
2047 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002048 deviceChanged = true;
2049 }
2050
2051 // Report added or removed devices immediately.
2052 if (deviceChanged) {
2053 continue;
2054 }
2055
2056 // Return now if we have collected any events or if we were explicitly awoken.
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002057 if (!events.empty() || awoken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002058 break;
2059 }
2060
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01002061 // Poll for events.
2062 // When a device driver has pending (unread) events, it acquires
2063 // a kernel wake lock. Once the last pending event has been read, the device
2064 // driver will release the kernel wake lock, but the epoll will hold the wakelock,
2065 // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
2066 // is called again for the same fd that produced the event.
2067 // Thus the system can only sleep if there are no events pending or
2068 // currently being processed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002069 //
2070 // The timeout is advisory only. If the device is asleep, it will not wake just to
2071 // service the timeout.
2072 mPendingEventIndex = 0;
2073
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01002074 mLock.unlock(); // release lock before poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08002075
2076 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
2077
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01002078 mLock.lock(); // reacquire lock after poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08002079
2080 if (pollResult == 0) {
2081 // Timed out.
2082 mPendingEventCount = 0;
2083 break;
2084 }
2085
2086 if (pollResult < 0) {
2087 // An error occurred.
2088 mPendingEventCount = 0;
2089
2090 // Sleep after errors to avoid locking up the system.
2091 // Hopefully the error is transient.
2092 if (errno != EINTR) {
2093 ALOGW("poll failed (errno=%d)\n", errno);
2094 usleep(100000);
2095 }
2096 } else {
2097 // Some events occurred.
2098 mPendingEventCount = size_t(pollResult);
2099 }
2100 }
2101
2102 // All done, return the number of events we read.
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002103 return events;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002104}
2105
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08002106std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002107 std::scoped_lock _l(mLock);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08002108
2109 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07002110 if (device == nullptr || !device->videoDevice) {
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08002111 return {};
2112 }
2113 return device->videoDevice->consumeFrames();
2114}
2115
Michael Wrightd02c5b62014-02-10 15:10:22 -08002116void EventHub::wake() {
2117 ALOGV("wake() called");
2118
2119 ssize_t nWrite;
2120 do {
2121 nWrite = write(mWakeWritePipeFd, "W", 1);
2122 } while (nWrite == -1 && errno == EINTR);
2123
2124 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002125 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002126 }
2127}
2128
2129void EventHub::scanDevicesLocked() {
Usama Arifb27c8e62021-06-03 16:44:09 +01002130 status_t result;
2131 std::error_code errorCode;
2132
2133 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
2134 result = scanDirLocked(DEVICE_INPUT_PATH);
2135 if (result < 0) {
2136 ALOGE("scan dir failed for %s", DEVICE_INPUT_PATH);
2137 }
2138 } else {
2139 if (errorCode) {
2140 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
2141 errorCode.message().c_str());
2142 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002143 }
Philip Quinn39b81682019-01-09 22:20:39 -08002144 if (isV4lScanningEnabled()) {
Usama Arifb27c8e62021-06-03 16:44:09 +01002145 result = scanVideoDirLocked(DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08002146 if (result != OK) {
Usama Arifb27c8e62021-06-03 16:44:09 +01002147 ALOGE("scan video dir failed for %s", DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08002148 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002149 }
Chris Ye989bb932020-07-04 16:18:59 -07002150 if (mDevices.find(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) == mDevices.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002151 createVirtualKeyboardLocked();
2152 }
2153}
2154
2155// ----------------------------------------------------------------------------
2156
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002157status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002158 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002159 struct epoll_event eventItem = {};
2160 eventItem.events = EPOLLIN | EPOLLWAKEUP;
2161 eventItem.data.fd = fd;
2162 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
2163 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002164 return -errno;
2165 }
2166 return OK;
2167}
2168
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002169status_t EventHub::unregisterFdFromEpoll(int fd) {
2170 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
2171 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
2172 return -errno;
2173 }
2174 return OK;
2175}
2176
Chris Ye989bb932020-07-04 16:18:59 -07002177status_t EventHub::registerDeviceForEpollLocked(Device& device) {
2178 status_t result = registerFdForEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002179 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07002180 ALOGE("Could not add input device fd to epoll for device %" PRId32, device.id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002181 return result;
2182 }
Chris Ye989bb932020-07-04 16:18:59 -07002183 if (device.videoDevice) {
2184 registerVideoDeviceForEpollLocked(*device.videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002185 }
2186 return result;
2187}
2188
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002189void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
2190 status_t result = registerFdForEpoll(videoDevice.getFd());
2191 if (result != OK) {
2192 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
2193 }
2194}
2195
Chris Ye989bb932020-07-04 16:18:59 -07002196status_t EventHub::unregisterDeviceFromEpollLocked(Device& device) {
2197 if (device.hasValidFd()) {
2198 status_t result = unregisterFdFromEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002199 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07002200 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device.id);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002201 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002202 }
2203 }
Chris Ye989bb932020-07-04 16:18:59 -07002204 if (device.videoDevice) {
2205 unregisterVideoDeviceFromEpollLocked(*device.videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002206 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002207 return OK;
2208}
2209
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002210void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
2211 if (videoDevice.hasValidFd()) {
2212 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
2213 if (result != OK) {
2214 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002215 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002216 }
2217 }
2218}
2219
Chris Yed3fef462021-03-07 17:10:08 -08002220void EventHub::reportDeviceAddedForStatisticsLocked(const InputDeviceIdentifier& identifier,
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002221 ftl::Flags<InputDeviceClass> classes) {
Chris Ye657c2f02021-05-25 16:24:37 -07002222 SHA256_CTX ctx;
2223 SHA256_Init(&ctx);
2224 SHA256_Update(&ctx, reinterpret_cast<const uint8_t*>(identifier.uniqueId.c_str()),
2225 identifier.uniqueId.size());
2226 std::array<uint8_t, SHA256_DIGEST_LENGTH> digest;
2227 SHA256_Final(digest.data(), &ctx);
2228
2229 std::string obfuscatedId;
2230 for (size_t i = 0; i < OBFUSCATED_LENGTH; i++) {
2231 obfuscatedId += StringPrintf("%02x", digest[i]);
2232 }
2233
Chris Yed3fef462021-03-07 17:10:08 -08002234 android::util::stats_write(android::util::INPUTDEVICE_REGISTERED, identifier.name.c_str(),
2235 identifier.vendor, identifier.product, identifier.version,
Chris Ye657c2f02021-05-25 16:24:37 -07002236 identifier.bus, obfuscatedId.c_str(), classes.get());
Chris Yed3fef462021-03-07 17:10:08 -08002237}
2238
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002239void EventHub::openDeviceLocked(const std::string& devicePath) {
2240 // If an input device happens to register around the time when EventHub's constructor runs, it
2241 // is possible that the same input event node (for example, /dev/input/event3) will be noticed
2242 // in both 'inotify' callback and also in the 'scanDirLocked' pass. To prevent duplicate devices
2243 // from getting registered, ensure that this path is not already covered by an existing device.
2244 for (const auto& [deviceId, device] : mDevices) {
2245 if (device->path == devicePath) {
2246 return; // device was already registered
2247 }
2248 }
2249
Michael Wrightd02c5b62014-02-10 15:10:22 -08002250 char buffer[80];
2251
Chris Ye8594e192020-07-14 10:34:06 -07002252 ALOGV("Opening device: %s", devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002253
Chris Ye8594e192020-07-14 10:34:06 -07002254 int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002255 if (fd < 0) {
Chris Ye8594e192020-07-14 10:34:06 -07002256 ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002257 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002258 }
2259
2260 InputDeviceIdentifier identifier;
2261
2262 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002263 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Chris Ye8594e192020-07-14 10:34:06 -07002264 ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002265 } else {
2266 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002267 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002268 }
2269
2270 // Check to see if the device is on our excluded list
2271 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002272 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002273 if (identifier.name == item) {
Chris Ye8594e192020-07-14 10:34:06 -07002274 ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002275 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002276 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002277 }
2278 }
2279
2280 // Get device driver version.
2281 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002282 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Chris Ye8594e192020-07-14 10:34:06 -07002283 ALOGE("could not get driver version for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002284 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002285 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002286 }
2287
2288 // Get device identifier.
2289 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002290 if (ioctl(fd, EVIOCGID, &inputId)) {
Chris Ye8594e192020-07-14 10:34:06 -07002291 ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002292 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002293 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002294 }
2295 identifier.bus = inputId.bustype;
2296 identifier.product = inputId.product;
2297 identifier.vendor = inputId.vendor;
2298 identifier.version = inputId.version;
2299
2300 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002301 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
2302 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002303 } else {
2304 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002305 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002306 }
2307
2308 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002309 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
2310 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002311 } else {
2312 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002313 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002314 }
2315
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002316 // Attempt to get the bluetooth address of an input device from the uniqueId.
2317 if (identifier.bus == BUS_BLUETOOTH &&
2318 std::regex_match(identifier.uniqueId,
2319 std::regex("^[A-Fa-f0-9]{2}(?::[A-Fa-f0-9]{2}){5}$"))) {
2320 identifier.bluetoothAddress = identifier.uniqueId;
2321 // The Bluetooth stack requires alphabetic characters to be uppercase in a valid address.
2322 for (auto& c : *identifier.bluetoothAddress) {
2323 c = ::toupper(c);
2324 }
2325 }
2326
Michael Wrightd02c5b62014-02-10 15:10:22 -08002327 // Fill in the descriptor.
2328 assignDescriptorLocked(identifier);
2329
Michael Wrightd02c5b62014-02-10 15:10:22 -08002330 // Allocate device. (The device object takes ownership of the fd at this point.)
2331 int32_t deviceId = mNextDeviceId++;
Prabir Pradhancb42b472022-08-23 16:01:19 +00002332 std::unique_ptr<Device> device =
2333 std::make_unique<Device>(fd, deviceId, devicePath, identifier,
2334 obtainAssociatedDeviceLocked(devicePath));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002335
Chris Ye8594e192020-07-14 10:34:06 -07002336 ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002337 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002338 " vendor %04x\n"
2339 " product %04x\n"
2340 " version %04x\n",
2341 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002342 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
2343 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
2344 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
2345 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002346 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
2347 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002348
2349 // Load the configuration file for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002350 device->loadConfigurationLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002351
2352 // Figure out the kinds of events the device reports.
Chris Ye66fbac32020-07-06 20:36:43 -07002353 device->readDeviceBitMask(EVIOCGBIT(EV_KEY, 0), device->keyBitmask);
2354 device->readDeviceBitMask(EVIOCGBIT(EV_ABS, 0), device->absBitmask);
2355 device->readDeviceBitMask(EVIOCGBIT(EV_REL, 0), device->relBitmask);
2356 device->readDeviceBitMask(EVIOCGBIT(EV_SW, 0), device->swBitmask);
2357 device->readDeviceBitMask(EVIOCGBIT(EV_LED, 0), device->ledBitmask);
2358 device->readDeviceBitMask(EVIOCGBIT(EV_FF, 0), device->ffBitmask);
Chris Yef59a2f42020-10-16 12:55:26 -07002359 device->readDeviceBitMask(EVIOCGBIT(EV_MSC, 0), device->mscBitmask);
Chris Ye66fbac32020-07-06 20:36:43 -07002360 device->readDeviceBitMask(EVIOCGPROP(0), device->propBitmask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002361
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002362 // See if this is a device with keys. This could be full keyboard, or other devices like
2363 // gamepads, joysticks, and styluses with buttons that should generate key presses.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002364 bool haveKeyboardKeys =
Chris Ye66fbac32020-07-06 20:36:43 -07002365 device->keyBitmask.any(0, BTN_MISC) || device->keyBitmask.any(BTN_WHEEL, KEY_MAX + 1);
2366 bool haveGamepadButtons = device->keyBitmask.any(BTN_MISC, BTN_MOUSE) ||
2367 device->keyBitmask.any(BTN_JOYSTICK, BTN_DIGI);
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002368 bool haveStylusButtons = device->keyBitmask.test(BTN_STYLUS) ||
2369 device->keyBitmask.test(BTN_STYLUS2) || device->keyBitmask.test(BTN_STYLUS3);
2370 if (haveKeyboardKeys || haveGamepadButtons || haveStylusButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002371 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002372 }
2373
2374 // See if this is a cursor device such as a trackball or mouse.
Chris Ye66fbac32020-07-06 20:36:43 -07002375 if (device->keyBitmask.test(BTN_MOUSE) && device->relBitmask.test(REL_X) &&
2376 device->relBitmask.test(REL_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002377 device->classes |= InputDeviceClass::CURSOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002378 }
2379
Prabir Pradhana3621852022-10-14 18:57:23 +00002380 // See if the device is specially configured to be of a certain type.
Harry Cuttsf13161a2023-03-08 14:15:49 +00002381 if (device->configuration) {
2382 std::string deviceType = device->configuration->getString("device.type").value_or("");
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07002383 if (deviceType == "rotaryEncoder") {
Chris Ye1b0c7342020-07-28 21:57:03 -07002384 device->classes |= InputDeviceClass::ROTARY_ENCODER;
Prabir Pradhana3621852022-10-14 18:57:23 +00002385 } else if (deviceType == "externalStylus") {
2386 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002387 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002388 }
2389
Michael Wrightd02c5b62014-02-10 15:10:22 -08002390 // See if this is a touch pad.
2391 // Is this a new modern multi-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002392 if (device->absBitmask.test(ABS_MT_POSITION_X) && device->absBitmask.test(ABS_MT_POSITION_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002393 // Some joysticks such as the PS3 controller report axes that conflict
2394 // with the ABS_MT range. Try to confirm that the device really is
2395 // a touch screen.
Chris Ye66fbac32020-07-06 20:36:43 -07002396 if (device->keyBitmask.test(BTN_TOUCH) || !haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002397 device->classes |= (InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT);
Harry Cutts79cc9fa2022-10-28 15:32:39 +00002398 if (device->propBitmask.test(INPUT_PROP_POINTER) &&
2399 !device->keyBitmask.any(BTN_TOOL_PEN, BTN_TOOL_FINGER) && !haveStylusButtons) {
2400 device->classes |= InputDeviceClass::TOUCHPAD;
2401 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002402 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002403 // Is this an old style single-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002404 } else if (device->keyBitmask.test(BTN_TOUCH) && device->absBitmask.test(ABS_X) &&
2405 device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002406 device->classes |= InputDeviceClass::TOUCH;
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002407 // Is this a stylus that reports contact/pressure independently of touch coordinates?
Chris Ye66fbac32020-07-06 20:36:43 -07002408 } else if ((device->absBitmask.test(ABS_PRESSURE) || device->keyBitmask.test(BTN_TOUCH)) &&
2409 !device->absBitmask.test(ABS_X) && !device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002410 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002411 }
2412
2413 // See if this device is a joystick.
2414 // Assumes that joysticks always have gamepad buttons in order to distinguish them
2415 // from other devices such as accelerometers that also have absolute axes.
2416 if (haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002417 auto assumedClasses = device->classes | InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002418 for (int i = 0; i <= ABS_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002419 if (device->absBitmask.test(i) &&
Chris Ye1b0c7342020-07-28 21:57:03 -07002420 (getAbsAxisUsage(i, assumedClasses).test(InputDeviceClass::JOYSTICK))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002421 device->classes = assumedClasses;
2422 break;
2423 }
2424 }
2425 }
2426
Chris Yef59a2f42020-10-16 12:55:26 -07002427 // Check whether this device is an accelerometer.
2428 if (device->propBitmask.test(INPUT_PROP_ACCELEROMETER)) {
2429 device->classes |= InputDeviceClass::SENSOR;
2430 }
2431
Michael Wrightd02c5b62014-02-10 15:10:22 -08002432 // Check whether this device has switches.
2433 for (int i = 0; i <= SW_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002434 if (device->swBitmask.test(i)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002435 device->classes |= InputDeviceClass::SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002436 break;
2437 }
2438 }
2439
2440 // Check whether this device supports the vibrator.
Chris Ye66fbac32020-07-06 20:36:43 -07002441 if (device->ffBitmask.test(FF_RUMBLE)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002442 device->classes |= InputDeviceClass::VIBRATOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002443 }
2444
2445 // Configure virtual keys.
Chris Ye1b0c7342020-07-28 21:57:03 -07002446 if ((device->classes.test(InputDeviceClass::TOUCH))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002447 // Load the virtual keys for the touch screen, if any.
2448 // We do this now so that we can make sure to load the keymap if necessary.
Chris Ye989bb932020-07-04 16:18:59 -07002449 bool success = device->loadVirtualKeyMapLocked();
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06002450 if (success) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002451 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002452 }
2453 }
2454
2455 // Load the key map.
Chris Yef59a2f42020-10-16 12:55:26 -07002456 // We need to do this for joysticks too because the key layout may specify axes, and for
2457 // sensor as well because the key layout may specify the axes to sensor data mapping.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002458 status_t keyMapStatus = NAME_NOT_FOUND;
Chris Yef59a2f42020-10-16 12:55:26 -07002459 if (device->classes.any(InputDeviceClass::KEYBOARD | InputDeviceClass::JOYSTICK |
2460 InputDeviceClass::SENSOR)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002461 // Load the keymap for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002462 keyMapStatus = device->loadKeyMapLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002463 }
2464
2465 // Configure the keyboard, gamepad or virtual keyboard.
Chris Ye1b0c7342020-07-28 21:57:03 -07002466 if (device->classes.test(InputDeviceClass::KEYBOARD)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002467 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002468 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002469 isEligibleBuiltInKeyboard(device->identifier, device->configuration.get(),
2470 &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002471 mBuiltInKeyboardId = device->id;
2472 }
2473
2474 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
Chris Ye989bb932020-07-04 16:18:59 -07002475 if (device->hasKeycodeLocked(AKEYCODE_Q)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002476 device->classes |= InputDeviceClass::ALPHAKEY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002477 }
2478
Prabir Pradhanae10ee62023-05-12 19:44:18 +00002479 // See if this device has a D-pad.
2480 if (std::all_of(DPAD_REQUIRED_KEYCODES.begin(), DPAD_REQUIRED_KEYCODES.end(),
2481 [&](int32_t keycode) { return device->hasKeycodeLocked(keycode); })) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002482 device->classes |= InputDeviceClass::DPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002483 }
2484
2485 // See if this device has a gamepad.
Prabir Pradhanae10ee62023-05-12 19:44:18 +00002486 if (std::any_of(GAMEPAD_KEYCODES.begin(), GAMEPAD_KEYCODES.end(),
2487 [&](int32_t keycode) { return device->hasKeycodeLocked(keycode); })) {
2488 device->classes |= InputDeviceClass::GAMEPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002489 }
Prabir Pradhana3621852022-10-14 18:57:23 +00002490
2491 // See if this device has any stylus buttons that we would want to fuse with touch data.
Prabir Pradhanae10ee62023-05-12 19:44:18 +00002492 if (!device->classes.any(InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT) &&
Prabir Pradhan3c28b942023-08-18 20:02:01 +00002493 !device->classes.any(InputDeviceClass::ALPHAKEY) &&
Prabir Pradhanae10ee62023-05-12 19:44:18 +00002494 std::any_of(STYLUS_BUTTON_KEYCODES.begin(), STYLUS_BUTTON_KEYCODES.end(),
2495 [&](int32_t keycode) { return device->hasKeycodeLocked(keycode); })) {
2496 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Prabir Pradhana3621852022-10-14 18:57:23 +00002497 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002498 }
2499
2500 // If the device isn't recognized as something we handle, don't monitor it.
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002501 if (device->classes == ftl::Flags<InputDeviceClass>(0)) {
Chris Ye8594e192020-07-14 10:34:06 -07002502 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002503 device->identifier.name.c_str());
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002504 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002505 }
2506
Chris Ye3fdbfef2021-01-06 18:45:18 -08002507 // Classify InputDeviceClass::BATTERY.
Prabir Pradhan51894782022-08-23 16:29:10 +00002508 if (device->associatedDevice && !device->associatedDevice->batteryInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002509 device->classes |= InputDeviceClass::BATTERY;
2510 }
Kim Low03ea0352020-11-06 12:45:07 -08002511
Chris Ye3fdbfef2021-01-06 18:45:18 -08002512 // Classify InputDeviceClass::LIGHT.
Prabir Pradhan51894782022-08-23 16:29:10 +00002513 if (device->associatedDevice && !device->associatedDevice->lightInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002514 device->classes |= InputDeviceClass::LIGHT;
Kim Low03ea0352020-11-06 12:45:07 -08002515 }
2516
Tim Kilbourn063ff532015-04-08 10:26:18 -07002517 // Determine whether the device has a mic.
Chris Ye989bb932020-07-04 16:18:59 -07002518 if (device->deviceHasMicLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002519 device->classes |= InputDeviceClass::MIC;
Tim Kilbourn063ff532015-04-08 10:26:18 -07002520 }
2521
Michael Wrightd02c5b62014-02-10 15:10:22 -08002522 // Determine whether the device is external or internal.
Chris Ye989bb932020-07-04 16:18:59 -07002523 if (device->isExternalDeviceLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002524 device->classes |= InputDeviceClass::EXTERNAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002525 }
2526
Chris Ye1b0c7342020-07-28 21:57:03 -07002527 if (device->classes.any(InputDeviceClass::JOYSTICK | InputDeviceClass::DPAD) &&
2528 device->classes.test(InputDeviceClass::GAMEPAD)) {
Chris Ye989bb932020-07-04 16:18:59 -07002529 device->controllerNumber = getNextControllerNumberLocked(device->identifier.name);
2530 device->setLedForControllerLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002531 }
2532
Chris Ye989bb932020-07-04 16:18:59 -07002533 if (registerDeviceForEpollLocked(*device) != OK) {
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002534 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002535 }
2536
Chris Ye989bb932020-07-04 16:18:59 -07002537 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002538
Chris Ye1b0c7342020-07-28 21:57:03 -07002539 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=%s, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002540 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Chris Ye1b0c7342020-07-28 21:57:03 -07002541 deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(),
2542 device->classes.string().c_str(), device->configurationFile.c_str(),
2543 device->keyMap.keyLayoutFile.c_str(), device->keyMap.keyCharacterMapFile.c_str(),
2544 toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002545
Chris Ye989bb932020-07-04 16:18:59 -07002546 addDeviceLocked(std::move(device));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002547}
2548
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002549void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
2550 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
2551 if (!videoDevice) {
2552 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
2553 return;
2554 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002555 // Transfer ownership of this video device to a matching input device
Chris Ye989bb932020-07-04 16:18:59 -07002556 for (const auto& [id, device] : mDevices) {
Chris Yed3fef462021-03-07 17:10:08 -08002557 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002558 return; // 'device' now owns 'videoDevice'
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002559 }
2560 }
2561
2562 // Couldn't find a matching input device, so just add it to a temporary holding queue.
2563 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002564 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002565 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002566 mUnattachedVideoDevices.push_back(std::move(videoDevice));
2567}
2568
Chris Yed3fef462021-03-07 17:10:08 -08002569bool EventHub::tryAddVideoDeviceLocked(EventHub::Device& device,
2570 std::unique_ptr<TouchVideoDevice>& videoDevice) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002571 if (videoDevice->getName() != device.identifier.name) {
2572 return false;
2573 }
2574 device.videoDevice = std::move(videoDevice);
2575 if (device.enabled) {
2576 registerVideoDeviceForEpollLocked(*device.videoDevice);
2577 }
2578 return true;
2579}
2580
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002581bool EventHub::isDeviceEnabled(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00002582 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002583 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002584 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002585 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2586 return false;
2587 }
2588 return device->enabled;
2589}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002590
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002591status_t EventHub::enableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002592 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002593 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002594 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002595 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2596 return BAD_VALUE;
2597 }
2598 if (device->enabled) {
2599 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
2600 return OK;
2601 }
2602 status_t result = device->enable();
2603 if (result != OK) {
2604 ALOGE("Failed to enable device %" PRId32, deviceId);
2605 return result;
2606 }
2607
Chris Ye989bb932020-07-04 16:18:59 -07002608 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002609
Chris Ye989bb932020-07-04 16:18:59 -07002610 return registerDeviceForEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002611}
2612
2613status_t EventHub::disableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002614 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002615 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002616 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002617 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2618 return BAD_VALUE;
2619 }
2620 if (!device->enabled) {
2621 ALOGW("Duplicate call to %s, input device already disabled", __func__);
2622 return OK;
2623 }
Chris Ye989bb932020-07-04 16:18:59 -07002624 unregisterDeviceFromEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002625 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002626}
2627
Vaibhav Devmurari5fc7d852023-03-17 18:43:33 +00002628// TODO(b/274755573): Shift to uevent handling on native side and remove this method
2629// Currently using Java UEventObserver to trigger this which uses UEvent infrastructure that uses a
2630// NETLINK socket to observe UEvents. We can create similar infrastructure on Eventhub side to
2631// directly observe UEvents instead of triggering from Java side.
2632void EventHub::sysfsNodeChanged(const std::string& sysfsNodePath) {
2633 std::scoped_lock _l(mLock);
2634
2635 // Check in opening devices
2636 for (auto it = mOpeningDevices.begin(); it != mOpeningDevices.end(); it++) {
2637 std::unique_ptr<Device>& device = *it;
2638 if (device->associatedDevice &&
2639 sysfsNodePath.find(device->associatedDevice->sysfsRootPath.string()) !=
2640 std::string::npos &&
2641 device->associatedDevice->isChanged()) {
2642 it = mOpeningDevices.erase(it);
2643 openDeviceLocked(device->path);
2644 }
2645 }
2646
2647 // Check in already added device
2648 std::vector<Device*> devicesToReopen;
2649 for (const auto& [id, device] : mDevices) {
2650 if (device->associatedDevice &&
2651 sysfsNodePath.find(device->associatedDevice->sysfsRootPath.string()) !=
2652 std::string::npos &&
2653 device->associatedDevice->isChanged()) {
2654 devicesToReopen.push_back(device.get());
2655 }
2656 }
2657 for (const auto& device : devicesToReopen) {
2658 closeDeviceLocked(*device);
2659 openDeviceLocked(device->path);
2660 }
2661 devicesToReopen.clear();
2662}
2663
Michael Wrightd02c5b62014-02-10 15:10:22 -08002664void EventHub::createVirtualKeyboardLocked() {
2665 InputDeviceIdentifier identifier;
2666 identifier.name = "Virtual";
2667 identifier.uniqueId = "<virtual>";
2668 assignDescriptorLocked(identifier);
2669
Chris Ye989bb932020-07-04 16:18:59 -07002670 std::unique_ptr<Device> device =
2671 std::make_unique<Device>(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
Harry Cutts33476232023-01-30 19:57:29 +00002672 identifier, /*associatedDevice=*/nullptr);
Chris Ye1b0c7342020-07-28 21:57:03 -07002673 device->classes = InputDeviceClass::KEYBOARD | InputDeviceClass::ALPHAKEY |
2674 InputDeviceClass::DPAD | InputDeviceClass::VIRTUAL;
Chris Ye989bb932020-07-04 16:18:59 -07002675 device->loadKeyMapLocked();
2676 addDeviceLocked(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002677}
2678
Chris Ye989bb932020-07-04 16:18:59 -07002679void EventHub::addDeviceLocked(std::unique_ptr<Device> device) {
Chris Yed3fef462021-03-07 17:10:08 -08002680 reportDeviceAddedForStatisticsLocked(device->identifier, device->classes);
Chris Ye989bb932020-07-04 16:18:59 -07002681 mOpeningDevices.push_back(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002682}
2683
Chris Ye989bb932020-07-04 16:18:59 -07002684int32_t EventHub::getNextControllerNumberLocked(const std::string& name) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002685 if (mControllerNumbers.isFull()) {
2686 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Chris Ye989bb932020-07-04 16:18:59 -07002687 name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002688 return 0;
2689 }
2690 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
2691 // one
2692 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
2693}
2694
Chris Ye989bb932020-07-04 16:18:59 -07002695void EventHub::releaseControllerNumberLocked(int32_t num) {
2696 if (num > 0) {
2697 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002698 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002699}
2700
Chris Ye8594e192020-07-14 10:34:06 -07002701void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002702 Device* device = getDeviceByPathLocked(devicePath);
Chris Ye989bb932020-07-04 16:18:59 -07002703 if (device != nullptr) {
2704 closeDeviceLocked(*device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002705 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002706 }
Chris Ye8594e192020-07-14 10:34:06 -07002707 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002708}
2709
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002710/**
2711 * Find the video device by filename, and close it.
2712 * The video device is closed by path during an inotify event, where we don't have the
2713 * additional context about the video device fd, or the associated input device.
2714 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002715void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002716 // A video device may be owned by an existing input device, or it may be stored in
2717 // the mUnattachedVideoDevices queue. Check both locations.
Chris Ye989bb932020-07-04 16:18:59 -07002718 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002719 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002720 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002721 device->videoDevice = nullptr;
2722 return;
2723 }
2724 }
Siarhei Vishniakouf47c339e2021-12-30 11:22:26 -08002725 std::erase_if(mUnattachedVideoDevices,
2726 [&devicePath](const std::unique_ptr<TouchVideoDevice>& videoDevice) {
2727 return videoDevice->getPath() == devicePath;
2728 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08002729}
2730
2731void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002732 mUnattachedVideoDevices.clear();
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002733 while (!mDevices.empty()) {
2734 closeDeviceLocked(*(mDevices.begin()->second));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002735 }
2736}
2737
Chris Ye989bb932020-07-04 16:18:59 -07002738void EventHub::closeDeviceLocked(Device& device) {
2739 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=%s", device.path.c_str(),
2740 device.identifier.name.c_str(), device.id, device.fd, device.classes.string().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002741
Chris Ye989bb932020-07-04 16:18:59 -07002742 if (device.id == mBuiltInKeyboardId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002743 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Chris Ye989bb932020-07-04 16:18:59 -07002744 device.path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002745 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
2746 }
2747
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002748 unregisterDeviceFromEpollLocked(device);
Chris Ye989bb932020-07-04 16:18:59 -07002749 if (device.videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002750 // This must be done after the video device is removed from epoll
Chris Ye989bb932020-07-04 16:18:59 -07002751 mUnattachedVideoDevices.push_back(std::move(device.videoDevice));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002752 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002753
Chris Ye989bb932020-07-04 16:18:59 -07002754 releaseControllerNumberLocked(device.controllerNumber);
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002755 device.controllerNumber = 0;
Chris Ye989bb932020-07-04 16:18:59 -07002756 device.close();
Chris Ye989bb932020-07-04 16:18:59 -07002757 mClosingDevices.push_back(std::move(mDevices[device.id]));
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002758
Chris Ye989bb932020-07-04 16:18:59 -07002759 mDevices.erase(device.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002760}
2761
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002762base::Result<void> EventHub::readNotifyLocked() {
2763 static constexpr auto EVENT_SIZE = static_cast<ssize_t>(sizeof(inotify_event));
2764 uint8_t eventBuffer[512];
2765 ssize_t sizeRead;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002766
2767 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002768 do {
2769 sizeRead = read(mINotifyFd, eventBuffer, sizeof(eventBuffer));
2770 } while (sizeRead < 0 && errno == EINTR);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002771
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002772 if (sizeRead < EVENT_SIZE) return Errorf("could not get event, %s", strerror(errno));
2773
2774 for (ssize_t eventPos = 0; sizeRead >= EVENT_SIZE;) {
2775 const inotify_event* event;
2776 event = (const inotify_event*)(eventBuffer + eventPos);
2777 if (event->len == 0) continue;
2778
2779 handleNotifyEventLocked(*event);
2780
2781 const ssize_t eventSize = EVENT_SIZE + event->len;
2782 sizeRead -= eventSize;
2783 eventPos += eventSize;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002784 }
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002785 return {};
2786}
2787
2788void EventHub::handleNotifyEventLocked(const inotify_event& event) {
2789 if (event.wd == mDeviceInputWd) {
2790 std::string filename = std::string(DEVICE_INPUT_PATH) + "/" + event.name;
2791 if (event.mask & IN_CREATE) {
2792 openDeviceLocked(filename);
2793 } else {
2794 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
2795 closeDeviceByPathLocked(filename);
2796 }
2797 } else if (event.wd == mDeviceWd) {
2798 if (isV4lTouchNode(event.name)) {
2799 std::string filename = std::string(DEVICE_PATH) + "/" + event.name;
2800 if (event.mask & IN_CREATE) {
2801 openVideoDeviceLocked(filename);
2802 } else {
2803 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
2804 closeVideoDeviceByPathLocked(filename);
2805 }
2806 } else if (strcmp(event.name, "input") == 0 && event.mask & IN_CREATE) {
2807 addDeviceInputInotify();
2808 }
2809 } else {
2810 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event.wd);
2811 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002812}
2813
Chris Ye8594e192020-07-14 10:34:06 -07002814status_t EventHub::scanDirLocked(const std::string& dirname) {
2815 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2816 openDeviceLocked(entry.path());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002817 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002818 return 0;
2819}
2820
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002821/**
2822 * Look for all dirname/v4l-touch* devices, and open them.
2823 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002824status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Chris Ye8594e192020-07-14 10:34:06 -07002825 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2826 if (isV4lTouchNode(entry.path())) {
2827 ALOGI("Found touch video device %s", entry.path().c_str());
2828 openVideoDeviceLocked(entry.path());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002829 }
2830 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002831 return OK;
2832}
2833
Michael Wrightd02c5b62014-02-10 15:10:22 -08002834void EventHub::requestReopenDevices() {
2835 ALOGV("requestReopenDevices() called");
2836
Chris Ye87143712020-11-10 05:05:58 +00002837 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002838 mNeedToReopenDevices = true;
2839}
2840
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002841void EventHub::dump(std::string& dump) const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002842 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002843
2844 { // acquire lock
Chris Ye87143712020-11-10 05:05:58 +00002845 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002846
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002847 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002848
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002849 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002850
Chris Ye989bb932020-07-04 16:18:59 -07002851 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002852 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002853 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002854 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002855 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002856 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002857 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002858 }
Chris Ye1b0c7342020-07-28 21:57:03 -07002859 dump += StringPrintf(INDENT3 "Classes: %s\n", device->classes.string().c_str());
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002860 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002861 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002862 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
2863 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002864 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002865 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002866 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002867 "product=0x%04x, version=0x%04x, bluetoothAddress=%s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002868 device->identifier.bus, device->identifier.vendor,
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002869 device->identifier.product, device->identifier.version,
2870 toString(device->identifier.bluetoothAddress).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002871 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002872 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002873 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002874 device->keyMap.keyCharacterMapFile.c_str());
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00002875 if (device->associatedDevice && device->associatedDevice->layoutInfo) {
2876 dump += StringPrintf(INDENT3 "LanguageTag: %s\n",
2877 device->associatedDevice->layoutInfo->languageTag.c_str());
2878 dump += StringPrintf(INDENT3 "LayoutType: %s\n",
2879 device->associatedDevice->layoutInfo->layoutType.c_str());
2880 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002881 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002882 device->configurationFile.c_str());
Prabir Pradhan51894782022-08-23 16:29:10 +00002883 dump += StringPrintf(INDENT3 "VideoDevice: %s\n",
2884 device->videoDevice ? device->videoDevice->dump().c_str()
2885 : "<none>");
2886 dump += StringPrintf(INDENT3 "SysfsDevicePath: %s\n",
2887 device->associatedDevice
2888 ? device->associatedDevice->sysfsRootPath.c_str()
2889 : "<none>");
Prabir Pradhan955b6132023-07-14 19:44:34 +00002890 if (device->keyBitmask.any(0, KEY_MAX + 1)) {
2891 const auto pressedKeys = device->keyState.dumpSetIndices(", ", [](int i) {
2892 return InputEventLookup::getLinuxEvdevLabel(EV_KEY, i, 1).code;
2893 });
2894 dump += StringPrintf(INDENT3 "KeyState (pressed): %s\n", pressedKeys.c_str());
2895 }
2896 if (device->swBitmask.any(0, SW_MAX + 1)) {
2897 const auto pressedSwitches = device->swState.dumpSetIndices(", ", [](int i) {
2898 return InputEventLookup::getLinuxEvdevLabel(EV_SW, i, 1).code;
2899 });
2900 dump += StringPrintf(INDENT3 "SwState (pressed): %s\n", pressedSwitches.c_str());
2901 }
2902 if (!device->absState.empty()) {
2903 std::string axisValues;
2904 for (const auto& [axis, state] : device->absState) {
2905 if (!axisValues.empty()) {
2906 axisValues += ", ";
2907 }
2908 axisValues += StringPrintf("%s=%d",
2909 InputEventLookup::getLinuxEvdevLabel(EV_ABS, axis, 0)
2910 .code.c_str(),
2911 state.value);
2912 }
2913 dump += INDENT3 "AbsState: " + axisValues + "\n";
2914 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002915 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002916
2917 dump += INDENT "Unattached video devices:\n";
2918 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
2919 dump += INDENT2 + videoDevice->dump() + "\n";
2920 }
2921 if (mUnattachedVideoDevices.empty()) {
2922 dump += INDENT2 "<none>\n";
2923 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002924 } // release lock
2925}
2926
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002927void EventHub::monitor() const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002928 // Acquire and release the lock to ensure that the event hub has not deadlocked.
Chris Ye1c2e0892020-11-30 21:41:44 -08002929 std::unique_lock<std::mutex> lock(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002930}
2931
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00002932std::string EventHub::AssociatedDevice::dump() const {
2933 return StringPrintf("path=%s, numBatteries=%zu, numLight=%zu", sysfsRootPath.c_str(),
2934 batteryInfos.size(), lightInfos.size());
2935}
2936
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002937} // namespace android