blob: 65583e95bf62cc4e254bec3e129704c9e41a8577 [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
516std::ostream& operator<<(std::ostream& out, const RawAbsoluteAxisInfo& info) {
517 if (info.valid) {
518 out << "min=" << info.minValue << ", max=" << info.maxValue << ", flat=" << info.flat
519 << ", fuzz=" << info.fuzz << ", resolution=" << info.resolution;
520 } 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];
648 axisInfo.valid = true;
649 axisInfo.minValue = info.minimum;
650 axisInfo.maxValue = info.maximum;
651 axisInfo.flat = info.flat;
652 axisInfo.fuzz = info.fuzz;
653 axisInfo.resolution = info.resolution;
654 value = info.value;
655 }
Chris Ye989bb932020-07-04 16:18:59 -0700656}
657
658bool EventHub::Device::hasKeycodeLocked(int keycode) const {
659 if (!keyMap.haveKeyLayout()) {
660 return false;
661 }
662
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700663 std::vector<int32_t> scanCodes = keyMap.keyLayoutMap->findScanCodesForKey(keycode);
Chris Ye989bb932020-07-04 16:18:59 -0700664 const size_t N = scanCodes.size();
665 for (size_t i = 0; i < N && i <= KEY_MAX; i++) {
666 int32_t sc = scanCodes[i];
667 if (sc >= 0 && sc <= KEY_MAX && keyBitmask.test(sc)) {
668 return true;
669 }
670 }
671
Charles Linaadf8d52023-03-30 13:34:54 +0800672 std::vector<int32_t> usageCodes = keyMap.keyLayoutMap->findUsageCodesForKey(keycode);
673 if (usageCodes.size() > 0 && mscBitmask.test(MSC_SCAN)) {
674 return true;
675 }
676
Chris Ye989bb932020-07-04 16:18:59 -0700677 return false;
678}
679
680void EventHub::Device::loadConfigurationLocked() {
681 configurationFile =
682 getInputDeviceConfigurationFilePathByDeviceIdentifier(identifier,
683 InputDeviceConfigurationFileType::
684 CONFIGURATION);
685 if (configurationFile.empty()) {
686 ALOGD("No input device configuration file found for device '%s'.", identifier.name.c_str());
687 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500688 android::base::Result<std::unique_ptr<PropertyMap>> propertyMap =
689 PropertyMap::load(configurationFile.c_str());
690 if (!propertyMap.ok()) {
Chris Ye989bb932020-07-04 16:18:59 -0700691 ALOGE("Error loading input device configuration file for device '%s'. "
692 "Using default configuration.",
693 identifier.name.c_str());
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500694 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500695 configuration = std::move(*propertyMap);
Chris Ye989bb932020-07-04 16:18:59 -0700696 }
697 }
698}
699
700bool EventHub::Device::loadVirtualKeyMapLocked() {
701 // The virtual key map is supplied by the kernel as a system board property file.
702 std::string propPath = "/sys/board_properties/virtualkeys.";
703 propPath += identifier.getCanonicalName();
704 if (access(propPath.c_str(), R_OK)) {
705 return false;
706 }
707 virtualKeyMap = VirtualKeyMap::load(propPath);
708 return virtualKeyMap != nullptr;
709}
710
711status_t EventHub::Device::loadKeyMapLocked() {
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500712 return keyMap.load(identifier, configuration.get());
Chris Ye989bb932020-07-04 16:18:59 -0700713}
714
715bool EventHub::Device::isExternalDeviceLocked() {
716 if (configuration) {
Harry Cuttsf13161a2023-03-08 14:15:49 +0000717 std::optional<bool> isInternal = configuration->getBool("device.internal");
718 if (isInternal.has_value()) {
719 return !isInternal.value();
Chris Ye989bb932020-07-04 16:18:59 -0700720 }
721 }
722 return identifier.bus == BUS_USB || identifier.bus == BUS_BLUETOOTH;
723}
724
725bool EventHub::Device::deviceHasMicLocked() {
726 if (configuration) {
Harry Cuttsf13161a2023-03-08 14:15:49 +0000727 std::optional<bool> hasMic = configuration->getBool("audio.mic");
728 if (hasMic.has_value()) {
729 return hasMic.value();
Chris Ye989bb932020-07-04 16:18:59 -0700730 }
731 }
732 return false;
733}
734
735void EventHub::Device::setLedStateLocked(int32_t led, bool on) {
736 int32_t sc;
737 if (hasValidFd() && mapLed(led, &sc) != NAME_NOT_FOUND) {
738 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -0700739 ev.input_event_sec = 0;
740 ev.input_event_usec = 0;
Chris Ye989bb932020-07-04 16:18:59 -0700741 ev.type = EV_LED;
742 ev.code = sc;
743 ev.value = on ? 1 : 0;
744
745 ssize_t nWrite;
746 do {
747 nWrite = write(fd, &ev, sizeof(struct input_event));
748 } while (nWrite == -1 && errno == EINTR);
749 }
750}
751
752void EventHub::Device::setLedForControllerLocked() {
753 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
754 setLedStateLocked(ALED_CONTROLLER_1 + i, controllerNumber == i + 1);
755 }
756}
757
758status_t EventHub::Device::mapLed(int32_t led, int32_t* outScanCode) const {
759 if (!keyMap.haveKeyLayout()) {
760 return NAME_NOT_FOUND;
761 }
762
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700763 std::optional<int32_t> scanCode = keyMap.keyLayoutMap->findScanCodeForLed(led);
764 if (scanCode.has_value()) {
765 if (*scanCode >= 0 && *scanCode <= LED_MAX && ledBitmask.test(*scanCode)) {
766 *outScanCode = *scanCode;
Chris Ye989bb932020-07-04 16:18:59 -0700767 return NO_ERROR;
768 }
769 }
770 return NAME_NOT_FOUND;
771}
772
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000773void EventHub::Device::trackInputEvent(const struct input_event& event) {
774 switch (event.type) {
775 case EV_KEY: {
776 LOG_ALWAYS_FATAL_IF(!currentFrameDropped &&
777 !keyState.set(static_cast<size_t>(event.code),
778 event.value != 0),
Prabir Pradhan10301422023-07-26 21:48:30 +0000779 "%s: device '%s' received invalid EV_KEY event code: %s value: %d",
780 __func__, identifier.name.c_str(),
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000781 InputEventLookup::getLinuxEvdevLabel(EV_KEY, event.code, 1)
Prabir Pradhan10301422023-07-26 21:48:30 +0000782 .code.c_str(),
783 event.value);
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000784 break;
785 }
786 case EV_SW: {
787 LOG_ALWAYS_FATAL_IF(!currentFrameDropped &&
788 !swState.set(static_cast<size_t>(event.code),
789 event.value != 0),
Prabir Pradhan10301422023-07-26 21:48:30 +0000790 "%s: device '%s' received invalid EV_SW event code: %s value: %d",
791 __func__, identifier.name.c_str(),
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000792 InputEventLookup::getLinuxEvdevLabel(EV_SW, event.code, 1)
Prabir Pradhan10301422023-07-26 21:48:30 +0000793 .code.c_str(),
794 event.value);
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000795 break;
796 }
Prabir Pradhan341d0782023-07-14 19:04:10 +0000797 case EV_ABS: {
Prabir Pradhan10301422023-07-26 21:48:30 +0000798 if (currentFrameDropped) {
799 break;
800 }
Prabir Pradhan341d0782023-07-14 19:04:10 +0000801 auto it = absState.find(event.code);
Prabir Pradhan10301422023-07-26 21:48:30 +0000802 LOG_ALWAYS_FATAL_IF(it == absState.end(),
803 "%s: device '%s' received invalid EV_ABS event code: %s value: %d",
804 __func__, identifier.name.c_str(),
Prabir Pradhan341d0782023-07-14 19:04:10 +0000805 InputEventLookup::getLinuxEvdevLabel(EV_ABS, event.code, 0)
Prabir Pradhan10301422023-07-26 21:48:30 +0000806 .code.c_str(),
807 event.value);
Prabir Pradhan341d0782023-07-14 19:04:10 +0000808 it->second.value = event.value;
809 break;
810 }
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000811 case EV_SYN: {
812 switch (event.code) {
813 case SYN_REPORT:
Arpit Singh1c3d8552024-01-08 14:16:28 +0000814 if (currentFrameDropped) {
815 // To recover after a SYN_DROPPED, we need to query the state of the device
816 // to synchronize our device state with the kernel's to account for the
817 // dropped events on receiving the next SYN_REPORT.
818 // Note we don't drop the SYN_REPORT at this point but it is used by the
819 // InputDevice to reset and repopulate mapper state
820 readDeviceState();
821 currentFrameDropped = false;
822 }
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000823 break;
824 case SYN_DROPPED:
825 // When we receive SYN_DROPPED, all events in the current frame should be
Arpit Singh1c3d8552024-01-08 14:16:28 +0000826 // dropped up to and including next SYN_REPORT
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000827 currentFrameDropped = true;
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000828 break;
829 default:
830 break;
831 }
832 break;
833 }
834 default:
835 break;
836 }
837}
838
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100839/**
840 * Get the capabilities for the current process.
841 * Crashes the system if unable to create / check / destroy the capabilities object.
842 */
843class Capabilities final {
844public:
845 explicit Capabilities() {
846 mCaps = cap_get_proc();
847 LOG_ALWAYS_FATAL_IF(mCaps == nullptr, "Could not get capabilities of the current process");
848 }
849
850 /**
851 * Check whether the current process has a specific capability
852 * in the set of effective capabilities.
853 * Return CAP_SET if the process has the requested capability
854 * Return CAP_CLEAR otherwise.
855 */
856 cap_flag_value_t checkEffectiveCapability(cap_value_t capability) {
857 cap_flag_value_t value;
858 const int result = cap_get_flag(mCaps, capability, CAP_EFFECTIVE, &value);
859 LOG_ALWAYS_FATAL_IF(result == -1, "Could not obtain the requested capability");
860 return value;
861 }
862
863 ~Capabilities() {
864 const int result = cap_free(mCaps);
865 LOG_ALWAYS_FATAL_IF(result == -1, "Could not release the capabilities structure");
866 }
867
868private:
869 cap_t mCaps;
870};
871
872static void ensureProcessCanBlockSuspend() {
873 Capabilities capabilities;
874 const bool canBlockSuspend =
875 capabilities.checkEffectiveCapability(CAP_BLOCK_SUSPEND) == CAP_SET;
876 LOG_ALWAYS_FATAL_IF(!canBlockSuspend,
877 "Input must be able to block suspend to properly process events");
878}
879
Michael Wrightd02c5b62014-02-10 15:10:22 -0800880// --- EventHub ---
881
Michael Wrightd02c5b62014-02-10 15:10:22 -0800882const int EventHub::EPOLL_MAX_EVENTS;
883
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700884EventHub::EventHub(void)
885 : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
886 mNextDeviceId(1),
887 mControllerNumbers(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800888 mNeedToSendFinishedDeviceScan(false),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700889 mNeedToReopenDevices(false),
890 mNeedToScanDevices(true),
891 mPendingEventCount(0),
892 mPendingEventIndex(0),
893 mPendingINotify(false) {
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100894 ensureProcessCanBlockSuspend();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800895
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800896 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800897 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800898
Michael Wright8e9a8562022-02-09 13:44:29 +0000899 mINotifyFd = inotify_init1(IN_CLOEXEC);
Prabir Pradhan952e65b2022-06-23 17:49:55 +0000900 LOG_ALWAYS_FATAL_IF(mINotifyFd < 0, "Could not create inotify instance: %s", strerror(errno));
Usama Arifb27c8e62021-06-03 16:44:09 +0100901
902 std::error_code errorCode;
903 bool isDeviceInotifyAdded = false;
904 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
905 addDeviceInputInotify();
Philip Quinn39b81682019-01-09 22:20:39 -0800906 } else {
Usama Arifb27c8e62021-06-03 16:44:09 +0100907 addDeviceInotify();
908 isDeviceInotifyAdded = true;
909 if (errorCode) {
910 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
911 errorCode.message().c_str());
912 }
913 }
914
915 if (isV4lScanningEnabled() && !isDeviceInotifyAdded) {
916 addDeviceInotify();
917 } else {
Philip Quinn39b81682019-01-09 22:20:39 -0800918 ALOGI("Video device scanning disabled");
919 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800920
Siarhei Vishniakou2d0e9482019-09-24 12:52:47 +0100921 struct epoll_event eventItem = {};
922 eventItem.events = EPOLLIN | EPOLLWAKEUP;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700923 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800924 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800925 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
926
927 int wakeFds[2];
Michael Wright8e9a8562022-02-09 13:44:29 +0000928 result = pipe2(wakeFds, O_CLOEXEC);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800929 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
930
931 mWakeReadPipeFd = wakeFds[0];
932 mWakeWritePipeFd = wakeFds[1];
933
934 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
935 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700936 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800937
938 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
939 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700940 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800941
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700942 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800943 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
944 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700945 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800946}
947
948EventHub::~EventHub(void) {
949 closeAllDevicesLocked();
950
Michael Wrightd02c5b62014-02-10 15:10:22 -0800951 ::close(mEpollFd);
952 ::close(mINotifyFd);
953 ::close(mWakeReadPipeFd);
954 ::close(mWakeWritePipeFd);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800955}
956
Usama Arifb27c8e62021-06-03 16:44:09 +0100957/**
958 * On devices that don't have any input devices (like some development boards), the /dev/input
959 * directory will be absent. However, the user may still plug in an input device at a later time.
960 * Add watch for contents of /dev/input only when /dev/input appears.
961 */
962void EventHub::addDeviceInputInotify() {
963 mDeviceInputWd = inotify_add_watch(mINotifyFd, DEVICE_INPUT_PATH, IN_DELETE | IN_CREATE);
964 LOG_ALWAYS_FATAL_IF(mDeviceInputWd < 0, "Could not register INotify for %s: %s",
965 DEVICE_INPUT_PATH, strerror(errno));
966}
967
968void EventHub::addDeviceInotify() {
969 mDeviceWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
970 LOG_ALWAYS_FATAL_IF(mDeviceWd < 0, "Could not register INotify for %s: %s", DEVICE_PATH,
971 strerror(errno));
972}
973
Michael Wrightd02c5b62014-02-10 15:10:22 -0800974InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000975 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800976 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700977 return device != nullptr ? device->identifier : InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800978}
979
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700980ftl::Flags<InputDeviceClass> EventHub::getDeviceClasses(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000981 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800982 Device* device = getDeviceLocked(deviceId);
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700983 return device != nullptr ? device->classes : ftl::Flags<InputDeviceClass>(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800984}
985
986int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000987 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800988 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700989 return device != nullptr ? device->controllerNumber : 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800990}
991
Harry Cuttsc34f7582023-03-07 16:23:30 +0000992std::optional<PropertyMap> EventHub::getConfiguration(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000993 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800994 Device* device = getDeviceLocked(deviceId);
Harry Cuttsc34f7582023-03-07 16:23:30 +0000995 if (device == nullptr || device->configuration == nullptr) {
996 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -0800997 }
Harry Cuttsc34f7582023-03-07 16:23:30 +0000998 return *device->configuration;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800999}
1000
Harry Cutts207674d2024-06-06 18:53:41 +00001001std::optional<RawAbsoluteAxisInfo> EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis) const {
Arpit Singh77140f42023-06-13 11:35:27 +00001002 if (axis < 0 || axis > ABS_MAX) {
Harry Cutts207674d2024-06-06 18:53:41 +00001003 return std::nullopt;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001004 }
Arpit Singh77140f42023-06-13 11:35:27 +00001005 std::scoped_lock _l(mLock);
Prabir Pradhan341d0782023-07-14 19:04:10 +00001006 const Device* device = getDeviceLocked(deviceId);
Arpit Singh77140f42023-06-13 11:35:27 +00001007 if (device == nullptr) {
Harry Cutts207674d2024-06-06 18:53:41 +00001008 return std::nullopt;
Arpit Singh77140f42023-06-13 11:35:27 +00001009 }
Prabir Pradhan341d0782023-07-14 19:04:10 +00001010 // We can read the RawAbsoluteAxisInfo even if the device is disabled and doesn't have a valid
1011 // fd, because the info is populated once when the device is first opened, and it doesn't change
1012 // throughout the device lifecycle.
1013 auto it = device->absState.find(axis);
1014 if (it == device->absState.end()) {
Harry Cutts207674d2024-06-06 18:53:41 +00001015 return std::nullopt;
Arpit Singh77140f42023-06-13 11:35:27 +00001016 }
Harry Cutts207674d2024-06-06 18:53:41 +00001017 return it->second.info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001018}
1019
1020bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
1021 if (axis >= 0 && axis <= REL_MAX) {
Chris Ye87143712020-11-10 05:05:58 +00001022 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001023 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001024 return device != nullptr ? device->relBitmask.test(axis) : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001025 }
1026 return false;
1027}
1028
1029bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
Chris Ye87143712020-11-10 05:05:58 +00001030 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001031
Chris Ye989bb932020-07-04 16:18:59 -07001032 Device* device = getDeviceLocked(deviceId);
1033 return property >= 0 && property <= INPUT_PROP_MAX && device != nullptr
1034 ? device->propBitmask.test(property)
1035 : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001036}
1037
Chris Yef59a2f42020-10-16 12:55:26 -07001038bool EventHub::hasMscEvent(int32_t deviceId, int mscEvent) const {
1039 std::scoped_lock _l(mLock);
1040
1041 Device* device = getDeviceLocked(deviceId);
1042 return mscEvent >= 0 && mscEvent <= MSC_MAX && device != nullptr
1043 ? device->mscBitmask.test(mscEvent)
1044 : false;
1045}
1046
Michael Wrightd02c5b62014-02-10 15:10:22 -08001047int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001048 if (scanCode < 0 || scanCode > KEY_MAX) {
1049 return AKEY_STATE_UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001050 }
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001051 std::scoped_lock _l(mLock);
1052 const Device* device = getDeviceLocked(deviceId);
1053 if (device == nullptr || !device->hasValidFd() || !device->keyBitmask.test(scanCode)) {
1054 return AKEY_STATE_UNKNOWN;
1055 }
1056 return device->keyState.test(scanCode) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001057}
1058
1059int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
Chris Ye87143712020-11-10 05:05:58 +00001060 std::scoped_lock _l(mLock);
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001061 const Device* device = getDeviceLocked(deviceId);
1062 if (device == nullptr || !device->hasValidFd() || !device->keyMap.haveKeyLayout()) {
1063 return AKEY_STATE_UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001064 }
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001065 const std::vector<int32_t> scanCodes =
1066 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode);
1067 if (scanCodes.empty()) {
1068 return AKEY_STATE_UNKNOWN;
1069 }
1070 return std::any_of(scanCodes.begin(), scanCodes.end(),
1071 [&device](const int32_t sc) {
1072 return sc >= 0 && sc <= KEY_MAX && device->keyState.test(sc);
1073 })
1074 ? AKEY_STATE_DOWN
1075 : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001076}
1077
Philip Junker4af3b3d2021-12-14 10:36:55 +01001078int32_t EventHub::getKeyCodeForKeyLocation(int32_t deviceId, int32_t locationKeyCode) const {
1079 std::scoped_lock _l(mLock);
1080
1081 Device* device = getDeviceLocked(deviceId);
1082 if (device == nullptr || !device->hasValidFd() || device->keyMap.keyCharacterMap == nullptr ||
1083 device->keyMap.keyLayoutMap == nullptr) {
1084 return AKEYCODE_UNKNOWN;
1085 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001086 std::vector<int32_t> scanCodes =
1087 device->keyMap.keyLayoutMap->findScanCodesForKey(locationKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +01001088 if (scanCodes.empty()) {
1089 ALOGW("Failed to get key code for key location: no scan code maps to key code %d for input"
1090 "device %d",
1091 locationKeyCode, deviceId);
1092 return AKEYCODE_UNKNOWN;
1093 }
1094 if (scanCodes.size() > 1) {
1095 ALOGW("Multiple scan codes map to the same key code %d, returning only the first match",
1096 locationKeyCode);
1097 }
1098 int32_t outKeyCode;
1099 status_t mapKeyRes =
Harry Cutts33476232023-01-30 19:57:29 +00001100 device->getKeyCharacterMap()->mapKey(scanCodes[0], /*usageCode=*/0, &outKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +01001101 switch (mapKeyRes) {
1102 case OK:
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001103 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +01001104 case NAME_NOT_FOUND:
1105 // key character map doesn't re-map this scanCode, hence the keyCode remains the same
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001106 outKeyCode = locationKeyCode;
1107 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +01001108 default:
1109 ALOGW("Failed to get key code for key location: Key character map returned error %s",
1110 statusToString(mapKeyRes).c_str());
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001111 outKeyCode = AKEYCODE_UNKNOWN;
1112 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +01001113 }
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001114 // Remap if there is a Key remapping added to the KCM and return the remapped key
1115 return device->getKeyCharacterMap()->applyKeyRemapping(outKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +01001116}
1117
Michael Wrightd02c5b62014-02-10 15:10:22 -08001118int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001119 if (sw < 0 || sw > SW_MAX) {
1120 return AKEY_STATE_UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001121 }
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001122 std::scoped_lock _l(mLock);
1123 const Device* device = getDeviceLocked(deviceId);
1124 if (device == nullptr || !device->hasValidFd() || !device->swBitmask.test(sw)) {
1125 return AKEY_STATE_UNKNOWN;
1126 }
1127 return device->swState.test(sw) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001128}
1129
Harry Cuttse2c5e202024-06-21 17:08:48 +00001130std::optional<int32_t> EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis) const {
Prabir Pradhan341d0782023-07-14 19:04:10 +00001131 if (axis < 0 || axis > ABS_MAX) {
Harry Cuttse2c5e202024-06-21 17:08:48 +00001132 return std::nullopt;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001133 }
Prabir Pradhan341d0782023-07-14 19:04:10 +00001134 std::scoped_lock _l(mLock);
1135 const Device* device = getDeviceLocked(deviceId);
1136 if (device == nullptr || !device->hasValidFd()) {
Harry Cuttse2c5e202024-06-21 17:08:48 +00001137 return std::nullopt;
Prabir Pradhan341d0782023-07-14 19:04:10 +00001138 }
1139 const auto it = device->absState.find(axis);
1140 if (it == device->absState.end()) {
Harry Cuttse2c5e202024-06-21 17:08:48 +00001141 return std::nullopt;
Prabir Pradhan341d0782023-07-14 19:04:10 +00001142 }
Harry Cuttse2c5e202024-06-21 17:08:48 +00001143 return it->second.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001144}
1145
Arpit Singh4b4a4572023-11-24 18:19:56 +00001146base::Result<std::vector<int32_t>> EventHub::getMtSlotValues(int32_t deviceId, int32_t axis,
1147 size_t slotCount) const {
1148 std::scoped_lock _l(mLock);
1149 const Device* device = getDeviceLocked(deviceId);
1150 if (device == nullptr || !device->hasValidFd() || !device->absBitmask.test(axis)) {
1151 return base::ResultError("device problem or axis not supported", NAME_NOT_FOUND);
1152 }
1153 std::vector<int32_t> outValues(slotCount + 1);
1154 outValues[0] = axis;
1155 const size_t bufferSize = outValues.size() * sizeof(int32_t);
1156 if (ioctl(device->fd, EVIOCGMTSLOTS(bufferSize), outValues.data()) != OK) {
1157 return base::ErrnoError();
1158 }
1159 return std::move(outValues);
1160}
1161
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001162bool EventHub::markSupportedKeyCodes(int32_t deviceId, const std::vector<int32_t>& keyCodes,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001163 uint8_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +00001164 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001165
1166 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001167 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001168 for (size_t codeIndex = 0; codeIndex < keyCodes.size(); codeIndex++) {
Sergej Salnikove5420e72023-05-11 11:52:54 +00001169 if (device->hasKeycodeLocked(keyCodes[codeIndex])) {
1170 outFlags[codeIndex] = 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001171 }
1172 }
1173 return true;
1174 }
1175 return false;
1176}
1177
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001178void EventHub::addKeyRemapping(int32_t deviceId, int32_t fromKeyCode, int32_t toKeyCode) const {
1179 std::scoped_lock _l(mLock);
1180 Device* device = getDeviceLocked(deviceId);
1181 if (device == nullptr) {
1182 return;
1183 }
1184 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
1185 if (kcm) {
1186 kcm->addKeyRemapping(fromKeyCode, toKeyCode);
1187 }
1188}
1189
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001190status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
1191 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +00001192 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001193 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001194 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001195
Chris Ye66fbac32020-07-06 20:36:43 -07001196 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001197 // Check the key character map first.
Chris Ye3a1e4462020-08-12 10:13:15 -07001198 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
1199 if (kcm) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001200 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
1201 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001202 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001203 }
1204 }
1205
1206 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001207 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -08001208 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001209 status = NO_ERROR;
1210 }
1211 }
1212
1213 if (status == NO_ERROR) {
Chris Ye3a1e4462020-08-12 10:13:15 -07001214 if (kcm) {
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001215 // Remap keys based on user-defined key remappings and key behavior defined in the
1216 // corresponding kcm file
1217 *outKeycode = kcm->applyKeyRemapping(*outKeycode);
1218
1219 // Remap keys based on Key behavior defined in KCM file
1220 std::tie(*outKeycode, *outMetaState) =
1221 kcm->applyKeyBehavior(*outKeycode, metaState);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001222 } else {
1223 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001224 }
1225 }
1226 }
1227
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001228 if (status != NO_ERROR) {
1229 *outKeycode = 0;
1230 *outFlags = 0;
1231 *outMetaState = metaState;
1232 }
1233
1234 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001235}
1236
1237status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
Chris Ye87143712020-11-10 05:05:58 +00001238 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001239 Device* device = getDeviceLocked(deviceId);
1240
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001241 if (device == nullptr || !device->keyMap.haveKeyLayout()) {
1242 return NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001244 std::optional<AxisInfo> info = device->keyMap.keyLayoutMap->mapAxis(scanCode);
1245 if (!info.has_value()) {
1246 return NAME_NOT_FOUND;
1247 }
1248 *outAxisInfo = *info;
1249 return NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001250}
1251
Chris Yef59a2f42020-10-16 12:55:26 -07001252base::Result<std::pair<InputDeviceSensorType, int32_t>> EventHub::mapSensor(int32_t deviceId,
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001253 int32_t absCode) const {
Chris Yef59a2f42020-10-16 12:55:26 -07001254 std::scoped_lock _l(mLock);
1255 Device* device = getDeviceLocked(deviceId);
1256
1257 if (device != nullptr && device->keyMap.haveKeyLayout()) {
1258 return device->keyMap.keyLayoutMap->mapSensor(absCode);
1259 }
1260 return Errorf("Device not found or device has no key layout.");
1261}
1262
Chris Yee2b1e5c2021-03-10 22:45:12 -08001263// Gets the battery info map from battery ID to RawBatteryInfo of the miscellaneous device
1264// associated with the device ID. Returns an empty map if no miscellaneous device found.
1265const std::unordered_map<int32_t, RawBatteryInfo>& EventHub::getBatteryInfoLocked(
1266 int32_t deviceId) const {
1267 static const std::unordered_map<int32_t, RawBatteryInfo> EMPTY_BATTERY_INFO = {};
1268 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001269 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001270 return EMPTY_BATTERY_INFO;
1271 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001272 return device->associatedDevice->batteryInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001273}
1274
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001275std::vector<int32_t> EventHub::getRawBatteryIds(int32_t deviceId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001276 std::scoped_lock _l(mLock);
1277 std::vector<int32_t> batteryIds;
1278
Prabir Pradhan51894782022-08-23 16:29:10 +00001279 for (const auto& [id, info] : getBatteryInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001280 batteryIds.push_back(id);
1281 }
1282
1283 return batteryIds;
1284}
1285
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001286std::optional<RawBatteryInfo> EventHub::getRawBatteryInfo(int32_t deviceId,
1287 int32_t batteryId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001288 std::scoped_lock _l(mLock);
1289
1290 const auto infos = getBatteryInfoLocked(deviceId);
1291
1292 auto it = infos.find(batteryId);
1293 if (it != infos.end()) {
1294 return it->second;
1295 }
1296
1297 return std::nullopt;
1298}
1299
1300// Gets the light info map from light ID to RawLightInfo of the miscellaneous device associated
Prabir Pradhan51894782022-08-23 16:29:10 +00001301// with the device ID. Returns an empty map if no miscellaneous device found.
Chris Yee2b1e5c2021-03-10 22:45:12 -08001302const std::unordered_map<int32_t, RawLightInfo>& EventHub::getLightInfoLocked(
1303 int32_t deviceId) const {
1304 static const std::unordered_map<int32_t, RawLightInfo> EMPTY_LIGHT_INFO = {};
1305 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001306 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001307 return EMPTY_LIGHT_INFO;
1308 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001309 return device->associatedDevice->lightInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001310}
1311
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001312std::vector<int32_t> EventHub::getRawLightIds(int32_t deviceId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001313 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001314 std::vector<int32_t> lightIds;
1315
Prabir Pradhan51894782022-08-23 16:29:10 +00001316 for (const auto& [id, info] : getLightInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001317 lightIds.push_back(id);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001318 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001319
Chris Ye3fdbfef2021-01-06 18:45:18 -08001320 return lightIds;
1321}
1322
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001323std::optional<RawLightInfo> EventHub::getRawLightInfo(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001324 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001325
Chris Yee2b1e5c2021-03-10 22:45:12 -08001326 const auto infos = getLightInfoLocked(deviceId);
1327
1328 auto it = infos.find(lightId);
1329 if (it != infos.end()) {
1330 return it->second;
Chris Ye3fdbfef2021-01-06 18:45:18 -08001331 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001332
Chris Ye3fdbfef2021-01-06 18:45:18 -08001333 return std::nullopt;
1334}
1335
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001336std::optional<int32_t> EventHub::getLightBrightness(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001337 std::scoped_lock _l(mLock);
1338
Chris Yee2b1e5c2021-03-10 22:45:12 -08001339 const auto infos = getLightInfoLocked(deviceId);
1340 auto it = infos.find(lightId);
1341 if (it == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001342 return std::nullopt;
1343 }
1344 std::string buffer;
1345 if (!base::ReadFileToString(it->second.path / LIGHT_NODES.at(InputLightClass::BRIGHTNESS),
1346 &buffer)) {
1347 return std::nullopt;
1348 }
1349 return std::stoi(buffer);
1350}
1351
1352std::optional<std::unordered_map<LightColor, int32_t>> EventHub::getLightIntensities(
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001353 int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001354 std::scoped_lock _l(mLock);
1355
Chris Yee2b1e5c2021-03-10 22:45:12 -08001356 const auto infos = getLightInfoLocked(deviceId);
1357 auto lightIt = infos.find(lightId);
1358 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001359 return std::nullopt;
1360 }
1361
1362 auto ret =
1363 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1364
1365 if (!ret.has_value()) {
1366 return std::nullopt;
1367 }
1368 std::array<LightColor, COLOR_NUM> colors = ret.value();
1369
1370 std::string intensityStr;
1371 if (!base::ReadFileToString(lightIt->second.path /
1372 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY),
1373 &intensityStr)) {
1374 return std::nullopt;
1375 }
1376
1377 // Intensity node outputs 3 color values
1378 std::regex intensityPattern("([0-9]+)\\s([0-9]+)\\s([0-9]+)[\\n]");
1379 std::smatch results;
1380
1381 if (!std::regex_match(intensityStr, results, intensityPattern)) {
1382 return std::nullopt;
1383 }
1384 std::unordered_map<LightColor, int32_t> intensities;
1385 for (size_t i = 1; i < results.size(); i++) {
1386 int value = std::stoi(results[i].str());
1387 intensities.emplace(colors[i - 1], value);
1388 }
1389 return intensities;
1390}
1391
1392void EventHub::setLightBrightness(int32_t deviceId, int32_t lightId, int32_t brightness) {
1393 std::scoped_lock _l(mLock);
1394
Chris Yee2b1e5c2021-03-10 22:45:12 -08001395 const auto infos = getLightInfoLocked(deviceId);
1396 auto lightIt = infos.find(lightId);
1397 if (lightIt == infos.end()) {
1398 ALOGE("%s lightId %d not found ", __func__, lightId);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001399 return;
1400 }
1401
1402 if (!base::WriteStringToFile(std::to_string(brightness),
1403 lightIt->second.path /
1404 LIGHT_NODES.at(InputLightClass::BRIGHTNESS))) {
1405 ALOGE("Can not write to file, error: %s", strerror(errno));
1406 }
1407}
1408
1409void EventHub::setLightIntensities(int32_t deviceId, int32_t lightId,
1410 std::unordered_map<LightColor, int32_t> intensities) {
1411 std::scoped_lock _l(mLock);
1412
Chris Yee2b1e5c2021-03-10 22:45:12 -08001413 const auto infos = getLightInfoLocked(deviceId);
1414 auto lightIt = infos.find(lightId);
1415 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001416 ALOGE("Light Id %d does not exist.", lightId);
1417 return;
1418 }
1419
1420 auto ret =
1421 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1422
1423 if (!ret.has_value()) {
1424 return;
1425 }
1426 std::array<LightColor, COLOR_NUM> colors = ret.value();
1427
1428 std::string rgbStr;
1429 for (size_t i = 0; i < COLOR_NUM; i++) {
1430 auto it = intensities.find(colors[i]);
1431 if (it != intensities.end()) {
1432 rgbStr += std::to_string(it->second);
1433 // Insert space between colors
1434 if (i < COLOR_NUM - 1) {
1435 rgbStr += " ";
1436 }
1437 }
1438 }
1439 // Append new line
1440 rgbStr += "\n";
1441
1442 if (!base::WriteStringToFile(rgbStr,
1443 lightIt->second.path /
1444 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY))) {
1445 ALOGE("Can not write to file, error: %s", strerror(errno));
1446 }
1447}
1448
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001449std::optional<RawLayoutInfo> EventHub::getRawLayoutInfo(int32_t deviceId) const {
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001450 std::scoped_lock _l(mLock);
1451 Device* device = getDeviceLocked(deviceId);
1452 if (device == nullptr || !device->associatedDevice) {
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001453 return std::nullopt;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001454 }
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001455 return device->associatedDevice->layoutInfo;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001456}
1457
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001458void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Chris Ye87143712020-11-10 05:05:58 +00001459 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001460
1461 mExcludedDevices = devices;
1462}
1463
1464bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
Chris Ye87143712020-11-10 05:05:58 +00001465 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001466 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001467 if (device != nullptr && scanCode >= 0 && scanCode <= KEY_MAX) {
1468 return device->keyBitmask.test(scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001469 }
1470 return false;
1471}
1472
Arthur Hungcb40a002021-08-03 14:31:01 +00001473bool EventHub::hasKeyCode(int32_t deviceId, int32_t keyCode) const {
1474 std::scoped_lock _l(mLock);
1475 Device* device = getDeviceLocked(deviceId);
1476 if (device != nullptr) {
1477 return device->hasKeycodeLocked(keyCode);
1478 }
1479 return false;
1480}
1481
Michael Wrightd02c5b62014-02-10 15:10:22 -08001482bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
Chris Ye87143712020-11-10 05:05:58 +00001483 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001484 Device* device = getDeviceLocked(deviceId);
1485 int32_t sc;
Chris Ye989bb932020-07-04 16:18:59 -07001486 if (device != nullptr && device->mapLed(led, &sc) == NO_ERROR) {
Chris Ye66fbac32020-07-06 20:36:43 -07001487 return device->ledBitmask.test(sc);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001488 }
1489 return false;
1490}
1491
1492void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
Chris Ye87143712020-11-10 05:05:58 +00001493 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001494 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -07001495 if (device != nullptr && device->hasValidFd()) {
1496 device->setLedStateLocked(led, on);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001497 }
1498}
1499
1500void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001501 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001502 outVirtualKeys.clear();
1503
Chris Ye87143712020-11-10 05:05:58 +00001504 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001505 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001506 if (device != nullptr && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001507 const std::vector<VirtualKeyDefinition> virtualKeys =
1508 device->virtualKeyMap->getVirtualKeys();
1509 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001510 }
1511}
1512
Chris Ye3a1e4462020-08-12 10:13:15 -07001513const std::shared_ptr<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001514 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001515 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001516 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001517 return device->getKeyCharacterMap();
1518 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001519 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001520}
1521
Vaibhav Devmurari23e8ae92022-12-29 12:07:56 +00001522// If provided map is null, it will reset key character map to default KCM.
Chris Ye3a1e4462020-08-12 10:13:15 -07001523bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, std::shared_ptr<KeyCharacterMap> map) {
Chris Ye87143712020-11-10 05:05:58 +00001524 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001525 Device* device = getDeviceLocked(deviceId);
Vaibhav Devmurari23e8ae92022-12-29 12:07:56 +00001526 if (device == nullptr || device->keyMap.keyCharacterMap == nullptr) {
Philip Junker90bc9492021-12-10 18:39:42 +01001527 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001528 }
Vaibhav Devmurari23e8ae92022-12-29 12:07:56 +00001529 if (map == nullptr) {
1530 device->keyMap.keyCharacterMap->clearLayoutOverlay();
1531 return true;
1532 }
Philip Junker90bc9492021-12-10 18:39:42 +01001533 device->keyMap.keyCharacterMap->combine(*map);
1534 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001535}
1536
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001537static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
1538 std::string rawDescriptor;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001539 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001540 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001541 if (!identifier.uniqueId.empty()) {
1542 rawDescriptor += "uniqueId:";
1543 rawDescriptor += identifier.uniqueId;
Josh Bartel938632f2022-07-19 15:34:22 -05001544 }
1545 if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001546 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001547 }
1548
1549 if (identifier.vendor == 0 && identifier.product == 0) {
1550 // If we don't know the vendor and product id, then the device is probably
1551 // built-in so we need to rely on other information to uniquely identify
1552 // the input device. Usually we try to avoid relying on the device name or
1553 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001554 if (!identifier.name.empty()) {
1555 rawDescriptor += "name:";
1556 rawDescriptor += identifier.name;
1557 } else if (!identifier.location.empty()) {
1558 rawDescriptor += "location:";
1559 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001560 }
1561 }
1562 identifier.descriptor = sha1(rawDescriptor);
1563 return rawDescriptor;
1564}
1565
1566void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
1567 // Compute a device descriptor that uniquely identifies the device.
1568 // The descriptor is assumed to be a stable identifier. Its value should not
1569 // change between reboots, reconnections, firmware updates or new releases
1570 // of Android. In practice we sometimes get devices that cannot be uniquely
1571 // identified. In this case we enforce uniqueness between connected devices.
1572 // Ideally, we also want the descriptor to be short and relatively opaque.
Josh Bartel938632f2022-07-19 15:34:22 -05001573 // Note that we explicitly do not use the path or location for external devices
1574 // as their path or location will change as they are plugged/unplugged or moved
1575 // to different ports. We do fallback to using name and location in the case of
1576 // internal devices which are detected by the vendor and product being 0 in
1577 // generateDescriptor. If two identical descriptors are detected we will fallback
1578 // to using a 'nonce' and incrementing it until the new descriptor no longer has
1579 // a match with any existing descriptors.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001580
1581 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001582 std::string rawDescriptor = generateDescriptor(identifier);
Josh Bartel938632f2022-07-19 15:34:22 -05001583 // Enforce that the generated descriptor is unique.
1584 while (hasDeviceWithDescriptorLocked(identifier.descriptor)) {
1585 identifier.nonce++;
1586 rawDescriptor = generateDescriptor(identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001587 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001588 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001589 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001590}
1591
Prabir Pradhancb42b472022-08-23 16:01:19 +00001592std::shared_ptr<const EventHub::AssociatedDevice> EventHub::obtainAssociatedDeviceLocked(
1593 const std::filesystem::path& devicePath) const {
1594 const std::optional<std::filesystem::path> sysfsRootPathOpt =
1595 getSysfsRootPath(devicePath.c_str());
1596 if (!sysfsRootPathOpt) {
1597 return nullptr;
1598 }
1599
1600 const auto& path = *sysfsRootPathOpt;
Prabir Pradhancb42b472022-08-23 16:01:19 +00001601
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00001602 std::shared_ptr<const AssociatedDevice> associatedDevice = std::make_shared<AssociatedDevice>(
Prabir Pradhancb42b472022-08-23 16:01:19 +00001603 AssociatedDevice{.sysfsRootPath = path,
1604 .batteryInfos = readBatteryConfiguration(path),
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001605 .lightInfos = readLightsConfiguration(path),
1606 .layoutInfo = readLayoutConfiguration(path)});
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00001607
1608 bool associatedDeviceChanged = false;
1609 for (const auto& [id, dev] : mDevices) {
1610 if (dev->associatedDevice && dev->associatedDevice->sysfsRootPath == path) {
1611 if (*associatedDevice != *dev->associatedDevice) {
1612 associatedDeviceChanged = true;
1613 dev->associatedDevice = associatedDevice;
1614 }
1615 associatedDevice = dev->associatedDevice;
1616 }
1617 }
1618 ALOGI_IF(associatedDeviceChanged,
1619 "The AssociatedDevice changed for path '%s'. Using new AssociatedDevice: %s",
1620 path.c_str(), associatedDevice->dump().c_str());
1621
1622 return associatedDevice;
Prabir Pradhancb42b472022-08-23 16:01:19 +00001623}
1624
Vaibhav Devmurari5fc7d852023-03-17 18:43:33 +00001625bool EventHub::AssociatedDevice::isChanged() const {
1626 std::unordered_map<int32_t, RawBatteryInfo> newBatteryInfos =
1627 readBatteryConfiguration(sysfsRootPath);
1628 std::unordered_map<int32_t, RawLightInfo> newLightInfos =
1629 readLightsConfiguration(sysfsRootPath);
1630 std::optional<RawLayoutInfo> newLayoutInfo = readLayoutConfiguration(sysfsRootPath);
1631
1632 if (newBatteryInfos == batteryInfos && newLightInfos == lightInfos &&
1633 newLayoutInfo == layoutInfo) {
1634 return false;
1635 }
1636 return true;
1637}
1638
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001639void EventHub::vibrate(int32_t deviceId, const VibrationElement& element) {
Chris Ye87143712020-11-10 05:05:58 +00001640 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001641 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001642 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001643 ff_effect effect;
1644 memset(&effect, 0, sizeof(effect));
1645 effect.type = FF_RUMBLE;
1646 effect.id = device->ffEffectId;
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001647 // evdev FF_RUMBLE effect only supports two channels of vibration.
Chris Ye6393a262020-08-04 19:41:36 -07001648 effect.u.rumble.strong_magnitude = element.getMagnitude(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1649 effect.u.rumble.weak_magnitude = element.getMagnitude(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001650 effect.replay.length = element.duration.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001651 effect.replay.delay = 0;
1652 if (ioctl(device->fd, EVIOCSFF, &effect)) {
1653 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001654 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001655 return;
1656 }
1657 device->ffEffectId = effect.id;
1658
1659 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -07001660 ev.input_event_sec = 0;
1661 ev.input_event_usec = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001662 ev.type = EV_FF;
1663 ev.code = device->ffEffectId;
1664 ev.value = 1;
1665 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1666 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001667 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001668 return;
1669 }
1670 device->ffEffectPlaying = true;
1671 }
1672}
1673
1674void EventHub::cancelVibrate(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001675 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001676 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001677 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001678 if (device->ffEffectPlaying) {
1679 device->ffEffectPlaying = false;
1680
1681 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -07001682 ev.input_event_sec = 0;
1683 ev.input_event_usec = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001684 ev.type = EV_FF;
1685 ev.code = device->ffEffectId;
1686 ev.value = 0;
1687 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1688 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001689 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001690 return;
1691 }
1692 }
1693 }
1694}
1695
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001696std::vector<int32_t> EventHub::getVibratorIds(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001697 std::scoped_lock _l(mLock);
1698 std::vector<int32_t> vibrators;
1699 Device* device = getDeviceLocked(deviceId);
1700 if (device != nullptr && device->hasValidFd() &&
1701 device->classes.test(InputDeviceClass::VIBRATOR)) {
1702 vibrators.push_back(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1703 vibrators.push_back(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
1704 }
1705 return vibrators;
1706}
1707
Josh Bartel938632f2022-07-19 15:34:22 -05001708/**
1709 * Checks both mDevices and mOpeningDevices for a device with the descriptor passed.
1710 */
1711bool EventHub::hasDeviceWithDescriptorLocked(const std::string& descriptor) const {
1712 for (const auto& device : mOpeningDevices) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001713 if (descriptor == device->identifier.descriptor) {
Josh Bartel938632f2022-07-19 15:34:22 -05001714 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001715 }
1716 }
Josh Bartel938632f2022-07-19 15:34:22 -05001717
1718 for (const auto& [id, device] : mDevices) {
1719 if (descriptor == device->identifier.descriptor) {
1720 return true;
1721 }
1722 }
1723 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001724}
1725
1726EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001727 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001728 deviceId = mBuiltInKeyboardId;
1729 }
Chris Ye989bb932020-07-04 16:18:59 -07001730 const auto& it = mDevices.find(deviceId);
1731 return it != mDevices.end() ? it->second.get() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001732}
1733
Chris Ye8594e192020-07-14 10:34:06 -07001734EventHub::Device* EventHub::getDeviceByPathLocked(const std::string& devicePath) const {
Chris Ye989bb932020-07-04 16:18:59 -07001735 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001736 if (device->path == devicePath) {
Chris Ye989bb932020-07-04 16:18:59 -07001737 return device.get();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001738 }
1739 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001740 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001741}
1742
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001743/**
1744 * The file descriptor could be either input device, or a video device (associated with a
1745 * specific input device). Check both cases here, and return the device that this event
1746 * belongs to. Caller can compare the fd's once more to determine event type.
1747 * Looks through all input devices, and only attached video devices. Unattached video
1748 * devices are ignored.
1749 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001750EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
Chris Ye989bb932020-07-04 16:18:59 -07001751 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001752 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001753 // This is an input device event
Chris Ye989bb932020-07-04 16:18:59 -07001754 return device.get();
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001755 }
1756 if (device->videoDevice && device->videoDevice->getFd() == fd) {
1757 // This is a video device event
Chris Ye989bb932020-07-04 16:18:59 -07001758 return device.get();
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001759 }
1760 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001761 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
1762 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001763 return nullptr;
1764}
1765
Chris Yee2b1e5c2021-03-10 22:45:12 -08001766std::optional<int32_t> EventHub::getBatteryCapacity(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001767 std::filesystem::path batteryPath;
1768 {
1769 // Do not read the sysfs node to get the battery state while holding
1770 // the EventHub lock. For some peripheral devices, reading battery state
1771 // can be broken and take 5+ seconds. Holding the lock in this case would
1772 // block all other event processing during this time. For now, we assume this
1773 // call never happens on the InputReader thread and read the sysfs node outside
1774 // the lock to prevent event processing from being blocked by this call.
1775 std::scoped_lock _l(mLock);
Kim Low03ea0352020-11-06 12:45:07 -08001776
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001777 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001778 auto it = infos.find(batteryId);
1779 if (it == infos.end()) {
1780 return std::nullopt;
1781 }
1782 batteryPath = it->second.path;
1783 } // release lock
1784
Chris Yee2b1e5c2021-03-10 22:45:12 -08001785 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001786
1787 // Some devices report battery capacity as an integer through the "capacity" file
Andy Chenf9f1a022022-08-29 20:07:10 -04001788 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001789 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001790 return std::stoi(base::Trim(buffer));
Kim Low03ea0352020-11-06 12:45:07 -08001791 }
1792
1793 // Other devices report capacity as an enum value POWER_SUPPLY_CAPACITY_LEVEL_XXX
1794 // These values are taken from kernel source code include/linux/power_supply.h
Andy Chenf9f1a022022-08-29 20:07:10 -04001795 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY_LEVEL),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001796 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001797 // Remove any white space such as trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001798 const auto levelIt = BATTERY_LEVEL.find(base::Trim(buffer));
1799 if (levelIt != BATTERY_LEVEL.end()) {
1800 return levelIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001801 }
1802 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001803
Kim Low03ea0352020-11-06 12:45:07 -08001804 return std::nullopt;
1805}
1806
Chris Yee2b1e5c2021-03-10 22:45:12 -08001807std::optional<int32_t> EventHub::getBatteryStatus(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001808 std::filesystem::path batteryPath;
1809 {
1810 // Do not read the sysfs node to get the battery state while holding
1811 // the EventHub lock. For some peripheral devices, reading battery state
1812 // can be broken and take 5+ seconds. Holding the lock in this case would
1813 // block all other event processing during this time. For now, we assume this
1814 // call never happens on the InputReader thread and read the sysfs node outside
1815 // the lock to prevent event processing from being blocked by this call.
1816 std::scoped_lock _l(mLock);
1817
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001818 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001819 auto it = infos.find(batteryId);
1820 if (it == infos.end()) {
1821 return std::nullopt;
1822 }
1823 batteryPath = it->second.path;
1824 } // release lock
1825
Chris Yee2b1e5c2021-03-10 22:45:12 -08001826 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001827
Andy Chenf9f1a022022-08-29 20:07:10 -04001828 if (!base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::STATUS),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001829 &buffer)) {
Kim Low03ea0352020-11-06 12:45:07 -08001830 ALOGE("Failed to read sysfs battery info: %s", strerror(errno));
1831 return std::nullopt;
1832 }
1833
Chris Yed1936772021-02-22 10:30:40 -08001834 // Remove white space like trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001835 const auto statusIt = BATTERY_STATUS.find(base::Trim(buffer));
1836 if (statusIt != BATTERY_STATUS.end()) {
1837 return statusIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001838 }
1839
1840 return std::nullopt;
1841}
1842
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001843std::vector<RawEvent> EventHub::getEvents(int timeoutMillis) {
Chris Ye87143712020-11-10 05:05:58 +00001844 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001845
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001846 std::array<input_event, EVENT_BUFFER_SIZE> readBuffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001847
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001848 std::vector<RawEvent> events;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001849 bool awoken = false;
1850 for (;;) {
1851 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
1852
1853 // Reopen input devices if needed.
1854 if (mNeedToReopenDevices) {
1855 mNeedToReopenDevices = false;
1856
1857 ALOGI("Reopening all input devices due to a configuration change.");
1858
1859 closeAllDevicesLocked();
1860 mNeedToScanDevices = true;
1861 break; // return to the caller before we actually rescan
1862 }
1863
1864 // Report any devices that had last been added/removed.
Chris Ye989bb932020-07-04 16:18:59 -07001865 for (auto it = mClosingDevices.begin(); it != mClosingDevices.end();) {
1866 std::unique_ptr<Device> device = std::move(*it);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001867 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001868 const int32_t deviceId = (device->id == mBuiltInKeyboardId)
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001869 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
1870 : device->id;
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001871 events.push_back({
1872 .when = now,
1873 .deviceId = deviceId,
1874 .type = DEVICE_REMOVED,
1875 });
Chris Ye989bb932020-07-04 16:18:59 -07001876 it = mClosingDevices.erase(it);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001877 mNeedToSendFinishedDeviceScan = true;
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001878 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001879 break;
1880 }
1881 }
1882
1883 if (mNeedToScanDevices) {
1884 mNeedToScanDevices = false;
1885 scanDevicesLocked();
1886 mNeedToSendFinishedDeviceScan = true;
1887 }
1888
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001889 while (!mOpeningDevices.empty()) {
1890 std::unique_ptr<Device> device = std::move(*mOpeningDevices.rbegin());
1891 mOpeningDevices.pop_back();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001892 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001893 const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1894 events.push_back({
1895 .when = now,
1896 .deviceId = deviceId,
1897 .type = DEVICE_ADDED,
1898 });
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001899
1900 // Try to find a matching video device by comparing device names
1901 for (auto it = mUnattachedVideoDevices.begin(); it != mUnattachedVideoDevices.end();
1902 it++) {
1903 std::unique_ptr<TouchVideoDevice>& videoDevice = *it;
Chris Yed3fef462021-03-07 17:10:08 -08001904 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001905 // videoDevice was transferred to 'device'
1906 it = mUnattachedVideoDevices.erase(it);
1907 break;
1908 }
1909 }
1910
1911 auto [dev_it, inserted] = mDevices.insert_or_assign(device->id, std::move(device));
1912 if (!inserted) {
Chris Ye989bb932020-07-04 16:18:59 -07001913 ALOGW("Device id %d exists, replaced.", device->id);
1914 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001915 mNeedToSendFinishedDeviceScan = true;
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001916 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001917 break;
1918 }
1919 }
1920
1921 if (mNeedToSendFinishedDeviceScan) {
1922 mNeedToSendFinishedDeviceScan = false;
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001923 events.push_back({
1924 .when = now,
1925 .type = FINISHED_DEVICE_SCAN,
1926 });
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001927 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001928 break;
1929 }
1930 }
1931
1932 // Grab the next input event.
1933 bool deviceChanged = false;
1934 while (mPendingEventIndex < mPendingEventCount) {
1935 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001936 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001937 if (eventItem.events & EPOLLIN) {
1938 mPendingINotify = true;
1939 } else {
1940 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
1941 }
1942 continue;
1943 }
1944
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001945 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001946 if (eventItem.events & EPOLLIN) {
1947 ALOGV("awoken after wake()");
1948 awoken = true;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001949 char wakeReadBuffer[16];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001950 ssize_t nRead;
1951 do {
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001952 nRead = read(mWakeReadPipeFd, wakeReadBuffer, sizeof(wakeReadBuffer));
1953 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(wakeReadBuffer));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001954 } else {
1955 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001956 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001957 }
1958 continue;
1959 }
1960
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001961 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Chris Ye989bb932020-07-04 16:18:59 -07001962 if (device == nullptr) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001963 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
1964 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001965 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001966 continue;
1967 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001968 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
1969 if (eventItem.events & EPOLLIN) {
1970 size_t numFrames = device->videoDevice->readAndQueueFrames();
1971 if (numFrames == 0) {
1972 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001973 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001974 }
1975 } else if (eventItem.events & EPOLLHUP) {
1976 // TODO(b/121395353) - consider adding EPOLLRDHUP
1977 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001978 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001979 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1980 device->videoDevice = nullptr;
1981 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001982 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1983 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001984 ALOG_ASSERT(!DEBUG);
1985 }
1986 continue;
1987 }
1988 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -08001989 if (eventItem.events & EPOLLIN) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001990 int32_t readSize =
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001991 read(device->fd, readBuffer.data(),
1992 sizeof(decltype(readBuffer)::value_type) * readBuffer.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001993 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
1994 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -07001995 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001996 " capacity: %zu errno: %d)\n",
1997 device->fd, readSize, readBuffer.size(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001998 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001999 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002000 } else if (readSize < 0) {
2001 if (errno != EAGAIN && errno != EINTR) {
2002 ALOGW("could not get event (errno=%d)", errno);
2003 }
2004 } else if ((readSize % sizeof(struct input_event)) != 0) {
2005 ALOGE("could not get event (wrong size: %d)", readSize);
2006 } else {
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002007 const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002008
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002009 const size_t count = size_t(readSize) / sizeof(struct input_event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002010 for (size_t i = 0; i < count; i++) {
2011 struct input_event& iev = readBuffer[i];
Prabir Pradhan9762ac92023-07-13 21:45:12 +00002012 device->trackInputEvent(iev);
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002013 events.push_back({
2014 .when = processEventTimestamp(iev),
2015 .readTime = systemTime(SYSTEM_TIME_MONOTONIC),
2016 .deviceId = deviceId,
2017 .type = iev.type,
2018 .code = iev.code,
2019 .value = iev.value,
2020 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08002021 }
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07002022 if (events.size() >= EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002023 // The result buffer is full. Reset the pending event index
2024 // so we will try to read the device again on the next iteration.
2025 mPendingEventIndex -= 1;
2026 break;
2027 }
2028 }
2029 } else if (eventItem.events & EPOLLHUP) {
2030 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002031 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002032 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07002033 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002034 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002035 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
2036 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002037 }
2038 }
2039
2040 // readNotify() will modify the list of devices so this must be done after
2041 // processing all other events to ensure that we read all remaining events
2042 // before closing the devices.
2043 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
2044 mPendingINotify = false;
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002045 const auto res = readNotifyLocked();
2046 if (!res.ok()) {
2047 ALOGW("Failed to read from inotify: %s", res.error().message().c_str());
2048 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002049 deviceChanged = true;
2050 }
2051
2052 // Report added or removed devices immediately.
2053 if (deviceChanged) {
2054 continue;
2055 }
2056
2057 // Return now if we have collected any events or if we were explicitly awoken.
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002058 if (!events.empty() || awoken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002059 break;
2060 }
2061
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01002062 // Poll for events.
2063 // When a device driver has pending (unread) events, it acquires
2064 // a kernel wake lock. Once the last pending event has been read, the device
2065 // driver will release the kernel wake lock, but the epoll will hold the wakelock,
2066 // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
2067 // is called again for the same fd that produced the event.
2068 // Thus the system can only sleep if there are no events pending or
2069 // currently being processed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002070 //
2071 // The timeout is advisory only. If the device is asleep, it will not wake just to
2072 // service the timeout.
2073 mPendingEventIndex = 0;
2074
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01002075 mLock.unlock(); // release lock before poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08002076
2077 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
2078
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01002079 mLock.lock(); // reacquire lock after poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08002080
2081 if (pollResult == 0) {
2082 // Timed out.
2083 mPendingEventCount = 0;
2084 break;
2085 }
2086
2087 if (pollResult < 0) {
2088 // An error occurred.
2089 mPendingEventCount = 0;
2090
2091 // Sleep after errors to avoid locking up the system.
2092 // Hopefully the error is transient.
2093 if (errno != EINTR) {
2094 ALOGW("poll failed (errno=%d)\n", errno);
2095 usleep(100000);
2096 }
2097 } else {
2098 // Some events occurred.
2099 mPendingEventCount = size_t(pollResult);
2100 }
2101 }
2102
2103 // All done, return the number of events we read.
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002104 return events;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002105}
2106
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08002107std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002108 std::scoped_lock _l(mLock);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08002109
2110 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07002111 if (device == nullptr || !device->videoDevice) {
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08002112 return {};
2113 }
2114 return device->videoDevice->consumeFrames();
2115}
2116
Michael Wrightd02c5b62014-02-10 15:10:22 -08002117void EventHub::wake() {
2118 ALOGV("wake() called");
2119
2120 ssize_t nWrite;
2121 do {
2122 nWrite = write(mWakeWritePipeFd, "W", 1);
2123 } while (nWrite == -1 && errno == EINTR);
2124
2125 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002126 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002127 }
2128}
2129
2130void EventHub::scanDevicesLocked() {
Usama Arifb27c8e62021-06-03 16:44:09 +01002131 status_t result;
2132 std::error_code errorCode;
2133
2134 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
2135 result = scanDirLocked(DEVICE_INPUT_PATH);
2136 if (result < 0) {
2137 ALOGE("scan dir failed for %s", DEVICE_INPUT_PATH);
2138 }
2139 } else {
2140 if (errorCode) {
2141 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
2142 errorCode.message().c_str());
2143 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002144 }
Philip Quinn39b81682019-01-09 22:20:39 -08002145 if (isV4lScanningEnabled()) {
Usama Arifb27c8e62021-06-03 16:44:09 +01002146 result = scanVideoDirLocked(DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08002147 if (result != OK) {
Usama Arifb27c8e62021-06-03 16:44:09 +01002148 ALOGE("scan video dir failed for %s", DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08002149 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002150 }
Chris Ye989bb932020-07-04 16:18:59 -07002151 if (mDevices.find(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) == mDevices.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002152 createVirtualKeyboardLocked();
2153 }
2154}
2155
2156// ----------------------------------------------------------------------------
2157
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002158status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002159 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002160 struct epoll_event eventItem = {};
2161 eventItem.events = EPOLLIN | EPOLLWAKEUP;
2162 eventItem.data.fd = fd;
2163 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
2164 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002165 return -errno;
2166 }
2167 return OK;
2168}
2169
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002170status_t EventHub::unregisterFdFromEpoll(int fd) {
2171 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
2172 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
2173 return -errno;
2174 }
2175 return OK;
2176}
2177
Chris Ye989bb932020-07-04 16:18:59 -07002178status_t EventHub::registerDeviceForEpollLocked(Device& device) {
2179 status_t result = registerFdForEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002180 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07002181 ALOGE("Could not add input device fd to epoll for device %" PRId32, device.id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002182 return result;
2183 }
Chris Ye989bb932020-07-04 16:18:59 -07002184 if (device.videoDevice) {
2185 registerVideoDeviceForEpollLocked(*device.videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002186 }
2187 return result;
2188}
2189
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002190void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
2191 status_t result = registerFdForEpoll(videoDevice.getFd());
2192 if (result != OK) {
2193 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
2194 }
2195}
2196
Chris Ye989bb932020-07-04 16:18:59 -07002197status_t EventHub::unregisterDeviceFromEpollLocked(Device& device) {
2198 if (device.hasValidFd()) {
2199 status_t result = unregisterFdFromEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002200 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07002201 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device.id);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002202 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002203 }
2204 }
Chris Ye989bb932020-07-04 16:18:59 -07002205 if (device.videoDevice) {
2206 unregisterVideoDeviceFromEpollLocked(*device.videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002207 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002208 return OK;
2209}
2210
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002211void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
2212 if (videoDevice.hasValidFd()) {
2213 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
2214 if (result != OK) {
2215 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002216 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002217 }
2218 }
2219}
2220
Chris Yed3fef462021-03-07 17:10:08 -08002221void EventHub::reportDeviceAddedForStatisticsLocked(const InputDeviceIdentifier& identifier,
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002222 ftl::Flags<InputDeviceClass> classes) {
Chris Ye657c2f02021-05-25 16:24:37 -07002223 SHA256_CTX ctx;
2224 SHA256_Init(&ctx);
2225 SHA256_Update(&ctx, reinterpret_cast<const uint8_t*>(identifier.uniqueId.c_str()),
2226 identifier.uniqueId.size());
2227 std::array<uint8_t, SHA256_DIGEST_LENGTH> digest;
2228 SHA256_Final(digest.data(), &ctx);
2229
2230 std::string obfuscatedId;
2231 for (size_t i = 0; i < OBFUSCATED_LENGTH; i++) {
2232 obfuscatedId += StringPrintf("%02x", digest[i]);
2233 }
2234
Chris Yed3fef462021-03-07 17:10:08 -08002235 android::util::stats_write(android::util::INPUTDEVICE_REGISTERED, identifier.name.c_str(),
2236 identifier.vendor, identifier.product, identifier.version,
Chris Ye657c2f02021-05-25 16:24:37 -07002237 identifier.bus, obfuscatedId.c_str(), classes.get());
Chris Yed3fef462021-03-07 17:10:08 -08002238}
2239
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002240void EventHub::openDeviceLocked(const std::string& devicePath) {
2241 // If an input device happens to register around the time when EventHub's constructor runs, it
2242 // is possible that the same input event node (for example, /dev/input/event3) will be noticed
2243 // in both 'inotify' callback and also in the 'scanDirLocked' pass. To prevent duplicate devices
2244 // from getting registered, ensure that this path is not already covered by an existing device.
2245 for (const auto& [deviceId, device] : mDevices) {
2246 if (device->path == devicePath) {
2247 return; // device was already registered
2248 }
2249 }
2250
Michael Wrightd02c5b62014-02-10 15:10:22 -08002251 char buffer[80];
2252
Chris Ye8594e192020-07-14 10:34:06 -07002253 ALOGV("Opening device: %s", devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002254
Chris Ye8594e192020-07-14 10:34:06 -07002255 int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002256 if (fd < 0) {
Chris Ye8594e192020-07-14 10:34:06 -07002257 ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002258 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002259 }
2260
2261 InputDeviceIdentifier identifier;
2262
2263 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002264 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Chris Ye8594e192020-07-14 10:34:06 -07002265 ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002266 } else {
2267 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002268 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002269 }
2270
2271 // Check to see if the device is on our excluded list
2272 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002273 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002274 if (identifier.name == item) {
Chris Ye8594e192020-07-14 10:34:06 -07002275 ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002276 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002277 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002278 }
2279 }
2280
2281 // Get device driver version.
2282 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002283 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Chris Ye8594e192020-07-14 10:34:06 -07002284 ALOGE("could not get driver version for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002285 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002286 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002287 }
2288
2289 // Get device identifier.
2290 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002291 if (ioctl(fd, EVIOCGID, &inputId)) {
Chris Ye8594e192020-07-14 10:34:06 -07002292 ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002293 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002294 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002295 }
2296 identifier.bus = inputId.bustype;
2297 identifier.product = inputId.product;
2298 identifier.vendor = inputId.vendor;
2299 identifier.version = inputId.version;
2300
2301 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002302 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
2303 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002304 } else {
2305 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002306 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002307 }
2308
2309 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002310 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
2311 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002312 } else {
2313 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002314 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002315 }
2316
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002317 // Attempt to get the bluetooth address of an input device from the uniqueId.
2318 if (identifier.bus == BUS_BLUETOOTH &&
2319 std::regex_match(identifier.uniqueId,
2320 std::regex("^[A-Fa-f0-9]{2}(?::[A-Fa-f0-9]{2}){5}$"))) {
2321 identifier.bluetoothAddress = identifier.uniqueId;
2322 // The Bluetooth stack requires alphabetic characters to be uppercase in a valid address.
2323 for (auto& c : *identifier.bluetoothAddress) {
2324 c = ::toupper(c);
2325 }
2326 }
2327
Michael Wrightd02c5b62014-02-10 15:10:22 -08002328 // Fill in the descriptor.
2329 assignDescriptorLocked(identifier);
2330
Michael Wrightd02c5b62014-02-10 15:10:22 -08002331 // Allocate device. (The device object takes ownership of the fd at this point.)
2332 int32_t deviceId = mNextDeviceId++;
Prabir Pradhancb42b472022-08-23 16:01:19 +00002333 std::unique_ptr<Device> device =
2334 std::make_unique<Device>(fd, deviceId, devicePath, identifier,
2335 obtainAssociatedDeviceLocked(devicePath));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002336
Chris Ye8594e192020-07-14 10:34:06 -07002337 ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002338 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002339 " vendor %04x\n"
2340 " product %04x\n"
2341 " version %04x\n",
2342 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002343 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
2344 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
2345 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
2346 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002347 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
2348 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002349
2350 // Load the configuration file for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002351 device->loadConfigurationLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002352
2353 // Figure out the kinds of events the device reports.
Chris Ye66fbac32020-07-06 20:36:43 -07002354 device->readDeviceBitMask(EVIOCGBIT(EV_KEY, 0), device->keyBitmask);
2355 device->readDeviceBitMask(EVIOCGBIT(EV_ABS, 0), device->absBitmask);
2356 device->readDeviceBitMask(EVIOCGBIT(EV_REL, 0), device->relBitmask);
2357 device->readDeviceBitMask(EVIOCGBIT(EV_SW, 0), device->swBitmask);
2358 device->readDeviceBitMask(EVIOCGBIT(EV_LED, 0), device->ledBitmask);
2359 device->readDeviceBitMask(EVIOCGBIT(EV_FF, 0), device->ffBitmask);
Chris Yef59a2f42020-10-16 12:55:26 -07002360 device->readDeviceBitMask(EVIOCGBIT(EV_MSC, 0), device->mscBitmask);
Chris Ye66fbac32020-07-06 20:36:43 -07002361 device->readDeviceBitMask(EVIOCGPROP(0), device->propBitmask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002362
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002363 // See if this is a device with keys. This could be full keyboard, or other devices like
2364 // gamepads, joysticks, and styluses with buttons that should generate key presses.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002365 bool haveKeyboardKeys =
Chris Ye66fbac32020-07-06 20:36:43 -07002366 device->keyBitmask.any(0, BTN_MISC) || device->keyBitmask.any(BTN_WHEEL, KEY_MAX + 1);
2367 bool haveGamepadButtons = device->keyBitmask.any(BTN_MISC, BTN_MOUSE) ||
2368 device->keyBitmask.any(BTN_JOYSTICK, BTN_DIGI);
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002369 bool haveStylusButtons = device->keyBitmask.test(BTN_STYLUS) ||
2370 device->keyBitmask.test(BTN_STYLUS2) || device->keyBitmask.test(BTN_STYLUS3);
2371 if (haveKeyboardKeys || haveGamepadButtons || haveStylusButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002372 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002373 }
2374
2375 // See if this is a cursor device such as a trackball or mouse.
Chris Ye66fbac32020-07-06 20:36:43 -07002376 if (device->keyBitmask.test(BTN_MOUSE) && device->relBitmask.test(REL_X) &&
2377 device->relBitmask.test(REL_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002378 device->classes |= InputDeviceClass::CURSOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002379 }
2380
Prabir Pradhana3621852022-10-14 18:57:23 +00002381 // See if the device is specially configured to be of a certain type.
Harry Cuttsf13161a2023-03-08 14:15:49 +00002382 if (device->configuration) {
2383 std::string deviceType = device->configuration->getString("device.type").value_or("");
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07002384 if (deviceType == "rotaryEncoder") {
Chris Ye1b0c7342020-07-28 21:57:03 -07002385 device->classes |= InputDeviceClass::ROTARY_ENCODER;
Prabir Pradhana3621852022-10-14 18:57:23 +00002386 } else if (deviceType == "externalStylus") {
2387 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002388 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002389 }
2390
Michael Wrightd02c5b62014-02-10 15:10:22 -08002391 // See if this is a touch pad.
2392 // Is this a new modern multi-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002393 if (device->absBitmask.test(ABS_MT_POSITION_X) && device->absBitmask.test(ABS_MT_POSITION_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002394 // Some joysticks such as the PS3 controller report axes that conflict
2395 // with the ABS_MT range. Try to confirm that the device really is
2396 // a touch screen.
Chris Ye66fbac32020-07-06 20:36:43 -07002397 if (device->keyBitmask.test(BTN_TOUCH) || !haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002398 device->classes |= (InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT);
Harry Cutts79cc9fa2022-10-28 15:32:39 +00002399 if (device->propBitmask.test(INPUT_PROP_POINTER) &&
2400 !device->keyBitmask.any(BTN_TOOL_PEN, BTN_TOOL_FINGER) && !haveStylusButtons) {
2401 device->classes |= InputDeviceClass::TOUCHPAD;
2402 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002403 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002404 // Is this an old style single-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002405 } else if (device->keyBitmask.test(BTN_TOUCH) && device->absBitmask.test(ABS_X) &&
2406 device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002407 device->classes |= InputDeviceClass::TOUCH;
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002408 // Is this a stylus that reports contact/pressure independently of touch coordinates?
Chris Ye66fbac32020-07-06 20:36:43 -07002409 } else if ((device->absBitmask.test(ABS_PRESSURE) || device->keyBitmask.test(BTN_TOUCH)) &&
2410 !device->absBitmask.test(ABS_X) && !device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002411 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002412 }
2413
2414 // See if this device is a joystick.
2415 // Assumes that joysticks always have gamepad buttons in order to distinguish them
2416 // from other devices such as accelerometers that also have absolute axes.
2417 if (haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002418 auto assumedClasses = device->classes | InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002419 for (int i = 0; i <= ABS_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002420 if (device->absBitmask.test(i) &&
Chris Ye1b0c7342020-07-28 21:57:03 -07002421 (getAbsAxisUsage(i, assumedClasses).test(InputDeviceClass::JOYSTICK))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002422 device->classes = assumedClasses;
2423 break;
2424 }
2425 }
2426 }
2427
Chris Yef59a2f42020-10-16 12:55:26 -07002428 // Check whether this device is an accelerometer.
2429 if (device->propBitmask.test(INPUT_PROP_ACCELEROMETER)) {
2430 device->classes |= InputDeviceClass::SENSOR;
2431 }
2432
Michael Wrightd02c5b62014-02-10 15:10:22 -08002433 // Check whether this device has switches.
2434 for (int i = 0; i <= SW_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002435 if (device->swBitmask.test(i)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002436 device->classes |= InputDeviceClass::SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002437 break;
2438 }
2439 }
2440
2441 // Check whether this device supports the vibrator.
Chris Ye66fbac32020-07-06 20:36:43 -07002442 if (device->ffBitmask.test(FF_RUMBLE)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002443 device->classes |= InputDeviceClass::VIBRATOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002444 }
2445
2446 // Configure virtual keys.
Chris Ye1b0c7342020-07-28 21:57:03 -07002447 if ((device->classes.test(InputDeviceClass::TOUCH))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002448 // Load the virtual keys for the touch screen, if any.
2449 // We do this now so that we can make sure to load the keymap if necessary.
Chris Ye989bb932020-07-04 16:18:59 -07002450 bool success = device->loadVirtualKeyMapLocked();
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06002451 if (success) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002452 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002453 }
2454 }
2455
2456 // Load the key map.
Chris Yef59a2f42020-10-16 12:55:26 -07002457 // We need to do this for joysticks too because the key layout may specify axes, and for
2458 // sensor as well because the key layout may specify the axes to sensor data mapping.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002459 status_t keyMapStatus = NAME_NOT_FOUND;
Chris Yef59a2f42020-10-16 12:55:26 -07002460 if (device->classes.any(InputDeviceClass::KEYBOARD | InputDeviceClass::JOYSTICK |
2461 InputDeviceClass::SENSOR)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002462 // Load the keymap for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002463 keyMapStatus = device->loadKeyMapLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002464 }
2465
2466 // Configure the keyboard, gamepad or virtual keyboard.
Chris Ye1b0c7342020-07-28 21:57:03 -07002467 if (device->classes.test(InputDeviceClass::KEYBOARD)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002468 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002469 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002470 isEligibleBuiltInKeyboard(device->identifier, device->configuration.get(),
2471 &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002472 mBuiltInKeyboardId = device->id;
2473 }
2474
2475 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
Chris Ye989bb932020-07-04 16:18:59 -07002476 if (device->hasKeycodeLocked(AKEYCODE_Q)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002477 device->classes |= InputDeviceClass::ALPHAKEY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002478 }
2479
Prabir Pradhanae10ee62023-05-12 19:44:18 +00002480 // See if this device has a D-pad.
2481 if (std::all_of(DPAD_REQUIRED_KEYCODES.begin(), DPAD_REQUIRED_KEYCODES.end(),
2482 [&](int32_t keycode) { return device->hasKeycodeLocked(keycode); })) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002483 device->classes |= InputDeviceClass::DPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002484 }
2485
2486 // See if this device has a gamepad.
Prabir Pradhanae10ee62023-05-12 19:44:18 +00002487 if (std::any_of(GAMEPAD_KEYCODES.begin(), GAMEPAD_KEYCODES.end(),
2488 [&](int32_t keycode) { return device->hasKeycodeLocked(keycode); })) {
2489 device->classes |= InputDeviceClass::GAMEPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002490 }
Prabir Pradhana3621852022-10-14 18:57:23 +00002491
2492 // See if this device has any stylus buttons that we would want to fuse with touch data.
Prabir Pradhanae10ee62023-05-12 19:44:18 +00002493 if (!device->classes.any(InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT) &&
Prabir Pradhan3c28b942023-08-18 20:02:01 +00002494 !device->classes.any(InputDeviceClass::ALPHAKEY) &&
Prabir Pradhanae10ee62023-05-12 19:44:18 +00002495 std::any_of(STYLUS_BUTTON_KEYCODES.begin(), STYLUS_BUTTON_KEYCODES.end(),
2496 [&](int32_t keycode) { return device->hasKeycodeLocked(keycode); })) {
2497 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Prabir Pradhana3621852022-10-14 18:57:23 +00002498 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002499 }
2500
2501 // If the device isn't recognized as something we handle, don't monitor it.
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002502 if (device->classes == ftl::Flags<InputDeviceClass>(0)) {
Chris Ye8594e192020-07-14 10:34:06 -07002503 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002504 device->identifier.name.c_str());
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002505 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002506 }
2507
Chris Ye3fdbfef2021-01-06 18:45:18 -08002508 // Classify InputDeviceClass::BATTERY.
Prabir Pradhan51894782022-08-23 16:29:10 +00002509 if (device->associatedDevice && !device->associatedDevice->batteryInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002510 device->classes |= InputDeviceClass::BATTERY;
2511 }
Kim Low03ea0352020-11-06 12:45:07 -08002512
Chris Ye3fdbfef2021-01-06 18:45:18 -08002513 // Classify InputDeviceClass::LIGHT.
Prabir Pradhan51894782022-08-23 16:29:10 +00002514 if (device->associatedDevice && !device->associatedDevice->lightInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002515 device->classes |= InputDeviceClass::LIGHT;
Kim Low03ea0352020-11-06 12:45:07 -08002516 }
2517
Tim Kilbourn063ff532015-04-08 10:26:18 -07002518 // Determine whether the device has a mic.
Chris Ye989bb932020-07-04 16:18:59 -07002519 if (device->deviceHasMicLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002520 device->classes |= InputDeviceClass::MIC;
Tim Kilbourn063ff532015-04-08 10:26:18 -07002521 }
2522
Michael Wrightd02c5b62014-02-10 15:10:22 -08002523 // Determine whether the device is external or internal.
Chris Ye989bb932020-07-04 16:18:59 -07002524 if (device->isExternalDeviceLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002525 device->classes |= InputDeviceClass::EXTERNAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002526 }
2527
Chris Ye1b0c7342020-07-28 21:57:03 -07002528 if (device->classes.any(InputDeviceClass::JOYSTICK | InputDeviceClass::DPAD) &&
2529 device->classes.test(InputDeviceClass::GAMEPAD)) {
Chris Ye989bb932020-07-04 16:18:59 -07002530 device->controllerNumber = getNextControllerNumberLocked(device->identifier.name);
2531 device->setLedForControllerLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002532 }
2533
Chris Ye989bb932020-07-04 16:18:59 -07002534 if (registerDeviceForEpollLocked(*device) != OK) {
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002535 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002536 }
2537
Chris Ye989bb932020-07-04 16:18:59 -07002538 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002539
Chris Ye1b0c7342020-07-28 21:57:03 -07002540 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=%s, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002541 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Chris Ye1b0c7342020-07-28 21:57:03 -07002542 deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(),
2543 device->classes.string().c_str(), device->configurationFile.c_str(),
2544 device->keyMap.keyLayoutFile.c_str(), device->keyMap.keyCharacterMapFile.c_str(),
2545 toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002546
Chris Ye989bb932020-07-04 16:18:59 -07002547 addDeviceLocked(std::move(device));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002548}
2549
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002550void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
2551 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
2552 if (!videoDevice) {
2553 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
2554 return;
2555 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002556 // Transfer ownership of this video device to a matching input device
Chris Ye989bb932020-07-04 16:18:59 -07002557 for (const auto& [id, device] : mDevices) {
Chris Yed3fef462021-03-07 17:10:08 -08002558 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002559 return; // 'device' now owns 'videoDevice'
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002560 }
2561 }
2562
2563 // Couldn't find a matching input device, so just add it to a temporary holding queue.
2564 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002565 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002566 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002567 mUnattachedVideoDevices.push_back(std::move(videoDevice));
2568}
2569
Chris Yed3fef462021-03-07 17:10:08 -08002570bool EventHub::tryAddVideoDeviceLocked(EventHub::Device& device,
2571 std::unique_ptr<TouchVideoDevice>& videoDevice) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002572 if (videoDevice->getName() != device.identifier.name) {
2573 return false;
2574 }
2575 device.videoDevice = std::move(videoDevice);
2576 if (device.enabled) {
2577 registerVideoDeviceForEpollLocked(*device.videoDevice);
2578 }
2579 return true;
2580}
2581
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002582bool EventHub::isDeviceEnabled(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00002583 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002584 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002585 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002586 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2587 return false;
2588 }
2589 return device->enabled;
2590}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002591
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002592status_t EventHub::enableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002593 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002594 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002595 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002596 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2597 return BAD_VALUE;
2598 }
2599 if (device->enabled) {
2600 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
2601 return OK;
2602 }
2603 status_t result = device->enable();
2604 if (result != OK) {
2605 ALOGE("Failed to enable device %" PRId32, deviceId);
2606 return result;
2607 }
2608
Chris Ye989bb932020-07-04 16:18:59 -07002609 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002610
Chris Ye989bb932020-07-04 16:18:59 -07002611 return registerDeviceForEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002612}
2613
2614status_t EventHub::disableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002615 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002616 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002617 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002618 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2619 return BAD_VALUE;
2620 }
2621 if (!device->enabled) {
2622 ALOGW("Duplicate call to %s, input device already disabled", __func__);
2623 return OK;
2624 }
Chris Ye989bb932020-07-04 16:18:59 -07002625 unregisterDeviceFromEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002626 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002627}
2628
Vaibhav Devmurari5fc7d852023-03-17 18:43:33 +00002629// TODO(b/274755573): Shift to uevent handling on native side and remove this method
2630// Currently using Java UEventObserver to trigger this which uses UEvent infrastructure that uses a
2631// NETLINK socket to observe UEvents. We can create similar infrastructure on Eventhub side to
2632// directly observe UEvents instead of triggering from Java side.
2633void EventHub::sysfsNodeChanged(const std::string& sysfsNodePath) {
2634 std::scoped_lock _l(mLock);
2635
2636 // Check in opening devices
2637 for (auto it = mOpeningDevices.begin(); it != mOpeningDevices.end(); it++) {
2638 std::unique_ptr<Device>& device = *it;
2639 if (device->associatedDevice &&
2640 sysfsNodePath.find(device->associatedDevice->sysfsRootPath.string()) !=
2641 std::string::npos &&
2642 device->associatedDevice->isChanged()) {
2643 it = mOpeningDevices.erase(it);
2644 openDeviceLocked(device->path);
2645 }
2646 }
2647
2648 // Check in already added device
2649 std::vector<Device*> devicesToReopen;
2650 for (const auto& [id, device] : mDevices) {
2651 if (device->associatedDevice &&
2652 sysfsNodePath.find(device->associatedDevice->sysfsRootPath.string()) !=
2653 std::string::npos &&
2654 device->associatedDevice->isChanged()) {
2655 devicesToReopen.push_back(device.get());
2656 }
2657 }
2658 for (const auto& device : devicesToReopen) {
2659 closeDeviceLocked(*device);
2660 openDeviceLocked(device->path);
2661 }
2662 devicesToReopen.clear();
2663}
2664
Michael Wrightd02c5b62014-02-10 15:10:22 -08002665void EventHub::createVirtualKeyboardLocked() {
2666 InputDeviceIdentifier identifier;
2667 identifier.name = "Virtual";
2668 identifier.uniqueId = "<virtual>";
2669 assignDescriptorLocked(identifier);
2670
Chris Ye989bb932020-07-04 16:18:59 -07002671 std::unique_ptr<Device> device =
2672 std::make_unique<Device>(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
Harry Cutts33476232023-01-30 19:57:29 +00002673 identifier, /*associatedDevice=*/nullptr);
Chris Ye1b0c7342020-07-28 21:57:03 -07002674 device->classes = InputDeviceClass::KEYBOARD | InputDeviceClass::ALPHAKEY |
2675 InputDeviceClass::DPAD | InputDeviceClass::VIRTUAL;
Chris Ye989bb932020-07-04 16:18:59 -07002676 device->loadKeyMapLocked();
2677 addDeviceLocked(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002678}
2679
Chris Ye989bb932020-07-04 16:18:59 -07002680void EventHub::addDeviceLocked(std::unique_ptr<Device> device) {
Chris Yed3fef462021-03-07 17:10:08 -08002681 reportDeviceAddedForStatisticsLocked(device->identifier, device->classes);
Chris Ye989bb932020-07-04 16:18:59 -07002682 mOpeningDevices.push_back(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002683}
2684
Chris Ye989bb932020-07-04 16:18:59 -07002685int32_t EventHub::getNextControllerNumberLocked(const std::string& name) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002686 if (mControllerNumbers.isFull()) {
2687 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Chris Ye989bb932020-07-04 16:18:59 -07002688 name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002689 return 0;
2690 }
2691 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
2692 // one
2693 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
2694}
2695
Chris Ye989bb932020-07-04 16:18:59 -07002696void EventHub::releaseControllerNumberLocked(int32_t num) {
2697 if (num > 0) {
2698 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002699 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002700}
2701
Chris Ye8594e192020-07-14 10:34:06 -07002702void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002703 Device* device = getDeviceByPathLocked(devicePath);
Chris Ye989bb932020-07-04 16:18:59 -07002704 if (device != nullptr) {
2705 closeDeviceLocked(*device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002706 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002707 }
Chris Ye8594e192020-07-14 10:34:06 -07002708 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002709}
2710
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002711/**
2712 * Find the video device by filename, and close it.
2713 * The video device is closed by path during an inotify event, where we don't have the
2714 * additional context about the video device fd, or the associated input device.
2715 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002716void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002717 // A video device may be owned by an existing input device, or it may be stored in
2718 // the mUnattachedVideoDevices queue. Check both locations.
Chris Ye989bb932020-07-04 16:18:59 -07002719 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002720 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002721 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002722 device->videoDevice = nullptr;
2723 return;
2724 }
2725 }
Siarhei Vishniakouf47c339e2021-12-30 11:22:26 -08002726 std::erase_if(mUnattachedVideoDevices,
2727 [&devicePath](const std::unique_ptr<TouchVideoDevice>& videoDevice) {
2728 return videoDevice->getPath() == devicePath;
2729 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08002730}
2731
2732void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002733 mUnattachedVideoDevices.clear();
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002734 while (!mDevices.empty()) {
2735 closeDeviceLocked(*(mDevices.begin()->second));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002736 }
2737}
2738
Chris Ye989bb932020-07-04 16:18:59 -07002739void EventHub::closeDeviceLocked(Device& device) {
2740 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=%s", device.path.c_str(),
2741 device.identifier.name.c_str(), device.id, device.fd, device.classes.string().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002742
Chris Ye989bb932020-07-04 16:18:59 -07002743 if (device.id == mBuiltInKeyboardId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002744 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Chris Ye989bb932020-07-04 16:18:59 -07002745 device.path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002746 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
2747 }
2748
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002749 unregisterDeviceFromEpollLocked(device);
Chris Ye989bb932020-07-04 16:18:59 -07002750 if (device.videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002751 // This must be done after the video device is removed from epoll
Chris Ye989bb932020-07-04 16:18:59 -07002752 mUnattachedVideoDevices.push_back(std::move(device.videoDevice));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002753 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002754
Chris Ye989bb932020-07-04 16:18:59 -07002755 releaseControllerNumberLocked(device.controllerNumber);
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002756 device.controllerNumber = 0;
Chris Ye989bb932020-07-04 16:18:59 -07002757 device.close();
Chris Ye989bb932020-07-04 16:18:59 -07002758 mClosingDevices.push_back(std::move(mDevices[device.id]));
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002759
Chris Ye989bb932020-07-04 16:18:59 -07002760 mDevices.erase(device.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002761}
2762
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002763base::Result<void> EventHub::readNotifyLocked() {
2764 static constexpr auto EVENT_SIZE = static_cast<ssize_t>(sizeof(inotify_event));
2765 uint8_t eventBuffer[512];
2766 ssize_t sizeRead;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002767
2768 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002769 do {
2770 sizeRead = read(mINotifyFd, eventBuffer, sizeof(eventBuffer));
2771 } while (sizeRead < 0 && errno == EINTR);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002772
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002773 if (sizeRead < EVENT_SIZE) return Errorf("could not get event, %s", strerror(errno));
2774
2775 for (ssize_t eventPos = 0; sizeRead >= EVENT_SIZE;) {
2776 const inotify_event* event;
2777 event = (const inotify_event*)(eventBuffer + eventPos);
2778 if (event->len == 0) continue;
2779
2780 handleNotifyEventLocked(*event);
2781
2782 const ssize_t eventSize = EVENT_SIZE + event->len;
2783 sizeRead -= eventSize;
2784 eventPos += eventSize;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002785 }
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002786 return {};
2787}
2788
2789void EventHub::handleNotifyEventLocked(const inotify_event& event) {
2790 if (event.wd == mDeviceInputWd) {
2791 std::string filename = std::string(DEVICE_INPUT_PATH) + "/" + event.name;
2792 if (event.mask & IN_CREATE) {
2793 openDeviceLocked(filename);
2794 } else {
2795 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
2796 closeDeviceByPathLocked(filename);
2797 }
2798 } else if (event.wd == mDeviceWd) {
2799 if (isV4lTouchNode(event.name)) {
2800 std::string filename = std::string(DEVICE_PATH) + "/" + event.name;
2801 if (event.mask & IN_CREATE) {
2802 openVideoDeviceLocked(filename);
2803 } else {
2804 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
2805 closeVideoDeviceByPathLocked(filename);
2806 }
2807 } else if (strcmp(event.name, "input") == 0 && event.mask & IN_CREATE) {
2808 addDeviceInputInotify();
2809 }
2810 } else {
2811 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event.wd);
2812 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002813}
2814
Chris Ye8594e192020-07-14 10:34:06 -07002815status_t EventHub::scanDirLocked(const std::string& dirname) {
2816 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2817 openDeviceLocked(entry.path());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002818 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002819 return 0;
2820}
2821
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002822/**
2823 * Look for all dirname/v4l-touch* devices, and open them.
2824 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002825status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Chris Ye8594e192020-07-14 10:34:06 -07002826 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2827 if (isV4lTouchNode(entry.path())) {
2828 ALOGI("Found touch video device %s", entry.path().c_str());
2829 openVideoDeviceLocked(entry.path());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002830 }
2831 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002832 return OK;
2833}
2834
Michael Wrightd02c5b62014-02-10 15:10:22 -08002835void EventHub::requestReopenDevices() {
2836 ALOGV("requestReopenDevices() called");
2837
Chris Ye87143712020-11-10 05:05:58 +00002838 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002839 mNeedToReopenDevices = true;
2840}
2841
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002842void EventHub::dump(std::string& dump) const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002843 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002844
2845 { // acquire lock
Chris Ye87143712020-11-10 05:05:58 +00002846 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002847
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002848 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002849
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002850 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002851
Chris Ye989bb932020-07-04 16:18:59 -07002852 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002853 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002854 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002855 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002856 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002857 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002858 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002859 }
Chris Ye1b0c7342020-07-28 21:57:03 -07002860 dump += StringPrintf(INDENT3 "Classes: %s\n", device->classes.string().c_str());
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002861 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002862 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002863 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
2864 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002865 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002866 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002867 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002868 "product=0x%04x, version=0x%04x, bluetoothAddress=%s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002869 device->identifier.bus, device->identifier.vendor,
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002870 device->identifier.product, device->identifier.version,
2871 toString(device->identifier.bluetoothAddress).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002872 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002873 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002874 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002875 device->keyMap.keyCharacterMapFile.c_str());
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00002876 if (device->associatedDevice && device->associatedDevice->layoutInfo) {
2877 dump += StringPrintf(INDENT3 "LanguageTag: %s\n",
2878 device->associatedDevice->layoutInfo->languageTag.c_str());
2879 dump += StringPrintf(INDENT3 "LayoutType: %s\n",
2880 device->associatedDevice->layoutInfo->layoutType.c_str());
2881 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002882 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002883 device->configurationFile.c_str());
Prabir Pradhan51894782022-08-23 16:29:10 +00002884 dump += StringPrintf(INDENT3 "VideoDevice: %s\n",
2885 device->videoDevice ? device->videoDevice->dump().c_str()
2886 : "<none>");
2887 dump += StringPrintf(INDENT3 "SysfsDevicePath: %s\n",
2888 device->associatedDevice
2889 ? device->associatedDevice->sysfsRootPath.c_str()
2890 : "<none>");
Prabir Pradhan955b6132023-07-14 19:44:34 +00002891 if (device->keyBitmask.any(0, KEY_MAX + 1)) {
2892 const auto pressedKeys = device->keyState.dumpSetIndices(", ", [](int i) {
2893 return InputEventLookup::getLinuxEvdevLabel(EV_KEY, i, 1).code;
2894 });
2895 dump += StringPrintf(INDENT3 "KeyState (pressed): %s\n", pressedKeys.c_str());
2896 }
2897 if (device->swBitmask.any(0, SW_MAX + 1)) {
2898 const auto pressedSwitches = device->swState.dumpSetIndices(", ", [](int i) {
2899 return InputEventLookup::getLinuxEvdevLabel(EV_SW, i, 1).code;
2900 });
2901 dump += StringPrintf(INDENT3 "SwState (pressed): %s\n", pressedSwitches.c_str());
2902 }
2903 if (!device->absState.empty()) {
2904 std::string axisValues;
2905 for (const auto& [axis, state] : device->absState) {
2906 if (!axisValues.empty()) {
2907 axisValues += ", ";
2908 }
2909 axisValues += StringPrintf("%s=%d",
2910 InputEventLookup::getLinuxEvdevLabel(EV_ABS, axis, 0)
2911 .code.c_str(),
2912 state.value);
2913 }
2914 dump += INDENT3 "AbsState: " + axisValues + "\n";
2915 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002916 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002917
2918 dump += INDENT "Unattached video devices:\n";
2919 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
2920 dump += INDENT2 + videoDevice->dump() + "\n";
2921 }
2922 if (mUnattachedVideoDevices.empty()) {
2923 dump += INDENT2 "<none>\n";
2924 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002925 } // release lock
2926}
2927
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002928void EventHub::monitor() const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002929 // Acquire and release the lock to ensure that the event hub has not deadlocked.
Chris Ye1c2e0892020-11-30 21:41:44 -08002930 std::unique_lock<std::mutex> lock(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002931}
2932
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00002933std::string EventHub::AssociatedDevice::dump() const {
2934 return StringPrintf("path=%s, numBatteries=%zu, numLight=%zu", sysfsRootPath.c_str(),
2935 batteryInfos.size(), lightInfos.size());
2936}
2937
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002938} // namespace android