blob: fe70a51b81c889ad73d3419c66b35276d6d83675 [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
1001status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001002 RawAbsoluteAxisInfo* outAxisInfo) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001003 outAxisInfo->clear();
Arpit Singh77140f42023-06-13 11:35:27 +00001004 if (axis < 0 || axis > ABS_MAX) {
Prabir Pradhan341d0782023-07-14 19:04:10 +00001005 return NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001006 }
Arpit Singh77140f42023-06-13 11:35:27 +00001007 std::scoped_lock _l(mLock);
Prabir Pradhan341d0782023-07-14 19:04:10 +00001008 const Device* device = getDeviceLocked(deviceId);
Arpit Singh77140f42023-06-13 11:35:27 +00001009 if (device == nullptr) {
Prabir Pradhan341d0782023-07-14 19:04:10 +00001010 return NAME_NOT_FOUND;
Arpit Singh77140f42023-06-13 11:35:27 +00001011 }
Prabir Pradhan341d0782023-07-14 19:04:10 +00001012 // We can read the RawAbsoluteAxisInfo even if the device is disabled and doesn't have a valid
1013 // fd, because the info is populated once when the device is first opened, and it doesn't change
1014 // throughout the device lifecycle.
1015 auto it = device->absState.find(axis);
1016 if (it == device->absState.end()) {
1017 return NAME_NOT_FOUND;
Arpit Singh77140f42023-06-13 11:35:27 +00001018 }
Prabir Pradhan341d0782023-07-14 19:04:10 +00001019 *outAxisInfo = it->second.info;
Arpit Singh77140f42023-06-13 11:35:27 +00001020 return OK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001021}
1022
1023bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
1024 if (axis >= 0 && axis <= REL_MAX) {
Chris Ye87143712020-11-10 05:05:58 +00001025 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001027 return device != nullptr ? device->relBitmask.test(axis) : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001028 }
1029 return false;
1030}
1031
1032bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
Chris Ye87143712020-11-10 05:05:58 +00001033 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001034
Chris Ye989bb932020-07-04 16:18:59 -07001035 Device* device = getDeviceLocked(deviceId);
1036 return property >= 0 && property <= INPUT_PROP_MAX && device != nullptr
1037 ? device->propBitmask.test(property)
1038 : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001039}
1040
Chris Yef59a2f42020-10-16 12:55:26 -07001041bool EventHub::hasMscEvent(int32_t deviceId, int mscEvent) const {
1042 std::scoped_lock _l(mLock);
1043
1044 Device* device = getDeviceLocked(deviceId);
1045 return mscEvent >= 0 && mscEvent <= MSC_MAX && device != nullptr
1046 ? device->mscBitmask.test(mscEvent)
1047 : false;
1048}
1049
Michael Wrightd02c5b62014-02-10 15:10:22 -08001050int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001051 if (scanCode < 0 || scanCode > KEY_MAX) {
1052 return AKEY_STATE_UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001053 }
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001054 std::scoped_lock _l(mLock);
1055 const Device* device = getDeviceLocked(deviceId);
1056 if (device == nullptr || !device->hasValidFd() || !device->keyBitmask.test(scanCode)) {
1057 return AKEY_STATE_UNKNOWN;
1058 }
1059 return device->keyState.test(scanCode) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001060}
1061
1062int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
Chris Ye87143712020-11-10 05:05:58 +00001063 std::scoped_lock _l(mLock);
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001064 const Device* device = getDeviceLocked(deviceId);
1065 if (device == nullptr || !device->hasValidFd() || !device->keyMap.haveKeyLayout()) {
1066 return AKEY_STATE_UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001067 }
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001068 const std::vector<int32_t> scanCodes =
1069 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode);
1070 if (scanCodes.empty()) {
1071 return AKEY_STATE_UNKNOWN;
1072 }
1073 return std::any_of(scanCodes.begin(), scanCodes.end(),
1074 [&device](const int32_t sc) {
1075 return sc >= 0 && sc <= KEY_MAX && device->keyState.test(sc);
1076 })
1077 ? AKEY_STATE_DOWN
1078 : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001079}
1080
Philip Junker4af3b3d2021-12-14 10:36:55 +01001081int32_t EventHub::getKeyCodeForKeyLocation(int32_t deviceId, int32_t locationKeyCode) const {
1082 std::scoped_lock _l(mLock);
1083
1084 Device* device = getDeviceLocked(deviceId);
1085 if (device == nullptr || !device->hasValidFd() || device->keyMap.keyCharacterMap == nullptr ||
1086 device->keyMap.keyLayoutMap == nullptr) {
1087 return AKEYCODE_UNKNOWN;
1088 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001089 std::vector<int32_t> scanCodes =
1090 device->keyMap.keyLayoutMap->findScanCodesForKey(locationKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +01001091 if (scanCodes.empty()) {
1092 ALOGW("Failed to get key code for key location: no scan code maps to key code %d for input"
1093 "device %d",
1094 locationKeyCode, deviceId);
1095 return AKEYCODE_UNKNOWN;
1096 }
1097 if (scanCodes.size() > 1) {
1098 ALOGW("Multiple scan codes map to the same key code %d, returning only the first match",
1099 locationKeyCode);
1100 }
1101 int32_t outKeyCode;
1102 status_t mapKeyRes =
Harry Cutts33476232023-01-30 19:57:29 +00001103 device->getKeyCharacterMap()->mapKey(scanCodes[0], /*usageCode=*/0, &outKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +01001104 switch (mapKeyRes) {
1105 case OK:
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001106 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +01001107 case NAME_NOT_FOUND:
1108 // key character map doesn't re-map this scanCode, hence the keyCode remains the same
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001109 outKeyCode = locationKeyCode;
1110 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +01001111 default:
1112 ALOGW("Failed to get key code for key location: Key character map returned error %s",
1113 statusToString(mapKeyRes).c_str());
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001114 outKeyCode = AKEYCODE_UNKNOWN;
1115 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +01001116 }
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001117 // Remap if there is a Key remapping added to the KCM and return the remapped key
1118 return device->getKeyCharacterMap()->applyKeyRemapping(outKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +01001119}
1120
Michael Wrightd02c5b62014-02-10 15:10:22 -08001121int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001122 if (sw < 0 || sw > SW_MAX) {
1123 return AKEY_STATE_UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001124 }
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001125 std::scoped_lock _l(mLock);
1126 const Device* device = getDeviceLocked(deviceId);
1127 if (device == nullptr || !device->hasValidFd() || !device->swBitmask.test(sw)) {
1128 return AKEY_STATE_UNKNOWN;
1129 }
1130 return device->swState.test(sw) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001131}
1132
1133status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
1134 *outValue = 0;
Prabir Pradhan341d0782023-07-14 19:04:10 +00001135 if (axis < 0 || axis > ABS_MAX) {
1136 return NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001137 }
Prabir Pradhan341d0782023-07-14 19:04:10 +00001138 std::scoped_lock _l(mLock);
1139 const Device* device = getDeviceLocked(deviceId);
1140 if (device == nullptr || !device->hasValidFd()) {
1141 return NAME_NOT_FOUND;
1142 }
1143 const auto it = device->absState.find(axis);
1144 if (it == device->absState.end()) {
1145 return NAME_NOT_FOUND;
1146 }
1147 *outValue = it->second.value;
1148 return OK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001149}
1150
Arpit Singh4b4a4572023-11-24 18:19:56 +00001151base::Result<std::vector<int32_t>> EventHub::getMtSlotValues(int32_t deviceId, int32_t axis,
1152 size_t slotCount) const {
1153 std::scoped_lock _l(mLock);
1154 const Device* device = getDeviceLocked(deviceId);
1155 if (device == nullptr || !device->hasValidFd() || !device->absBitmask.test(axis)) {
1156 return base::ResultError("device problem or axis not supported", NAME_NOT_FOUND);
1157 }
1158 std::vector<int32_t> outValues(slotCount + 1);
1159 outValues[0] = axis;
1160 const size_t bufferSize = outValues.size() * sizeof(int32_t);
1161 if (ioctl(device->fd, EVIOCGMTSLOTS(bufferSize), outValues.data()) != OK) {
1162 return base::ErrnoError();
1163 }
1164 return std::move(outValues);
1165}
1166
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001167bool EventHub::markSupportedKeyCodes(int32_t deviceId, const std::vector<int32_t>& keyCodes,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001168 uint8_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +00001169 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001170
1171 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001172 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001173 for (size_t codeIndex = 0; codeIndex < keyCodes.size(); codeIndex++) {
Sergej Salnikove5420e72023-05-11 11:52:54 +00001174 if (device->hasKeycodeLocked(keyCodes[codeIndex])) {
1175 outFlags[codeIndex] = 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001176 }
1177 }
1178 return true;
1179 }
1180 return false;
1181}
1182
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001183void EventHub::addKeyRemapping(int32_t deviceId, int32_t fromKeyCode, int32_t toKeyCode) const {
1184 std::scoped_lock _l(mLock);
1185 Device* device = getDeviceLocked(deviceId);
1186 if (device == nullptr) {
1187 return;
1188 }
1189 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
1190 if (kcm) {
1191 kcm->addKeyRemapping(fromKeyCode, toKeyCode);
1192 }
1193}
1194
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001195status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
1196 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +00001197 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001198 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001199 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001200
Chris Ye66fbac32020-07-06 20:36:43 -07001201 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001202 // Check the key character map first.
Chris Ye3a1e4462020-08-12 10:13:15 -07001203 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
1204 if (kcm) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001205 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
1206 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001207 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001208 }
1209 }
1210
1211 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001212 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -08001213 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001214 status = NO_ERROR;
1215 }
1216 }
1217
1218 if (status == NO_ERROR) {
Chris Ye3a1e4462020-08-12 10:13:15 -07001219 if (kcm) {
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001220 // Remap keys based on user-defined key remappings and key behavior defined in the
1221 // corresponding kcm file
1222 *outKeycode = kcm->applyKeyRemapping(*outKeycode);
1223
1224 // Remap keys based on Key behavior defined in KCM file
1225 std::tie(*outKeycode, *outMetaState) =
1226 kcm->applyKeyBehavior(*outKeycode, metaState);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001227 } else {
1228 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001229 }
1230 }
1231 }
1232
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001233 if (status != NO_ERROR) {
1234 *outKeycode = 0;
1235 *outFlags = 0;
1236 *outMetaState = metaState;
1237 }
1238
1239 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001240}
1241
1242status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
Chris Ye87143712020-11-10 05:05:58 +00001243 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001244 Device* device = getDeviceLocked(deviceId);
1245
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001246 if (device == nullptr || !device->keyMap.haveKeyLayout()) {
1247 return NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001248 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001249 std::optional<AxisInfo> info = device->keyMap.keyLayoutMap->mapAxis(scanCode);
1250 if (!info.has_value()) {
1251 return NAME_NOT_FOUND;
1252 }
1253 *outAxisInfo = *info;
1254 return NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001255}
1256
Chris Yef59a2f42020-10-16 12:55:26 -07001257base::Result<std::pair<InputDeviceSensorType, int32_t>> EventHub::mapSensor(int32_t deviceId,
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001258 int32_t absCode) const {
Chris Yef59a2f42020-10-16 12:55:26 -07001259 std::scoped_lock _l(mLock);
1260 Device* device = getDeviceLocked(deviceId);
1261
1262 if (device != nullptr && device->keyMap.haveKeyLayout()) {
1263 return device->keyMap.keyLayoutMap->mapSensor(absCode);
1264 }
1265 return Errorf("Device not found or device has no key layout.");
1266}
1267
Chris Yee2b1e5c2021-03-10 22:45:12 -08001268// Gets the battery info map from battery ID to RawBatteryInfo of the miscellaneous device
1269// associated with the device ID. Returns an empty map if no miscellaneous device found.
1270const std::unordered_map<int32_t, RawBatteryInfo>& EventHub::getBatteryInfoLocked(
1271 int32_t deviceId) const {
1272 static const std::unordered_map<int32_t, RawBatteryInfo> EMPTY_BATTERY_INFO = {};
1273 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001274 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001275 return EMPTY_BATTERY_INFO;
1276 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001277 return device->associatedDevice->batteryInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001278}
1279
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001280std::vector<int32_t> EventHub::getRawBatteryIds(int32_t deviceId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001281 std::scoped_lock _l(mLock);
1282 std::vector<int32_t> batteryIds;
1283
Prabir Pradhan51894782022-08-23 16:29:10 +00001284 for (const auto& [id, info] : getBatteryInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001285 batteryIds.push_back(id);
1286 }
1287
1288 return batteryIds;
1289}
1290
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001291std::optional<RawBatteryInfo> EventHub::getRawBatteryInfo(int32_t deviceId,
1292 int32_t batteryId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001293 std::scoped_lock _l(mLock);
1294
1295 const auto infos = getBatteryInfoLocked(deviceId);
1296
1297 auto it = infos.find(batteryId);
1298 if (it != infos.end()) {
1299 return it->second;
1300 }
1301
1302 return std::nullopt;
1303}
1304
1305// Gets the light info map from light ID to RawLightInfo of the miscellaneous device associated
Prabir Pradhan51894782022-08-23 16:29:10 +00001306// with the device ID. Returns an empty map if no miscellaneous device found.
Chris Yee2b1e5c2021-03-10 22:45:12 -08001307const std::unordered_map<int32_t, RawLightInfo>& EventHub::getLightInfoLocked(
1308 int32_t deviceId) const {
1309 static const std::unordered_map<int32_t, RawLightInfo> EMPTY_LIGHT_INFO = {};
1310 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001311 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001312 return EMPTY_LIGHT_INFO;
1313 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001314 return device->associatedDevice->lightInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001315}
1316
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001317std::vector<int32_t> EventHub::getRawLightIds(int32_t deviceId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001318 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001319 std::vector<int32_t> lightIds;
1320
Prabir Pradhan51894782022-08-23 16:29:10 +00001321 for (const auto& [id, info] : getLightInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001322 lightIds.push_back(id);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001323 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001324
Chris Ye3fdbfef2021-01-06 18:45:18 -08001325 return lightIds;
1326}
1327
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001328std::optional<RawLightInfo> EventHub::getRawLightInfo(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001329 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001330
Chris Yee2b1e5c2021-03-10 22:45:12 -08001331 const auto infos = getLightInfoLocked(deviceId);
1332
1333 auto it = infos.find(lightId);
1334 if (it != infos.end()) {
1335 return it->second;
Chris Ye3fdbfef2021-01-06 18:45:18 -08001336 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001337
Chris Ye3fdbfef2021-01-06 18:45:18 -08001338 return std::nullopt;
1339}
1340
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001341std::optional<int32_t> EventHub::getLightBrightness(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001342 std::scoped_lock _l(mLock);
1343
Chris Yee2b1e5c2021-03-10 22:45:12 -08001344 const auto infos = getLightInfoLocked(deviceId);
1345 auto it = infos.find(lightId);
1346 if (it == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001347 return std::nullopt;
1348 }
1349 std::string buffer;
1350 if (!base::ReadFileToString(it->second.path / LIGHT_NODES.at(InputLightClass::BRIGHTNESS),
1351 &buffer)) {
1352 return std::nullopt;
1353 }
1354 return std::stoi(buffer);
1355}
1356
1357std::optional<std::unordered_map<LightColor, int32_t>> EventHub::getLightIntensities(
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001358 int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001359 std::scoped_lock _l(mLock);
1360
Chris Yee2b1e5c2021-03-10 22:45:12 -08001361 const auto infos = getLightInfoLocked(deviceId);
1362 auto lightIt = infos.find(lightId);
1363 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001364 return std::nullopt;
1365 }
1366
1367 auto ret =
1368 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1369
1370 if (!ret.has_value()) {
1371 return std::nullopt;
1372 }
1373 std::array<LightColor, COLOR_NUM> colors = ret.value();
1374
1375 std::string intensityStr;
1376 if (!base::ReadFileToString(lightIt->second.path /
1377 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY),
1378 &intensityStr)) {
1379 return std::nullopt;
1380 }
1381
1382 // Intensity node outputs 3 color values
1383 std::regex intensityPattern("([0-9]+)\\s([0-9]+)\\s([0-9]+)[\\n]");
1384 std::smatch results;
1385
1386 if (!std::regex_match(intensityStr, results, intensityPattern)) {
1387 return std::nullopt;
1388 }
1389 std::unordered_map<LightColor, int32_t> intensities;
1390 for (size_t i = 1; i < results.size(); i++) {
1391 int value = std::stoi(results[i].str());
1392 intensities.emplace(colors[i - 1], value);
1393 }
1394 return intensities;
1395}
1396
1397void EventHub::setLightBrightness(int32_t deviceId, int32_t lightId, int32_t brightness) {
1398 std::scoped_lock _l(mLock);
1399
Chris Yee2b1e5c2021-03-10 22:45:12 -08001400 const auto infos = getLightInfoLocked(deviceId);
1401 auto lightIt = infos.find(lightId);
1402 if (lightIt == infos.end()) {
1403 ALOGE("%s lightId %d not found ", __func__, lightId);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001404 return;
1405 }
1406
1407 if (!base::WriteStringToFile(std::to_string(brightness),
1408 lightIt->second.path /
1409 LIGHT_NODES.at(InputLightClass::BRIGHTNESS))) {
1410 ALOGE("Can not write to file, error: %s", strerror(errno));
1411 }
1412}
1413
1414void EventHub::setLightIntensities(int32_t deviceId, int32_t lightId,
1415 std::unordered_map<LightColor, int32_t> intensities) {
1416 std::scoped_lock _l(mLock);
1417
Chris Yee2b1e5c2021-03-10 22:45:12 -08001418 const auto infos = getLightInfoLocked(deviceId);
1419 auto lightIt = infos.find(lightId);
1420 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001421 ALOGE("Light Id %d does not exist.", lightId);
1422 return;
1423 }
1424
1425 auto ret =
1426 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1427
1428 if (!ret.has_value()) {
1429 return;
1430 }
1431 std::array<LightColor, COLOR_NUM> colors = ret.value();
1432
1433 std::string rgbStr;
1434 for (size_t i = 0; i < COLOR_NUM; i++) {
1435 auto it = intensities.find(colors[i]);
1436 if (it != intensities.end()) {
1437 rgbStr += std::to_string(it->second);
1438 // Insert space between colors
1439 if (i < COLOR_NUM - 1) {
1440 rgbStr += " ";
1441 }
1442 }
1443 }
1444 // Append new line
1445 rgbStr += "\n";
1446
1447 if (!base::WriteStringToFile(rgbStr,
1448 lightIt->second.path /
1449 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY))) {
1450 ALOGE("Can not write to file, error: %s", strerror(errno));
1451 }
1452}
1453
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001454std::optional<RawLayoutInfo> EventHub::getRawLayoutInfo(int32_t deviceId) const {
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001455 std::scoped_lock _l(mLock);
1456 Device* device = getDeviceLocked(deviceId);
1457 if (device == nullptr || !device->associatedDevice) {
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001458 return std::nullopt;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001459 }
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001460 return device->associatedDevice->layoutInfo;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001461}
1462
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001463void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Chris Ye87143712020-11-10 05:05:58 +00001464 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001465
1466 mExcludedDevices = devices;
1467}
1468
1469bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
Chris Ye87143712020-11-10 05:05:58 +00001470 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001471 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001472 if (device != nullptr && scanCode >= 0 && scanCode <= KEY_MAX) {
1473 return device->keyBitmask.test(scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001474 }
1475 return false;
1476}
1477
Arthur Hungcb40a002021-08-03 14:31:01 +00001478bool EventHub::hasKeyCode(int32_t deviceId, int32_t keyCode) const {
1479 std::scoped_lock _l(mLock);
1480 Device* device = getDeviceLocked(deviceId);
1481 if (device != nullptr) {
1482 return device->hasKeycodeLocked(keyCode);
1483 }
1484 return false;
1485}
1486
Michael Wrightd02c5b62014-02-10 15:10:22 -08001487bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
Chris Ye87143712020-11-10 05:05:58 +00001488 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001489 Device* device = getDeviceLocked(deviceId);
1490 int32_t sc;
Chris Ye989bb932020-07-04 16:18:59 -07001491 if (device != nullptr && device->mapLed(led, &sc) == NO_ERROR) {
Chris Ye66fbac32020-07-06 20:36:43 -07001492 return device->ledBitmask.test(sc);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001493 }
1494 return false;
1495}
1496
1497void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
Chris Ye87143712020-11-10 05:05:58 +00001498 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001499 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -07001500 if (device != nullptr && device->hasValidFd()) {
1501 device->setLedStateLocked(led, on);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001502 }
1503}
1504
1505void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001506 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001507 outVirtualKeys.clear();
1508
Chris Ye87143712020-11-10 05:05:58 +00001509 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001510 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001511 if (device != nullptr && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001512 const std::vector<VirtualKeyDefinition> virtualKeys =
1513 device->virtualKeyMap->getVirtualKeys();
1514 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001515 }
1516}
1517
Chris Ye3a1e4462020-08-12 10:13:15 -07001518const std::shared_ptr<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001519 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001520 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001521 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001522 return device->getKeyCharacterMap();
1523 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001524 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001525}
1526
Vaibhav Devmurari23e8ae92022-12-29 12:07:56 +00001527// If provided map is null, it will reset key character map to default KCM.
Chris Ye3a1e4462020-08-12 10:13:15 -07001528bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, std::shared_ptr<KeyCharacterMap> map) {
Chris Ye87143712020-11-10 05:05:58 +00001529 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001530 Device* device = getDeviceLocked(deviceId);
Vaibhav Devmurari23e8ae92022-12-29 12:07:56 +00001531 if (device == nullptr || device->keyMap.keyCharacterMap == nullptr) {
Philip Junker90bc9492021-12-10 18:39:42 +01001532 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001533 }
Vaibhav Devmurari23e8ae92022-12-29 12:07:56 +00001534 if (map == nullptr) {
1535 device->keyMap.keyCharacterMap->clearLayoutOverlay();
1536 return true;
1537 }
Philip Junker90bc9492021-12-10 18:39:42 +01001538 device->keyMap.keyCharacterMap->combine(*map);
1539 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001540}
1541
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001542static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
1543 std::string rawDescriptor;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001544 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001545 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001546 if (!identifier.uniqueId.empty()) {
1547 rawDescriptor += "uniqueId:";
1548 rawDescriptor += identifier.uniqueId;
Josh Bartel938632f2022-07-19 15:34:22 -05001549 }
1550 if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001551 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001552 }
1553
1554 if (identifier.vendor == 0 && identifier.product == 0) {
1555 // If we don't know the vendor and product id, then the device is probably
1556 // built-in so we need to rely on other information to uniquely identify
1557 // the input device. Usually we try to avoid relying on the device name or
1558 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001559 if (!identifier.name.empty()) {
1560 rawDescriptor += "name:";
1561 rawDescriptor += identifier.name;
1562 } else if (!identifier.location.empty()) {
1563 rawDescriptor += "location:";
1564 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001565 }
1566 }
1567 identifier.descriptor = sha1(rawDescriptor);
1568 return rawDescriptor;
1569}
1570
1571void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
1572 // Compute a device descriptor that uniquely identifies the device.
1573 // The descriptor is assumed to be a stable identifier. Its value should not
1574 // change between reboots, reconnections, firmware updates or new releases
1575 // of Android. In practice we sometimes get devices that cannot be uniquely
1576 // identified. In this case we enforce uniqueness between connected devices.
1577 // Ideally, we also want the descriptor to be short and relatively opaque.
Josh Bartel938632f2022-07-19 15:34:22 -05001578 // Note that we explicitly do not use the path or location for external devices
1579 // as their path or location will change as they are plugged/unplugged or moved
1580 // to different ports. We do fallback to using name and location in the case of
1581 // internal devices which are detected by the vendor and product being 0 in
1582 // generateDescriptor. If two identical descriptors are detected we will fallback
1583 // to using a 'nonce' and incrementing it until the new descriptor no longer has
1584 // a match with any existing descriptors.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001585
1586 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001587 std::string rawDescriptor = generateDescriptor(identifier);
Josh Bartel938632f2022-07-19 15:34:22 -05001588 // Enforce that the generated descriptor is unique.
1589 while (hasDeviceWithDescriptorLocked(identifier.descriptor)) {
1590 identifier.nonce++;
1591 rawDescriptor = generateDescriptor(identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001592 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001593 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001594 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001595}
1596
Prabir Pradhancb42b472022-08-23 16:01:19 +00001597std::shared_ptr<const EventHub::AssociatedDevice> EventHub::obtainAssociatedDeviceLocked(
1598 const std::filesystem::path& devicePath) const {
1599 const std::optional<std::filesystem::path> sysfsRootPathOpt =
1600 getSysfsRootPath(devicePath.c_str());
1601 if (!sysfsRootPathOpt) {
1602 return nullptr;
1603 }
1604
1605 const auto& path = *sysfsRootPathOpt;
Prabir Pradhancb42b472022-08-23 16:01:19 +00001606
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00001607 std::shared_ptr<const AssociatedDevice> associatedDevice = std::make_shared<AssociatedDevice>(
Prabir Pradhancb42b472022-08-23 16:01:19 +00001608 AssociatedDevice{.sysfsRootPath = path,
1609 .batteryInfos = readBatteryConfiguration(path),
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001610 .lightInfos = readLightsConfiguration(path),
1611 .layoutInfo = readLayoutConfiguration(path)});
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00001612
1613 bool associatedDeviceChanged = false;
1614 for (const auto& [id, dev] : mDevices) {
1615 if (dev->associatedDevice && dev->associatedDevice->sysfsRootPath == path) {
1616 if (*associatedDevice != *dev->associatedDevice) {
1617 associatedDeviceChanged = true;
1618 dev->associatedDevice = associatedDevice;
1619 }
1620 associatedDevice = dev->associatedDevice;
1621 }
1622 }
1623 ALOGI_IF(associatedDeviceChanged,
1624 "The AssociatedDevice changed for path '%s'. Using new AssociatedDevice: %s",
1625 path.c_str(), associatedDevice->dump().c_str());
1626
1627 return associatedDevice;
Prabir Pradhancb42b472022-08-23 16:01:19 +00001628}
1629
Vaibhav Devmurari5fc7d852023-03-17 18:43:33 +00001630bool EventHub::AssociatedDevice::isChanged() const {
1631 std::unordered_map<int32_t, RawBatteryInfo> newBatteryInfos =
1632 readBatteryConfiguration(sysfsRootPath);
1633 std::unordered_map<int32_t, RawLightInfo> newLightInfos =
1634 readLightsConfiguration(sysfsRootPath);
1635 std::optional<RawLayoutInfo> newLayoutInfo = readLayoutConfiguration(sysfsRootPath);
1636
1637 if (newBatteryInfos == batteryInfos && newLightInfos == lightInfos &&
1638 newLayoutInfo == layoutInfo) {
1639 return false;
1640 }
1641 return true;
1642}
1643
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001644void EventHub::vibrate(int32_t deviceId, const VibrationElement& element) {
Chris Ye87143712020-11-10 05:05:58 +00001645 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001646 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001647 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001648 ff_effect effect;
1649 memset(&effect, 0, sizeof(effect));
1650 effect.type = FF_RUMBLE;
1651 effect.id = device->ffEffectId;
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001652 // evdev FF_RUMBLE effect only supports two channels of vibration.
Chris Ye6393a262020-08-04 19:41:36 -07001653 effect.u.rumble.strong_magnitude = element.getMagnitude(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1654 effect.u.rumble.weak_magnitude = element.getMagnitude(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001655 effect.replay.length = element.duration.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001656 effect.replay.delay = 0;
1657 if (ioctl(device->fd, EVIOCSFF, &effect)) {
1658 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001659 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001660 return;
1661 }
1662 device->ffEffectId = effect.id;
1663
1664 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -07001665 ev.input_event_sec = 0;
1666 ev.input_event_usec = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001667 ev.type = EV_FF;
1668 ev.code = device->ffEffectId;
1669 ev.value = 1;
1670 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1671 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001672 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001673 return;
1674 }
1675 device->ffEffectPlaying = true;
1676 }
1677}
1678
1679void EventHub::cancelVibrate(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001680 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001681 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001682 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001683 if (device->ffEffectPlaying) {
1684 device->ffEffectPlaying = false;
1685
1686 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -07001687 ev.input_event_sec = 0;
1688 ev.input_event_usec = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001689 ev.type = EV_FF;
1690 ev.code = device->ffEffectId;
1691 ev.value = 0;
1692 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1693 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001694 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001695 return;
1696 }
1697 }
1698 }
1699}
1700
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001701std::vector<int32_t> EventHub::getVibratorIds(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001702 std::scoped_lock _l(mLock);
1703 std::vector<int32_t> vibrators;
1704 Device* device = getDeviceLocked(deviceId);
1705 if (device != nullptr && device->hasValidFd() &&
1706 device->classes.test(InputDeviceClass::VIBRATOR)) {
1707 vibrators.push_back(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1708 vibrators.push_back(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
1709 }
1710 return vibrators;
1711}
1712
Josh Bartel938632f2022-07-19 15:34:22 -05001713/**
1714 * Checks both mDevices and mOpeningDevices for a device with the descriptor passed.
1715 */
1716bool EventHub::hasDeviceWithDescriptorLocked(const std::string& descriptor) const {
1717 for (const auto& device : mOpeningDevices) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001718 if (descriptor == device->identifier.descriptor) {
Josh Bartel938632f2022-07-19 15:34:22 -05001719 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001720 }
1721 }
Josh Bartel938632f2022-07-19 15:34:22 -05001722
1723 for (const auto& [id, device] : mDevices) {
1724 if (descriptor == device->identifier.descriptor) {
1725 return true;
1726 }
1727 }
1728 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001729}
1730
1731EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001732 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001733 deviceId = mBuiltInKeyboardId;
1734 }
Chris Ye989bb932020-07-04 16:18:59 -07001735 const auto& it = mDevices.find(deviceId);
1736 return it != mDevices.end() ? it->second.get() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001737}
1738
Chris Ye8594e192020-07-14 10:34:06 -07001739EventHub::Device* EventHub::getDeviceByPathLocked(const std::string& devicePath) const {
Chris Ye989bb932020-07-04 16:18:59 -07001740 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001741 if (device->path == devicePath) {
Chris Ye989bb932020-07-04 16:18:59 -07001742 return device.get();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001743 }
1744 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001745 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001746}
1747
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001748/**
1749 * The file descriptor could be either input device, or a video device (associated with a
1750 * specific input device). Check both cases here, and return the device that this event
1751 * belongs to. Caller can compare the fd's once more to determine event type.
1752 * Looks through all input devices, and only attached video devices. Unattached video
1753 * devices are ignored.
1754 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001755EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
Chris Ye989bb932020-07-04 16:18:59 -07001756 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001757 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001758 // This is an input device event
Chris Ye989bb932020-07-04 16:18:59 -07001759 return device.get();
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001760 }
1761 if (device->videoDevice && device->videoDevice->getFd() == fd) {
1762 // This is a video device event
Chris Ye989bb932020-07-04 16:18:59 -07001763 return device.get();
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001764 }
1765 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001766 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
1767 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001768 return nullptr;
1769}
1770
Chris Yee2b1e5c2021-03-10 22:45:12 -08001771std::optional<int32_t> EventHub::getBatteryCapacity(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001772 std::filesystem::path batteryPath;
1773 {
1774 // Do not read the sysfs node to get the battery state while holding
1775 // the EventHub lock. For some peripheral devices, reading battery state
1776 // can be broken and take 5+ seconds. Holding the lock in this case would
1777 // block all other event processing during this time. For now, we assume this
1778 // call never happens on the InputReader thread and read the sysfs node outside
1779 // the lock to prevent event processing from being blocked by this call.
1780 std::scoped_lock _l(mLock);
Kim Low03ea0352020-11-06 12:45:07 -08001781
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001782 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001783 auto it = infos.find(batteryId);
1784 if (it == infos.end()) {
1785 return std::nullopt;
1786 }
1787 batteryPath = it->second.path;
1788 } // release lock
1789
Chris Yee2b1e5c2021-03-10 22:45:12 -08001790 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001791
1792 // Some devices report battery capacity as an integer through the "capacity" file
Andy Chenf9f1a022022-08-29 20:07:10 -04001793 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001794 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001795 return std::stoi(base::Trim(buffer));
Kim Low03ea0352020-11-06 12:45:07 -08001796 }
1797
1798 // Other devices report capacity as an enum value POWER_SUPPLY_CAPACITY_LEVEL_XXX
1799 // These values are taken from kernel source code include/linux/power_supply.h
Andy Chenf9f1a022022-08-29 20:07:10 -04001800 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY_LEVEL),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001801 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001802 // Remove any white space such as trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001803 const auto levelIt = BATTERY_LEVEL.find(base::Trim(buffer));
1804 if (levelIt != BATTERY_LEVEL.end()) {
1805 return levelIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001806 }
1807 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001808
Kim Low03ea0352020-11-06 12:45:07 -08001809 return std::nullopt;
1810}
1811
Chris Yee2b1e5c2021-03-10 22:45:12 -08001812std::optional<int32_t> EventHub::getBatteryStatus(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001813 std::filesystem::path batteryPath;
1814 {
1815 // Do not read the sysfs node to get the battery state while holding
1816 // the EventHub lock. For some peripheral devices, reading battery state
1817 // can be broken and take 5+ seconds. Holding the lock in this case would
1818 // block all other event processing during this time. For now, we assume this
1819 // call never happens on the InputReader thread and read the sysfs node outside
1820 // the lock to prevent event processing from being blocked by this call.
1821 std::scoped_lock _l(mLock);
1822
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001823 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001824 auto it = infos.find(batteryId);
1825 if (it == infos.end()) {
1826 return std::nullopt;
1827 }
1828 batteryPath = it->second.path;
1829 } // release lock
1830
Chris Yee2b1e5c2021-03-10 22:45:12 -08001831 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001832
Andy Chenf9f1a022022-08-29 20:07:10 -04001833 if (!base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::STATUS),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001834 &buffer)) {
Kim Low03ea0352020-11-06 12:45:07 -08001835 ALOGE("Failed to read sysfs battery info: %s", strerror(errno));
1836 return std::nullopt;
1837 }
1838
Chris Yed1936772021-02-22 10:30:40 -08001839 // Remove white space like trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001840 const auto statusIt = BATTERY_STATUS.find(base::Trim(buffer));
1841 if (statusIt != BATTERY_STATUS.end()) {
1842 return statusIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001843 }
1844
1845 return std::nullopt;
1846}
1847
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001848std::vector<RawEvent> EventHub::getEvents(int timeoutMillis) {
Chris Ye87143712020-11-10 05:05:58 +00001849 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001850
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001851 std::array<input_event, EVENT_BUFFER_SIZE> readBuffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001852
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001853 std::vector<RawEvent> events;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001854 bool awoken = false;
1855 for (;;) {
1856 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
1857
1858 // Reopen input devices if needed.
1859 if (mNeedToReopenDevices) {
1860 mNeedToReopenDevices = false;
1861
1862 ALOGI("Reopening all input devices due to a configuration change.");
1863
1864 closeAllDevicesLocked();
1865 mNeedToScanDevices = true;
1866 break; // return to the caller before we actually rescan
1867 }
1868
1869 // Report any devices that had last been added/removed.
Chris Ye989bb932020-07-04 16:18:59 -07001870 for (auto it = mClosingDevices.begin(); it != mClosingDevices.end();) {
1871 std::unique_ptr<Device> device = std::move(*it);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001872 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001873 const int32_t deviceId = (device->id == mBuiltInKeyboardId)
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001874 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
1875 : device->id;
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001876 events.push_back({
1877 .when = now,
1878 .deviceId = deviceId,
1879 .type = DEVICE_REMOVED,
1880 });
Chris Ye989bb932020-07-04 16:18:59 -07001881 it = mClosingDevices.erase(it);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001882 mNeedToSendFinishedDeviceScan = true;
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001883 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001884 break;
1885 }
1886 }
1887
1888 if (mNeedToScanDevices) {
1889 mNeedToScanDevices = false;
1890 scanDevicesLocked();
1891 mNeedToSendFinishedDeviceScan = true;
1892 }
1893
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001894 while (!mOpeningDevices.empty()) {
1895 std::unique_ptr<Device> device = std::move(*mOpeningDevices.rbegin());
1896 mOpeningDevices.pop_back();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001897 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001898 const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1899 events.push_back({
1900 .when = now,
1901 .deviceId = deviceId,
1902 .type = DEVICE_ADDED,
1903 });
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001904
1905 // Try to find a matching video device by comparing device names
1906 for (auto it = mUnattachedVideoDevices.begin(); it != mUnattachedVideoDevices.end();
1907 it++) {
1908 std::unique_ptr<TouchVideoDevice>& videoDevice = *it;
Chris Yed3fef462021-03-07 17:10:08 -08001909 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001910 // videoDevice was transferred to 'device'
1911 it = mUnattachedVideoDevices.erase(it);
1912 break;
1913 }
1914 }
1915
1916 auto [dev_it, inserted] = mDevices.insert_or_assign(device->id, std::move(device));
1917 if (!inserted) {
Chris Ye989bb932020-07-04 16:18:59 -07001918 ALOGW("Device id %d exists, replaced.", device->id);
1919 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001920 mNeedToSendFinishedDeviceScan = true;
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001921 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001922 break;
1923 }
1924 }
1925
1926 if (mNeedToSendFinishedDeviceScan) {
1927 mNeedToSendFinishedDeviceScan = false;
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001928 events.push_back({
1929 .when = now,
1930 .type = FINISHED_DEVICE_SCAN,
1931 });
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001932 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001933 break;
1934 }
1935 }
1936
1937 // Grab the next input event.
1938 bool deviceChanged = false;
1939 while (mPendingEventIndex < mPendingEventCount) {
1940 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001941 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001942 if (eventItem.events & EPOLLIN) {
1943 mPendingINotify = true;
1944 } else {
1945 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
1946 }
1947 continue;
1948 }
1949
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001950 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001951 if (eventItem.events & EPOLLIN) {
1952 ALOGV("awoken after wake()");
1953 awoken = true;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001954 char wakeReadBuffer[16];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001955 ssize_t nRead;
1956 do {
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001957 nRead = read(mWakeReadPipeFd, wakeReadBuffer, sizeof(wakeReadBuffer));
1958 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(wakeReadBuffer));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001959 } else {
1960 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001961 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001962 }
1963 continue;
1964 }
1965
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001966 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Chris Ye989bb932020-07-04 16:18:59 -07001967 if (device == nullptr) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001968 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
1969 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001970 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001971 continue;
1972 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001973 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
1974 if (eventItem.events & EPOLLIN) {
1975 size_t numFrames = device->videoDevice->readAndQueueFrames();
1976 if (numFrames == 0) {
1977 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001978 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001979 }
1980 } else if (eventItem.events & EPOLLHUP) {
1981 // TODO(b/121395353) - consider adding EPOLLRDHUP
1982 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001983 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001984 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1985 device->videoDevice = nullptr;
1986 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001987 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1988 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001989 ALOG_ASSERT(!DEBUG);
1990 }
1991 continue;
1992 }
1993 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -08001994 if (eventItem.events & EPOLLIN) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001995 int32_t readSize =
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001996 read(device->fd, readBuffer.data(),
1997 sizeof(decltype(readBuffer)::value_type) * readBuffer.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001998 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
1999 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -07002000 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07002001 " capacity: %zu errno: %d)\n",
2002 device->fd, readSize, readBuffer.size(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002003 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07002004 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002005 } else if (readSize < 0) {
2006 if (errno != EAGAIN && errno != EINTR) {
2007 ALOGW("could not get event (errno=%d)", errno);
2008 }
2009 } else if ((readSize % sizeof(struct input_event)) != 0) {
2010 ALOGE("could not get event (wrong size: %d)", readSize);
2011 } else {
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002012 const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002013
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002014 const size_t count = size_t(readSize) / sizeof(struct input_event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002015 for (size_t i = 0; i < count; i++) {
2016 struct input_event& iev = readBuffer[i];
Prabir Pradhan9762ac92023-07-13 21:45:12 +00002017 device->trackInputEvent(iev);
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002018 events.push_back({
2019 .when = processEventTimestamp(iev),
2020 .readTime = systemTime(SYSTEM_TIME_MONOTONIC),
2021 .deviceId = deviceId,
2022 .type = iev.type,
2023 .code = iev.code,
2024 .value = iev.value,
2025 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08002026 }
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07002027 if (events.size() >= EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002028 // The result buffer is full. Reset the pending event index
2029 // so we will try to read the device again on the next iteration.
2030 mPendingEventIndex -= 1;
2031 break;
2032 }
2033 }
2034 } else if (eventItem.events & EPOLLHUP) {
2035 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002036 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002037 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07002038 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002039 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002040 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
2041 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002042 }
2043 }
2044
2045 // readNotify() will modify the list of devices so this must be done after
2046 // processing all other events to ensure that we read all remaining events
2047 // before closing the devices.
2048 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
2049 mPendingINotify = false;
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002050 const auto res = readNotifyLocked();
2051 if (!res.ok()) {
2052 ALOGW("Failed to read from inotify: %s", res.error().message().c_str());
2053 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002054 deviceChanged = true;
2055 }
2056
2057 // Report added or removed devices immediately.
2058 if (deviceChanged) {
2059 continue;
2060 }
2061
2062 // Return now if we have collected any events or if we were explicitly awoken.
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002063 if (!events.empty() || awoken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002064 break;
2065 }
2066
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01002067 // Poll for events.
2068 // When a device driver has pending (unread) events, it acquires
2069 // a kernel wake lock. Once the last pending event has been read, the device
2070 // driver will release the kernel wake lock, but the epoll will hold the wakelock,
2071 // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
2072 // is called again for the same fd that produced the event.
2073 // Thus the system can only sleep if there are no events pending or
2074 // currently being processed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002075 //
2076 // The timeout is advisory only. If the device is asleep, it will not wake just to
2077 // service the timeout.
2078 mPendingEventIndex = 0;
2079
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01002080 mLock.unlock(); // release lock before poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08002081
2082 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
2083
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01002084 mLock.lock(); // reacquire lock after poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08002085
2086 if (pollResult == 0) {
2087 // Timed out.
2088 mPendingEventCount = 0;
2089 break;
2090 }
2091
2092 if (pollResult < 0) {
2093 // An error occurred.
2094 mPendingEventCount = 0;
2095
2096 // Sleep after errors to avoid locking up the system.
2097 // Hopefully the error is transient.
2098 if (errno != EINTR) {
2099 ALOGW("poll failed (errno=%d)\n", errno);
2100 usleep(100000);
2101 }
2102 } else {
2103 // Some events occurred.
2104 mPendingEventCount = size_t(pollResult);
2105 }
2106 }
2107
2108 // All done, return the number of events we read.
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002109 return events;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002110}
2111
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08002112std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002113 std::scoped_lock _l(mLock);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08002114
2115 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07002116 if (device == nullptr || !device->videoDevice) {
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08002117 return {};
2118 }
2119 return device->videoDevice->consumeFrames();
2120}
2121
Michael Wrightd02c5b62014-02-10 15:10:22 -08002122void EventHub::wake() {
2123 ALOGV("wake() called");
2124
2125 ssize_t nWrite;
2126 do {
2127 nWrite = write(mWakeWritePipeFd, "W", 1);
2128 } while (nWrite == -1 && errno == EINTR);
2129
2130 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002131 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002132 }
2133}
2134
2135void EventHub::scanDevicesLocked() {
Usama Arifb27c8e62021-06-03 16:44:09 +01002136 status_t result;
2137 std::error_code errorCode;
2138
2139 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
2140 result = scanDirLocked(DEVICE_INPUT_PATH);
2141 if (result < 0) {
2142 ALOGE("scan dir failed for %s", DEVICE_INPUT_PATH);
2143 }
2144 } else {
2145 if (errorCode) {
2146 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
2147 errorCode.message().c_str());
2148 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002149 }
Philip Quinn39b81682019-01-09 22:20:39 -08002150 if (isV4lScanningEnabled()) {
Usama Arifb27c8e62021-06-03 16:44:09 +01002151 result = scanVideoDirLocked(DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08002152 if (result != OK) {
Usama Arifb27c8e62021-06-03 16:44:09 +01002153 ALOGE("scan video dir failed for %s", DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08002154 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002155 }
Chris Ye989bb932020-07-04 16:18:59 -07002156 if (mDevices.find(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) == mDevices.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002157 createVirtualKeyboardLocked();
2158 }
2159}
2160
2161// ----------------------------------------------------------------------------
2162
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002163status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002164 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002165 struct epoll_event eventItem = {};
2166 eventItem.events = EPOLLIN | EPOLLWAKEUP;
2167 eventItem.data.fd = fd;
2168 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
2169 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002170 return -errno;
2171 }
2172 return OK;
2173}
2174
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002175status_t EventHub::unregisterFdFromEpoll(int fd) {
2176 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
2177 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
2178 return -errno;
2179 }
2180 return OK;
2181}
2182
Chris Ye989bb932020-07-04 16:18:59 -07002183status_t EventHub::registerDeviceForEpollLocked(Device& device) {
2184 status_t result = registerFdForEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002185 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07002186 ALOGE("Could not add input device fd to epoll for device %" PRId32, device.id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002187 return result;
2188 }
Chris Ye989bb932020-07-04 16:18:59 -07002189 if (device.videoDevice) {
2190 registerVideoDeviceForEpollLocked(*device.videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002191 }
2192 return result;
2193}
2194
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002195void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
2196 status_t result = registerFdForEpoll(videoDevice.getFd());
2197 if (result != OK) {
2198 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
2199 }
2200}
2201
Chris Ye989bb932020-07-04 16:18:59 -07002202status_t EventHub::unregisterDeviceFromEpollLocked(Device& device) {
2203 if (device.hasValidFd()) {
2204 status_t result = unregisterFdFromEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002205 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07002206 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device.id);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002207 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002208 }
2209 }
Chris Ye989bb932020-07-04 16:18:59 -07002210 if (device.videoDevice) {
2211 unregisterVideoDeviceFromEpollLocked(*device.videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002212 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002213 return OK;
2214}
2215
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002216void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
2217 if (videoDevice.hasValidFd()) {
2218 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
2219 if (result != OK) {
2220 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002221 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002222 }
2223 }
2224}
2225
Chris Yed3fef462021-03-07 17:10:08 -08002226void EventHub::reportDeviceAddedForStatisticsLocked(const InputDeviceIdentifier& identifier,
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002227 ftl::Flags<InputDeviceClass> classes) {
Chris Ye657c2f02021-05-25 16:24:37 -07002228 SHA256_CTX ctx;
2229 SHA256_Init(&ctx);
2230 SHA256_Update(&ctx, reinterpret_cast<const uint8_t*>(identifier.uniqueId.c_str()),
2231 identifier.uniqueId.size());
2232 std::array<uint8_t, SHA256_DIGEST_LENGTH> digest;
2233 SHA256_Final(digest.data(), &ctx);
2234
2235 std::string obfuscatedId;
2236 for (size_t i = 0; i < OBFUSCATED_LENGTH; i++) {
2237 obfuscatedId += StringPrintf("%02x", digest[i]);
2238 }
2239
Chris Yed3fef462021-03-07 17:10:08 -08002240 android::util::stats_write(android::util::INPUTDEVICE_REGISTERED, identifier.name.c_str(),
2241 identifier.vendor, identifier.product, identifier.version,
Chris Ye657c2f02021-05-25 16:24:37 -07002242 identifier.bus, obfuscatedId.c_str(), classes.get());
Chris Yed3fef462021-03-07 17:10:08 -08002243}
2244
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002245void EventHub::openDeviceLocked(const std::string& devicePath) {
2246 // If an input device happens to register around the time when EventHub's constructor runs, it
2247 // is possible that the same input event node (for example, /dev/input/event3) will be noticed
2248 // in both 'inotify' callback and also in the 'scanDirLocked' pass. To prevent duplicate devices
2249 // from getting registered, ensure that this path is not already covered by an existing device.
2250 for (const auto& [deviceId, device] : mDevices) {
2251 if (device->path == devicePath) {
2252 return; // device was already registered
2253 }
2254 }
2255
Michael Wrightd02c5b62014-02-10 15:10:22 -08002256 char buffer[80];
2257
Chris Ye8594e192020-07-14 10:34:06 -07002258 ALOGV("Opening device: %s", devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002259
Chris Ye8594e192020-07-14 10:34:06 -07002260 int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002261 if (fd < 0) {
Chris Ye8594e192020-07-14 10:34:06 -07002262 ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002263 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002264 }
2265
2266 InputDeviceIdentifier identifier;
2267
2268 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002269 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Chris Ye8594e192020-07-14 10:34:06 -07002270 ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002271 } else {
2272 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002273 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002274 }
2275
2276 // Check to see if the device is on our excluded list
2277 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002278 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002279 if (identifier.name == item) {
Chris Ye8594e192020-07-14 10:34:06 -07002280 ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002281 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002282 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002283 }
2284 }
2285
2286 // Get device driver version.
2287 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002288 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Chris Ye8594e192020-07-14 10:34:06 -07002289 ALOGE("could not get driver version for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002290 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002291 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002292 }
2293
2294 // Get device identifier.
2295 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002296 if (ioctl(fd, EVIOCGID, &inputId)) {
Chris Ye8594e192020-07-14 10:34:06 -07002297 ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002298 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002299 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002300 }
2301 identifier.bus = inputId.bustype;
2302 identifier.product = inputId.product;
2303 identifier.vendor = inputId.vendor;
2304 identifier.version = inputId.version;
2305
2306 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002307 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
2308 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002309 } else {
2310 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002311 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002312 }
2313
2314 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002315 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
2316 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002317 } else {
2318 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002319 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002320 }
2321
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002322 // Attempt to get the bluetooth address of an input device from the uniqueId.
2323 if (identifier.bus == BUS_BLUETOOTH &&
2324 std::regex_match(identifier.uniqueId,
2325 std::regex("^[A-Fa-f0-9]{2}(?::[A-Fa-f0-9]{2}){5}$"))) {
2326 identifier.bluetoothAddress = identifier.uniqueId;
2327 // The Bluetooth stack requires alphabetic characters to be uppercase in a valid address.
2328 for (auto& c : *identifier.bluetoothAddress) {
2329 c = ::toupper(c);
2330 }
2331 }
2332
Michael Wrightd02c5b62014-02-10 15:10:22 -08002333 // Fill in the descriptor.
2334 assignDescriptorLocked(identifier);
2335
Michael Wrightd02c5b62014-02-10 15:10:22 -08002336 // Allocate device. (The device object takes ownership of the fd at this point.)
2337 int32_t deviceId = mNextDeviceId++;
Prabir Pradhancb42b472022-08-23 16:01:19 +00002338 std::unique_ptr<Device> device =
2339 std::make_unique<Device>(fd, deviceId, devicePath, identifier,
2340 obtainAssociatedDeviceLocked(devicePath));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002341
Chris Ye8594e192020-07-14 10:34:06 -07002342 ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002343 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002344 " vendor %04x\n"
2345 " product %04x\n"
2346 " version %04x\n",
2347 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002348 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
2349 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
2350 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
2351 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002352 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
2353 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002354
2355 // Load the configuration file for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002356 device->loadConfigurationLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002357
2358 // Figure out the kinds of events the device reports.
Chris Ye66fbac32020-07-06 20:36:43 -07002359 device->readDeviceBitMask(EVIOCGBIT(EV_KEY, 0), device->keyBitmask);
2360 device->readDeviceBitMask(EVIOCGBIT(EV_ABS, 0), device->absBitmask);
2361 device->readDeviceBitMask(EVIOCGBIT(EV_REL, 0), device->relBitmask);
2362 device->readDeviceBitMask(EVIOCGBIT(EV_SW, 0), device->swBitmask);
2363 device->readDeviceBitMask(EVIOCGBIT(EV_LED, 0), device->ledBitmask);
2364 device->readDeviceBitMask(EVIOCGBIT(EV_FF, 0), device->ffBitmask);
Chris Yef59a2f42020-10-16 12:55:26 -07002365 device->readDeviceBitMask(EVIOCGBIT(EV_MSC, 0), device->mscBitmask);
Chris Ye66fbac32020-07-06 20:36:43 -07002366 device->readDeviceBitMask(EVIOCGPROP(0), device->propBitmask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002367
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002368 // See if this is a device with keys. This could be full keyboard, or other devices like
2369 // gamepads, joysticks, and styluses with buttons that should generate key presses.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002370 bool haveKeyboardKeys =
Chris Ye66fbac32020-07-06 20:36:43 -07002371 device->keyBitmask.any(0, BTN_MISC) || device->keyBitmask.any(BTN_WHEEL, KEY_MAX + 1);
2372 bool haveGamepadButtons = device->keyBitmask.any(BTN_MISC, BTN_MOUSE) ||
2373 device->keyBitmask.any(BTN_JOYSTICK, BTN_DIGI);
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002374 bool haveStylusButtons = device->keyBitmask.test(BTN_STYLUS) ||
2375 device->keyBitmask.test(BTN_STYLUS2) || device->keyBitmask.test(BTN_STYLUS3);
2376 if (haveKeyboardKeys || haveGamepadButtons || haveStylusButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002377 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002378 }
2379
2380 // See if this is a cursor device such as a trackball or mouse.
Chris Ye66fbac32020-07-06 20:36:43 -07002381 if (device->keyBitmask.test(BTN_MOUSE) && device->relBitmask.test(REL_X) &&
2382 device->relBitmask.test(REL_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002383 device->classes |= InputDeviceClass::CURSOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002384 }
2385
Prabir Pradhana3621852022-10-14 18:57:23 +00002386 // See if the device is specially configured to be of a certain type.
Harry Cuttsf13161a2023-03-08 14:15:49 +00002387 if (device->configuration) {
2388 std::string deviceType = device->configuration->getString("device.type").value_or("");
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07002389 if (deviceType == "rotaryEncoder") {
Chris Ye1b0c7342020-07-28 21:57:03 -07002390 device->classes |= InputDeviceClass::ROTARY_ENCODER;
Prabir Pradhana3621852022-10-14 18:57:23 +00002391 } else if (deviceType == "externalStylus") {
2392 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002393 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002394 }
2395
Michael Wrightd02c5b62014-02-10 15:10:22 -08002396 // See if this is a touch pad.
2397 // Is this a new modern multi-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002398 if (device->absBitmask.test(ABS_MT_POSITION_X) && device->absBitmask.test(ABS_MT_POSITION_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002399 // Some joysticks such as the PS3 controller report axes that conflict
2400 // with the ABS_MT range. Try to confirm that the device really is
2401 // a touch screen.
Chris Ye66fbac32020-07-06 20:36:43 -07002402 if (device->keyBitmask.test(BTN_TOUCH) || !haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002403 device->classes |= (InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT);
Harry Cutts79cc9fa2022-10-28 15:32:39 +00002404 if (device->propBitmask.test(INPUT_PROP_POINTER) &&
2405 !device->keyBitmask.any(BTN_TOOL_PEN, BTN_TOOL_FINGER) && !haveStylusButtons) {
2406 device->classes |= InputDeviceClass::TOUCHPAD;
2407 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002408 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002409 // Is this an old style single-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002410 } else if (device->keyBitmask.test(BTN_TOUCH) && device->absBitmask.test(ABS_X) &&
2411 device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002412 device->classes |= InputDeviceClass::TOUCH;
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002413 // Is this a stylus that reports contact/pressure independently of touch coordinates?
Chris Ye66fbac32020-07-06 20:36:43 -07002414 } else if ((device->absBitmask.test(ABS_PRESSURE) || device->keyBitmask.test(BTN_TOUCH)) &&
2415 !device->absBitmask.test(ABS_X) && !device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002416 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002417 }
2418
2419 // See if this device is a joystick.
2420 // Assumes that joysticks always have gamepad buttons in order to distinguish them
2421 // from other devices such as accelerometers that also have absolute axes.
2422 if (haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002423 auto assumedClasses = device->classes | InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002424 for (int i = 0; i <= ABS_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002425 if (device->absBitmask.test(i) &&
Chris Ye1b0c7342020-07-28 21:57:03 -07002426 (getAbsAxisUsage(i, assumedClasses).test(InputDeviceClass::JOYSTICK))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002427 device->classes = assumedClasses;
2428 break;
2429 }
2430 }
2431 }
2432
Chris Yef59a2f42020-10-16 12:55:26 -07002433 // Check whether this device is an accelerometer.
2434 if (device->propBitmask.test(INPUT_PROP_ACCELEROMETER)) {
2435 device->classes |= InputDeviceClass::SENSOR;
2436 }
2437
Michael Wrightd02c5b62014-02-10 15:10:22 -08002438 // Check whether this device has switches.
2439 for (int i = 0; i <= SW_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002440 if (device->swBitmask.test(i)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002441 device->classes |= InputDeviceClass::SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002442 break;
2443 }
2444 }
2445
2446 // Check whether this device supports the vibrator.
Chris Ye66fbac32020-07-06 20:36:43 -07002447 if (device->ffBitmask.test(FF_RUMBLE)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002448 device->classes |= InputDeviceClass::VIBRATOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002449 }
2450
2451 // Configure virtual keys.
Chris Ye1b0c7342020-07-28 21:57:03 -07002452 if ((device->classes.test(InputDeviceClass::TOUCH))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002453 // Load the virtual keys for the touch screen, if any.
2454 // We do this now so that we can make sure to load the keymap if necessary.
Chris Ye989bb932020-07-04 16:18:59 -07002455 bool success = device->loadVirtualKeyMapLocked();
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06002456 if (success) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002457 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002458 }
2459 }
2460
2461 // Load the key map.
Chris Yef59a2f42020-10-16 12:55:26 -07002462 // We need to do this for joysticks too because the key layout may specify axes, and for
2463 // sensor as well because the key layout may specify the axes to sensor data mapping.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002464 status_t keyMapStatus = NAME_NOT_FOUND;
Chris Yef59a2f42020-10-16 12:55:26 -07002465 if (device->classes.any(InputDeviceClass::KEYBOARD | InputDeviceClass::JOYSTICK |
2466 InputDeviceClass::SENSOR)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002467 // Load the keymap for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002468 keyMapStatus = device->loadKeyMapLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002469 }
2470
2471 // Configure the keyboard, gamepad or virtual keyboard.
Chris Ye1b0c7342020-07-28 21:57:03 -07002472 if (device->classes.test(InputDeviceClass::KEYBOARD)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002473 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002474 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002475 isEligibleBuiltInKeyboard(device->identifier, device->configuration.get(),
2476 &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002477 mBuiltInKeyboardId = device->id;
2478 }
2479
2480 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
Chris Ye989bb932020-07-04 16:18:59 -07002481 if (device->hasKeycodeLocked(AKEYCODE_Q)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002482 device->classes |= InputDeviceClass::ALPHAKEY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002483 }
2484
Prabir Pradhanae10ee62023-05-12 19:44:18 +00002485 // See if this device has a D-pad.
2486 if (std::all_of(DPAD_REQUIRED_KEYCODES.begin(), DPAD_REQUIRED_KEYCODES.end(),
2487 [&](int32_t keycode) { return device->hasKeycodeLocked(keycode); })) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002488 device->classes |= InputDeviceClass::DPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002489 }
2490
2491 // See if this device has a gamepad.
Prabir Pradhanae10ee62023-05-12 19:44:18 +00002492 if (std::any_of(GAMEPAD_KEYCODES.begin(), GAMEPAD_KEYCODES.end(),
2493 [&](int32_t keycode) { return device->hasKeycodeLocked(keycode); })) {
2494 device->classes |= InputDeviceClass::GAMEPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002495 }
Prabir Pradhana3621852022-10-14 18:57:23 +00002496
2497 // See if this device has any stylus buttons that we would want to fuse with touch data.
Prabir Pradhanae10ee62023-05-12 19:44:18 +00002498 if (!device->classes.any(InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT) &&
Prabir Pradhan3c28b942023-08-18 20:02:01 +00002499 !device->classes.any(InputDeviceClass::ALPHAKEY) &&
Prabir Pradhanae10ee62023-05-12 19:44:18 +00002500 std::any_of(STYLUS_BUTTON_KEYCODES.begin(), STYLUS_BUTTON_KEYCODES.end(),
2501 [&](int32_t keycode) { return device->hasKeycodeLocked(keycode); })) {
2502 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Prabir Pradhana3621852022-10-14 18:57:23 +00002503 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002504 }
2505
2506 // If the device isn't recognized as something we handle, don't monitor it.
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002507 if (device->classes == ftl::Flags<InputDeviceClass>(0)) {
Chris Ye8594e192020-07-14 10:34:06 -07002508 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002509 device->identifier.name.c_str());
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002510 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002511 }
2512
Chris Ye3fdbfef2021-01-06 18:45:18 -08002513 // Classify InputDeviceClass::BATTERY.
Prabir Pradhan51894782022-08-23 16:29:10 +00002514 if (device->associatedDevice && !device->associatedDevice->batteryInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002515 device->classes |= InputDeviceClass::BATTERY;
2516 }
Kim Low03ea0352020-11-06 12:45:07 -08002517
Chris Ye3fdbfef2021-01-06 18:45:18 -08002518 // Classify InputDeviceClass::LIGHT.
Prabir Pradhan51894782022-08-23 16:29:10 +00002519 if (device->associatedDevice && !device->associatedDevice->lightInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002520 device->classes |= InputDeviceClass::LIGHT;
Kim Low03ea0352020-11-06 12:45:07 -08002521 }
2522
Tim Kilbourn063ff532015-04-08 10:26:18 -07002523 // Determine whether the device has a mic.
Chris Ye989bb932020-07-04 16:18:59 -07002524 if (device->deviceHasMicLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002525 device->classes |= InputDeviceClass::MIC;
Tim Kilbourn063ff532015-04-08 10:26:18 -07002526 }
2527
Michael Wrightd02c5b62014-02-10 15:10:22 -08002528 // Determine whether the device is external or internal.
Chris Ye989bb932020-07-04 16:18:59 -07002529 if (device->isExternalDeviceLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002530 device->classes |= InputDeviceClass::EXTERNAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002531 }
2532
Chris Ye1b0c7342020-07-28 21:57:03 -07002533 if (device->classes.any(InputDeviceClass::JOYSTICK | InputDeviceClass::DPAD) &&
2534 device->classes.test(InputDeviceClass::GAMEPAD)) {
Chris Ye989bb932020-07-04 16:18:59 -07002535 device->controllerNumber = getNextControllerNumberLocked(device->identifier.name);
2536 device->setLedForControllerLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002537 }
2538
Chris Ye989bb932020-07-04 16:18:59 -07002539 if (registerDeviceForEpollLocked(*device) != OK) {
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002540 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002541 }
2542
Chris Ye989bb932020-07-04 16:18:59 -07002543 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002544
Chris Ye1b0c7342020-07-28 21:57:03 -07002545 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=%s, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002546 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Chris Ye1b0c7342020-07-28 21:57:03 -07002547 deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(),
2548 device->classes.string().c_str(), device->configurationFile.c_str(),
2549 device->keyMap.keyLayoutFile.c_str(), device->keyMap.keyCharacterMapFile.c_str(),
2550 toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002551
Chris Ye989bb932020-07-04 16:18:59 -07002552 addDeviceLocked(std::move(device));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002553}
2554
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002555void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
2556 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
2557 if (!videoDevice) {
2558 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
2559 return;
2560 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002561 // Transfer ownership of this video device to a matching input device
Chris Ye989bb932020-07-04 16:18:59 -07002562 for (const auto& [id, device] : mDevices) {
Chris Yed3fef462021-03-07 17:10:08 -08002563 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002564 return; // 'device' now owns 'videoDevice'
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002565 }
2566 }
2567
2568 // Couldn't find a matching input device, so just add it to a temporary holding queue.
2569 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002570 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002571 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002572 mUnattachedVideoDevices.push_back(std::move(videoDevice));
2573}
2574
Chris Yed3fef462021-03-07 17:10:08 -08002575bool EventHub::tryAddVideoDeviceLocked(EventHub::Device& device,
2576 std::unique_ptr<TouchVideoDevice>& videoDevice) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002577 if (videoDevice->getName() != device.identifier.name) {
2578 return false;
2579 }
2580 device.videoDevice = std::move(videoDevice);
2581 if (device.enabled) {
2582 registerVideoDeviceForEpollLocked(*device.videoDevice);
2583 }
2584 return true;
2585}
2586
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002587bool EventHub::isDeviceEnabled(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00002588 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002589 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002590 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002591 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2592 return false;
2593 }
2594 return device->enabled;
2595}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002596
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002597status_t EventHub::enableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002598 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002599 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002600 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002601 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2602 return BAD_VALUE;
2603 }
2604 if (device->enabled) {
2605 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
2606 return OK;
2607 }
2608 status_t result = device->enable();
2609 if (result != OK) {
2610 ALOGE("Failed to enable device %" PRId32, deviceId);
2611 return result;
2612 }
2613
Chris Ye989bb932020-07-04 16:18:59 -07002614 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002615
Chris Ye989bb932020-07-04 16:18:59 -07002616 return registerDeviceForEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002617}
2618
2619status_t EventHub::disableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002620 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002621 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002622 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002623 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2624 return BAD_VALUE;
2625 }
2626 if (!device->enabled) {
2627 ALOGW("Duplicate call to %s, input device already disabled", __func__);
2628 return OK;
2629 }
Chris Ye989bb932020-07-04 16:18:59 -07002630 unregisterDeviceFromEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002631 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002632}
2633
Vaibhav Devmurari5fc7d852023-03-17 18:43:33 +00002634// TODO(b/274755573): Shift to uevent handling on native side and remove this method
2635// Currently using Java UEventObserver to trigger this which uses UEvent infrastructure that uses a
2636// NETLINK socket to observe UEvents. We can create similar infrastructure on Eventhub side to
2637// directly observe UEvents instead of triggering from Java side.
2638void EventHub::sysfsNodeChanged(const std::string& sysfsNodePath) {
2639 std::scoped_lock _l(mLock);
2640
2641 // Check in opening devices
2642 for (auto it = mOpeningDevices.begin(); it != mOpeningDevices.end(); it++) {
2643 std::unique_ptr<Device>& device = *it;
2644 if (device->associatedDevice &&
2645 sysfsNodePath.find(device->associatedDevice->sysfsRootPath.string()) !=
2646 std::string::npos &&
2647 device->associatedDevice->isChanged()) {
2648 it = mOpeningDevices.erase(it);
2649 openDeviceLocked(device->path);
2650 }
2651 }
2652
2653 // Check in already added device
2654 std::vector<Device*> devicesToReopen;
2655 for (const auto& [id, device] : mDevices) {
2656 if (device->associatedDevice &&
2657 sysfsNodePath.find(device->associatedDevice->sysfsRootPath.string()) !=
2658 std::string::npos &&
2659 device->associatedDevice->isChanged()) {
2660 devicesToReopen.push_back(device.get());
2661 }
2662 }
2663 for (const auto& device : devicesToReopen) {
2664 closeDeviceLocked(*device);
2665 openDeviceLocked(device->path);
2666 }
2667 devicesToReopen.clear();
2668}
2669
Michael Wrightd02c5b62014-02-10 15:10:22 -08002670void EventHub::createVirtualKeyboardLocked() {
2671 InputDeviceIdentifier identifier;
2672 identifier.name = "Virtual";
2673 identifier.uniqueId = "<virtual>";
2674 assignDescriptorLocked(identifier);
2675
Chris Ye989bb932020-07-04 16:18:59 -07002676 std::unique_ptr<Device> device =
2677 std::make_unique<Device>(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
Harry Cutts33476232023-01-30 19:57:29 +00002678 identifier, /*associatedDevice=*/nullptr);
Chris Ye1b0c7342020-07-28 21:57:03 -07002679 device->classes = InputDeviceClass::KEYBOARD | InputDeviceClass::ALPHAKEY |
2680 InputDeviceClass::DPAD | InputDeviceClass::VIRTUAL;
Chris Ye989bb932020-07-04 16:18:59 -07002681 device->loadKeyMapLocked();
2682 addDeviceLocked(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002683}
2684
Chris Ye989bb932020-07-04 16:18:59 -07002685void EventHub::addDeviceLocked(std::unique_ptr<Device> device) {
Chris Yed3fef462021-03-07 17:10:08 -08002686 reportDeviceAddedForStatisticsLocked(device->identifier, device->classes);
Chris Ye989bb932020-07-04 16:18:59 -07002687 mOpeningDevices.push_back(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002688}
2689
Chris Ye989bb932020-07-04 16:18:59 -07002690int32_t EventHub::getNextControllerNumberLocked(const std::string& name) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002691 if (mControllerNumbers.isFull()) {
2692 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Chris Ye989bb932020-07-04 16:18:59 -07002693 name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002694 return 0;
2695 }
2696 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
2697 // one
2698 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
2699}
2700
Chris Ye989bb932020-07-04 16:18:59 -07002701void EventHub::releaseControllerNumberLocked(int32_t num) {
2702 if (num > 0) {
2703 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002704 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002705}
2706
Chris Ye8594e192020-07-14 10:34:06 -07002707void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002708 Device* device = getDeviceByPathLocked(devicePath);
Chris Ye989bb932020-07-04 16:18:59 -07002709 if (device != nullptr) {
2710 closeDeviceLocked(*device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002711 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002712 }
Chris Ye8594e192020-07-14 10:34:06 -07002713 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002714}
2715
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002716/**
2717 * Find the video device by filename, and close it.
2718 * The video device is closed by path during an inotify event, where we don't have the
2719 * additional context about the video device fd, or the associated input device.
2720 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002721void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002722 // A video device may be owned by an existing input device, or it may be stored in
2723 // the mUnattachedVideoDevices queue. Check both locations.
Chris Ye989bb932020-07-04 16:18:59 -07002724 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002725 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002726 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002727 device->videoDevice = nullptr;
2728 return;
2729 }
2730 }
Siarhei Vishniakouf47c339e2021-12-30 11:22:26 -08002731 std::erase_if(mUnattachedVideoDevices,
2732 [&devicePath](const std::unique_ptr<TouchVideoDevice>& videoDevice) {
2733 return videoDevice->getPath() == devicePath;
2734 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08002735}
2736
2737void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002738 mUnattachedVideoDevices.clear();
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002739 while (!mDevices.empty()) {
2740 closeDeviceLocked(*(mDevices.begin()->second));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002741 }
2742}
2743
Chris Ye989bb932020-07-04 16:18:59 -07002744void EventHub::closeDeviceLocked(Device& device) {
2745 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=%s", device.path.c_str(),
2746 device.identifier.name.c_str(), device.id, device.fd, device.classes.string().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002747
Chris Ye989bb932020-07-04 16:18:59 -07002748 if (device.id == mBuiltInKeyboardId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002749 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Chris Ye989bb932020-07-04 16:18:59 -07002750 device.path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002751 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
2752 }
2753
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002754 unregisterDeviceFromEpollLocked(device);
Chris Ye989bb932020-07-04 16:18:59 -07002755 if (device.videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002756 // This must be done after the video device is removed from epoll
Chris Ye989bb932020-07-04 16:18:59 -07002757 mUnattachedVideoDevices.push_back(std::move(device.videoDevice));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002758 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002759
Chris Ye989bb932020-07-04 16:18:59 -07002760 releaseControllerNumberLocked(device.controllerNumber);
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002761 device.controllerNumber = 0;
Chris Ye989bb932020-07-04 16:18:59 -07002762 device.close();
Chris Ye989bb932020-07-04 16:18:59 -07002763 mClosingDevices.push_back(std::move(mDevices[device.id]));
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002764
Chris Ye989bb932020-07-04 16:18:59 -07002765 mDevices.erase(device.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002766}
2767
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002768base::Result<void> EventHub::readNotifyLocked() {
2769 static constexpr auto EVENT_SIZE = static_cast<ssize_t>(sizeof(inotify_event));
2770 uint8_t eventBuffer[512];
2771 ssize_t sizeRead;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002772
2773 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002774 do {
2775 sizeRead = read(mINotifyFd, eventBuffer, sizeof(eventBuffer));
2776 } while (sizeRead < 0 && errno == EINTR);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002777
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002778 if (sizeRead < EVENT_SIZE) return Errorf("could not get event, %s", strerror(errno));
2779
2780 for (ssize_t eventPos = 0; sizeRead >= EVENT_SIZE;) {
2781 const inotify_event* event;
2782 event = (const inotify_event*)(eventBuffer + eventPos);
2783 if (event->len == 0) continue;
2784
2785 handleNotifyEventLocked(*event);
2786
2787 const ssize_t eventSize = EVENT_SIZE + event->len;
2788 sizeRead -= eventSize;
2789 eventPos += eventSize;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002790 }
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002791 return {};
2792}
2793
2794void EventHub::handleNotifyEventLocked(const inotify_event& event) {
2795 if (event.wd == mDeviceInputWd) {
2796 std::string filename = std::string(DEVICE_INPUT_PATH) + "/" + event.name;
2797 if (event.mask & IN_CREATE) {
2798 openDeviceLocked(filename);
2799 } else {
2800 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
2801 closeDeviceByPathLocked(filename);
2802 }
2803 } else if (event.wd == mDeviceWd) {
2804 if (isV4lTouchNode(event.name)) {
2805 std::string filename = std::string(DEVICE_PATH) + "/" + event.name;
2806 if (event.mask & IN_CREATE) {
2807 openVideoDeviceLocked(filename);
2808 } else {
2809 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
2810 closeVideoDeviceByPathLocked(filename);
2811 }
2812 } else if (strcmp(event.name, "input") == 0 && event.mask & IN_CREATE) {
2813 addDeviceInputInotify();
2814 }
2815 } else {
2816 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event.wd);
2817 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002818}
2819
Chris Ye8594e192020-07-14 10:34:06 -07002820status_t EventHub::scanDirLocked(const std::string& dirname) {
2821 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2822 openDeviceLocked(entry.path());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002823 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002824 return 0;
2825}
2826
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002827/**
2828 * Look for all dirname/v4l-touch* devices, and open them.
2829 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002830status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Chris Ye8594e192020-07-14 10:34:06 -07002831 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2832 if (isV4lTouchNode(entry.path())) {
2833 ALOGI("Found touch video device %s", entry.path().c_str());
2834 openVideoDeviceLocked(entry.path());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002835 }
2836 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002837 return OK;
2838}
2839
Michael Wrightd02c5b62014-02-10 15:10:22 -08002840void EventHub::requestReopenDevices() {
2841 ALOGV("requestReopenDevices() called");
2842
Chris Ye87143712020-11-10 05:05:58 +00002843 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002844 mNeedToReopenDevices = true;
2845}
2846
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002847void EventHub::dump(std::string& dump) const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002848 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002849
2850 { // acquire lock
Chris Ye87143712020-11-10 05:05:58 +00002851 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002852
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002853 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002854
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002855 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002856
Chris Ye989bb932020-07-04 16:18:59 -07002857 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002858 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002859 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002860 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002861 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002862 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002863 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002864 }
Chris Ye1b0c7342020-07-28 21:57:03 -07002865 dump += StringPrintf(INDENT3 "Classes: %s\n", device->classes.string().c_str());
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002866 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002867 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002868 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
2869 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002870 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002871 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002872 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002873 "product=0x%04x, version=0x%04x, bluetoothAddress=%s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002874 device->identifier.bus, device->identifier.vendor,
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002875 device->identifier.product, device->identifier.version,
2876 toString(device->identifier.bluetoothAddress).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002877 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002878 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002879 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002880 device->keyMap.keyCharacterMapFile.c_str());
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00002881 if (device->associatedDevice && device->associatedDevice->layoutInfo) {
2882 dump += StringPrintf(INDENT3 "LanguageTag: %s\n",
2883 device->associatedDevice->layoutInfo->languageTag.c_str());
2884 dump += StringPrintf(INDENT3 "LayoutType: %s\n",
2885 device->associatedDevice->layoutInfo->layoutType.c_str());
2886 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002887 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002888 device->configurationFile.c_str());
Prabir Pradhan51894782022-08-23 16:29:10 +00002889 dump += StringPrintf(INDENT3 "VideoDevice: %s\n",
2890 device->videoDevice ? device->videoDevice->dump().c_str()
2891 : "<none>");
2892 dump += StringPrintf(INDENT3 "SysfsDevicePath: %s\n",
2893 device->associatedDevice
2894 ? device->associatedDevice->sysfsRootPath.c_str()
2895 : "<none>");
Prabir Pradhan955b6132023-07-14 19:44:34 +00002896 if (device->keyBitmask.any(0, KEY_MAX + 1)) {
2897 const auto pressedKeys = device->keyState.dumpSetIndices(", ", [](int i) {
2898 return InputEventLookup::getLinuxEvdevLabel(EV_KEY, i, 1).code;
2899 });
2900 dump += StringPrintf(INDENT3 "KeyState (pressed): %s\n", pressedKeys.c_str());
2901 }
2902 if (device->swBitmask.any(0, SW_MAX + 1)) {
2903 const auto pressedSwitches = device->swState.dumpSetIndices(", ", [](int i) {
2904 return InputEventLookup::getLinuxEvdevLabel(EV_SW, i, 1).code;
2905 });
2906 dump += StringPrintf(INDENT3 "SwState (pressed): %s\n", pressedSwitches.c_str());
2907 }
2908 if (!device->absState.empty()) {
2909 std::string axisValues;
2910 for (const auto& [axis, state] : device->absState) {
2911 if (!axisValues.empty()) {
2912 axisValues += ", ";
2913 }
2914 axisValues += StringPrintf("%s=%d",
2915 InputEventLookup::getLinuxEvdevLabel(EV_ABS, axis, 0)
2916 .code.c_str(),
2917 state.value);
2918 }
2919 dump += INDENT3 "AbsState: " + axisValues + "\n";
2920 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002921 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002922
2923 dump += INDENT "Unattached video devices:\n";
2924 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
2925 dump += INDENT2 + videoDevice->dump() + "\n";
2926 }
2927 if (mUnattachedVideoDevices.empty()) {
2928 dump += INDENT2 "<none>\n";
2929 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002930 } // release lock
2931}
2932
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002933void EventHub::monitor() const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002934 // Acquire and release the lock to ensure that the event hub has not deadlocked.
Chris Ye1c2e0892020-11-30 21:41:44 -08002935 std::unique_lock<std::mutex> lock(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002936}
2937
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00002938std::string EventHub::AssociatedDevice::dump() const {
2939 return StringPrintf("path=%s, numBatteries=%zu, numLight=%zu", sysfsRootPath.c_str(),
2940 batteryInfos.size(), lightInfos.size());
2941}
2942
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002943} // namespace android