blob: 7052c61a37faad9437151f046d4535bc75a54232 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2005 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070017#include <assert.h>
18#include <dirent.h>
19#include <errno.h>
20#include <fcntl.h>
21#include <inttypes.h>
Colin Cross5b799302022-10-18 21:52:41 -070022#include <linux/ioctl.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070023#include <memory.h>
24#include <stdint.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +010028#include <sys/capability.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070029#include <sys/epoll.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070030#include <sys/inotify.h>
31#include <sys/ioctl.h>
Kim Low03ea0352020-11-06 12:45:07 -080032#include <sys/stat.h>
33#include <sys/sysmacros.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070034#include <unistd.h>
35
Michael Wrightd02c5b62014-02-10 15:10:22 -080036#define LOG_TAG "EventHub"
37
38// #define LOG_NDEBUG 0
Kim Low03ea0352020-11-06 12:45:07 -080039#include <android-base/file.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080040#include <android-base/stringprintf.h>
Chris Yed3fef462021-03-07 17:10:08 -080041#include <android-base/strings.h>
Philip Quinn39b81682019-01-09 22:20:39 -080042#include <cutils/properties.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080043#include <ftl/enum.h>
Chris Ye8594e192020-07-14 10:34:06 -070044#include <input/KeyCharacterMap.h>
45#include <input/KeyLayoutMap.h>
Prabir Pradhan07525ef2022-10-03 21:51:26 +000046#include <input/PrintTools.h>
Chris Ye8594e192020-07-14 10:34:06 -070047#include <input/VirtualKeyMap.h>
Dan Albert677d87e2014-06-16 17:31:28 -070048#include <openssl/sha.h>
Chris Yed3fef462021-03-07 17:10:08 -080049#include <statslog.h>
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070050#include <utils/Errors.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080051#include <utils/Log.h>
52#include <utils/Timers.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080053
Chris Ye8594e192020-07-14 10:34:06 -070054#include <filesystem>
Harry Cuttsf13161a2023-03-08 14:15:49 +000055#include <optional>
Chris Ye3fdbfef2021-01-06 18:45:18 -080056#include <regex>
Prabir Pradhancb42b472022-08-23 16:01:19 +000057#include <utility>
Chris Ye8594e192020-07-14 10:34:06 -070058
59#include "EventHub.h"
Michael Wrightd02c5b62014-02-10 15:10:22 -080060
Prabir Pradhanae10ee62023-05-12 19:44:18 +000061#include "KeyCodeClassifications.h"
62
Michael Wrightd02c5b62014-02-10 15:10:22 -080063#define INDENT " "
64#define INDENT2 " "
65#define INDENT3 " "
66
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080067using android::base::StringPrintf;
68
Michael Wrightd02c5b62014-02-10 15:10:22 -080069namespace android {
70
Dominik Laskowski2f01d772022-03-23 16:01:29 -070071using namespace ftl::flag_operators;
72
Usama Arifb27c8e62021-06-03 16:44:09 +010073static const char* DEVICE_INPUT_PATH = "/dev/input";
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080074// v4l2 devices go directly into /dev
Usama Arifb27c8e62021-06-03 16:44:09 +010075static const char* DEVICE_PATH = "/dev";
Michael Wrightd02c5b62014-02-10 15:10:22 -080076
Chris Ye657c2f02021-05-25 16:24:37 -070077static constexpr size_t OBFUSCATED_LENGTH = 8;
78
Chris Ye87143712020-11-10 05:05:58 +000079static constexpr int32_t FF_STRONG_MAGNITUDE_CHANNEL_IDX = 0;
80static constexpr int32_t FF_WEAK_MAGNITUDE_CHANNEL_IDX = 1;
Chris Ye6393a262020-08-04 19:41:36 -070081
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -070082static constexpr size_t EVENT_BUFFER_SIZE = 256;
83
Chris Yee2b1e5c2021-03-10 22:45:12 -080084// Mapping for input battery class node IDs lookup.
85// https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
86static const std::unordered_map<std::string, InputBatteryClass> BATTERY_CLASSES =
87 {{"capacity", InputBatteryClass::CAPACITY},
88 {"capacity_level", InputBatteryClass::CAPACITY_LEVEL},
89 {"status", InputBatteryClass::STATUS}};
90
91// Mapping for input battery class node names lookup.
92// https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
93static const std::unordered_map<InputBatteryClass, std::string> BATTERY_NODES =
94 {{InputBatteryClass::CAPACITY, "capacity"},
95 {InputBatteryClass::CAPACITY_LEVEL, "capacity_level"},
96 {InputBatteryClass::STATUS, "status"}};
97
Kim Low03ea0352020-11-06 12:45:07 -080098// must be kept in sync with definitions in kernel /drivers/power/supply/power_supply_sysfs.c
99static const std::unordered_map<std::string, int32_t> BATTERY_STATUS =
100 {{"Unknown", BATTERY_STATUS_UNKNOWN},
101 {"Charging", BATTERY_STATUS_CHARGING},
102 {"Discharging", BATTERY_STATUS_DISCHARGING},
103 {"Not charging", BATTERY_STATUS_NOT_CHARGING},
104 {"Full", BATTERY_STATUS_FULL}};
105
106// Mapping taken from
107// https://gitlab.freedesktop.org/upower/upower/-/blob/master/src/linux/up-device-supply.c#L484
108static const std::unordered_map<std::string, int32_t> BATTERY_LEVEL = {{"Critical", 5},
109 {"Low", 10},
110 {"Normal", 55},
111 {"High", 70},
112 {"Full", 100},
113 {"Unknown", 50}};
114
Chris Ye3fdbfef2021-01-06 18:45:18 -0800115// Mapping for input led class node names lookup.
116// https://www.kernel.org/doc/html/latest/leds/leds-class.html
117static const std::unordered_map<std::string, InputLightClass> LIGHT_CLASSES =
118 {{"red", InputLightClass::RED},
119 {"green", InputLightClass::GREEN},
120 {"blue", InputLightClass::BLUE},
121 {"global", InputLightClass::GLOBAL},
122 {"brightness", InputLightClass::BRIGHTNESS},
123 {"multi_index", InputLightClass::MULTI_INDEX},
124 {"multi_intensity", InputLightClass::MULTI_INTENSITY},
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000125 {"max_brightness", InputLightClass::MAX_BRIGHTNESS},
DingYong99f2c3c2023-12-20 15:46:06 +0800126 {"kbd_backlight", InputLightClass::KEYBOARD_BACKLIGHT},
127 {"mic_mute", InputLightClass::KEYBOARD_MIC_MUTE}};
Chris Ye3fdbfef2021-01-06 18:45:18 -0800128
129// Mapping for input multicolor led class node names.
130// https://www.kernel.org/doc/html/latest/leds/leds-class-multicolor.html
131static const std::unordered_map<InputLightClass, std::string> LIGHT_NODES =
132 {{InputLightClass::BRIGHTNESS, "brightness"},
133 {InputLightClass::MULTI_INDEX, "multi_index"},
134 {InputLightClass::MULTI_INTENSITY, "multi_intensity"}};
135
136// Mapping for light color name and the light color
137const std::unordered_map<std::string, LightColor> LIGHT_COLORS = {{"red", LightColor::RED},
138 {"green", LightColor::GREEN},
139 {"blue", LightColor::BLUE}};
140
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000141// Mapping for country code to Layout info.
142// See bCountryCode in 6.2.1 of https://usb.org/sites/default/files/hid1_11.pdf.
143const std::unordered_map<std::int32_t, RawLayoutInfo> LAYOUT_INFOS =
144 {{0, RawLayoutInfo{.languageTag = "", .layoutType = ""}}, // NOT_SUPPORTED
145 {1, RawLayoutInfo{.languageTag = "ar-Arab", .layoutType = ""}}, // ARABIC
146 {2, RawLayoutInfo{.languageTag = "fr-BE", .layoutType = ""}}, // BELGIAN
147 {3, RawLayoutInfo{.languageTag = "fr-CA", .layoutType = ""}}, // CANADIAN_BILINGUAL
148 {4, RawLayoutInfo{.languageTag = "fr-CA", .layoutType = ""}}, // CANADIAN_FRENCH
149 {5, RawLayoutInfo{.languageTag = "cs", .layoutType = ""}}, // CZECH_REPUBLIC
150 {6, RawLayoutInfo{.languageTag = "da", .layoutType = ""}}, // DANISH
151 {7, RawLayoutInfo{.languageTag = "fi", .layoutType = ""}}, // FINNISH
152 {8, RawLayoutInfo{.languageTag = "fr-FR", .layoutType = ""}}, // FRENCH
153 {9, RawLayoutInfo{.languageTag = "de", .layoutType = ""}}, // GERMAN
154 {10, RawLayoutInfo{.languageTag = "el", .layoutType = ""}}, // GREEK
155 {11, RawLayoutInfo{.languageTag = "iw", .layoutType = ""}}, // HEBREW
156 {12, RawLayoutInfo{.languageTag = "hu", .layoutType = ""}}, // HUNGARY
157 {13, RawLayoutInfo{.languageTag = "en", .layoutType = "extended"}}, // INTERNATIONAL (ISO)
158 {14, RawLayoutInfo{.languageTag = "it", .layoutType = ""}}, // ITALIAN
159 {15, RawLayoutInfo{.languageTag = "ja", .layoutType = ""}}, // JAPAN
160 {16, RawLayoutInfo{.languageTag = "ko", .layoutType = ""}}, // KOREAN
161 {17, RawLayoutInfo{.languageTag = "es-419", .layoutType = ""}}, // LATIN_AMERICA
162 {18, RawLayoutInfo{.languageTag = "nl", .layoutType = ""}}, // DUTCH
163 {19, RawLayoutInfo{.languageTag = "nb", .layoutType = ""}}, // NORWEGIAN
164 {20, RawLayoutInfo{.languageTag = "fa", .layoutType = ""}}, // PERSIAN
165 {21, RawLayoutInfo{.languageTag = "pl", .layoutType = ""}}, // POLAND
166 {22, RawLayoutInfo{.languageTag = "pt", .layoutType = ""}}, // PORTUGUESE
167 {23, RawLayoutInfo{.languageTag = "ru", .layoutType = ""}}, // RUSSIA
168 {24, RawLayoutInfo{.languageTag = "sk", .layoutType = ""}}, // SLOVAKIA
169 {25, RawLayoutInfo{.languageTag = "es-ES", .layoutType = ""}}, // SPANISH
170 {26, RawLayoutInfo{.languageTag = "sv", .layoutType = ""}}, // SWEDISH
171 {27, RawLayoutInfo{.languageTag = "fr-CH", .layoutType = ""}}, // SWISS_FRENCH
172 {28, RawLayoutInfo{.languageTag = "de-CH", .layoutType = ""}}, // SWISS_GERMAN
173 {29, RawLayoutInfo{.languageTag = "de-CH", .layoutType = ""}}, // SWITZERLAND
174 {30, RawLayoutInfo{.languageTag = "zh-TW", .layoutType = ""}}, // TAIWAN
175 {31, RawLayoutInfo{.languageTag = "tr", .layoutType = "turkish_q"}}, // TURKISH_Q
176 {32, RawLayoutInfo{.languageTag = "en-GB", .layoutType = ""}}, // UK
177 {33, RawLayoutInfo{.languageTag = "en-US", .layoutType = ""}}, // US
178 {34, RawLayoutInfo{.languageTag = "", .layoutType = ""}}, // YUGOSLAVIA
179 {35, RawLayoutInfo{.languageTag = "tr", .layoutType = "turkish_f"}}}; // TURKISH_F
180
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100181static std::string sha1(const std::string& in) {
Dan Albert677d87e2014-06-16 17:31:28 -0700182 SHA_CTX ctx;
183 SHA1_Init(&ctx);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100184 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
Dan Albert677d87e2014-06-16 17:31:28 -0700185 u_char digest[SHA_DIGEST_LENGTH];
186 SHA1_Final(digest, &ctx);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800187
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100188 std::string out;
Dan Albert677d87e2014-06-16 17:31:28 -0700189 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100190 out += StringPrintf("%02x", digest[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800191 }
192 return out;
193}
194
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800195/**
196 * Return true if name matches "v4l-touch*"
197 */
Chris Ye8594e192020-07-14 10:34:06 -0700198static bool isV4lTouchNode(std::string name) {
199 return name.find("v4l-touch") != std::string::npos;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800200}
201
Philip Quinn39b81682019-01-09 22:20:39 -0800202/**
203 * Returns true if V4L devices should be scanned.
204 *
205 * The system property ro.input.video_enabled can be used to control whether
206 * EventHub scans and opens V4L devices. As V4L does not support multiple
207 * clients, EventHub effectively blocks access to these devices when it opens
Siarhei Vishniakou29f88492019-04-05 14:11:43 -0700208 * them.
209 *
210 * Setting this to "false" would prevent any video devices from being discovered and
211 * associated with input devices.
212 *
213 * This property can be used as follows:
214 * 1. To turn off features that are dependent on video device presence.
215 * 2. During testing and development, to allow other clients to read video devices
216 * directly from /dev.
Philip Quinn39b81682019-01-09 22:20:39 -0800217 */
218static bool isV4lScanningEnabled() {
Harry Cutts33476232023-01-30 19:57:29 +0000219 return property_get_bool("ro.input.video_enabled", /*default_value=*/true);
Philip Quinn39b81682019-01-09 22:20:39 -0800220}
221
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800222static nsecs_t processEventTimestamp(const struct input_event& event) {
223 // Use the time specified in the event instead of the current time
224 // so that downstream code can get more accurate estimates of
225 // event dispatch latency from the time the event is enqueued onto
226 // the evdev client buffer.
227 //
228 // The event's timestamp fortuitously uses the same monotonic clock
229 // time base as the rest of Android. The kernel event device driver
230 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
231 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
232 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
233 // system call that also queries ktime_get_ts().
234
Colin Cross5b799302022-10-18 21:52:41 -0700235 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.input_event_sec) +
236 microseconds_to_nanoseconds(event.input_event_usec);
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800237 return inputEventTime;
238}
239
Kim Low03ea0352020-11-06 12:45:07 -0800240/**
Prabir Pradhancb42b472022-08-23 16:01:19 +0000241 * Returns the sysfs root path of the input device.
Kim Low03ea0352020-11-06 12:45:07 -0800242 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800243static std::optional<std::filesystem::path> getSysfsRootPath(const char* devicePath) {
Kim Low03ea0352020-11-06 12:45:07 -0800244 std::error_code errorCode;
245
246 // Stat the device path to get the major and minor number of the character file
247 struct stat statbuf;
248 if (stat(devicePath, &statbuf) == -1) {
249 ALOGE("Could not stat device %s due to error: %s.", devicePath, std::strerror(errno));
Chris Ye3fdbfef2021-01-06 18:45:18 -0800250 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800251 }
252
253 unsigned int major_num = major(statbuf.st_rdev);
254 unsigned int minor_num = minor(statbuf.st_rdev);
255
256 // Realpath "/sys/dev/char/{major}:{minor}" to get the sysfs path to the input event
257 auto sysfsPath = std::filesystem::path("/sys/dev/char/");
258 sysfsPath /= std::to_string(major_num) + ":" + std::to_string(minor_num);
259 sysfsPath = std::filesystem::canonical(sysfsPath, errorCode);
260
261 // Make sure nothing went wrong in call to canonical()
262 if (errorCode) {
263 ALOGW("Could not run filesystem::canonical() due to error %d : %s.", errorCode.value(),
264 errorCode.message().c_str());
Chris Ye3fdbfef2021-01-06 18:45:18 -0800265 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800266 }
267
268 // Continue to go up a directory until we reach a directory named "input"
269 while (sysfsPath != "/" && sysfsPath.filename() != "input") {
270 sysfsPath = sysfsPath.parent_path();
271 }
272
273 // Then go up one more and you will be at the sysfs root of the device
274 sysfsPath = sysfsPath.parent_path();
275
276 // Make sure we didn't reach root path and that directory actually exists
277 if (sysfsPath == "/" || !std::filesystem::exists(sysfsPath, errorCode)) {
278 if (errorCode) {
279 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
280 errorCode.message().c_str());
281 }
282
283 // Not found
Chris Ye3fdbfef2021-01-06 18:45:18 -0800284 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800285 }
286
287 return sysfsPath;
288}
289
290/**
Chris Ye3fdbfef2021-01-06 18:45:18 -0800291 * Returns the list of files under a specified path.
Kim Low03ea0352020-11-06 12:45:07 -0800292 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800293static std::vector<std::filesystem::path> allFilesInPath(const std::filesystem::path& path) {
294 std::vector<std::filesystem::path> nodes;
295 std::error_code errorCode;
296 auto iter = std::filesystem::directory_iterator(path, errorCode);
297 while (!errorCode && iter != std::filesystem::directory_iterator()) {
298 nodes.push_back(iter->path());
299 iter++;
300 }
301 return nodes;
302}
303
304/**
305 * Returns the list of files under a specified directory in a sysfs path.
306 * Example:
307 * findSysfsNodes(sysfsRootPath, SysfsClass::LEDS) will return all led nodes under "leds" directory
308 * in the sysfs path.
309 */
310static std::vector<std::filesystem::path> findSysfsNodes(const std::filesystem::path& sysfsRoot,
311 SysfsClass clazz) {
Dominik Laskowski75788452021-02-09 18:51:25 -0800312 std::string nodeStr = ftl::enum_string(clazz);
Chris Ye3fdbfef2021-01-06 18:45:18 -0800313 std::for_each(nodeStr.begin(), nodeStr.end(),
314 [](char& c) { c = std::tolower(static_cast<unsigned char>(c)); });
315 std::vector<std::filesystem::path> nodes;
316 for (auto path = sysfsRoot; path != "/" && nodes.empty(); path = path.parent_path()) {
317 nodes = allFilesInPath(path / nodeStr);
318 }
319 return nodes;
320}
321
322static std::optional<std::array<LightColor, COLOR_NUM>> getColorIndexArray(
323 std::filesystem::path path) {
324 std::string indexStr;
325 if (!base::ReadFileToString(path, &indexStr)) {
326 return std::nullopt;
327 }
328
329 // Parse the multi color LED index file, refer to kernel docs
330 // leds/leds-class-multicolor.html
331 std::regex indexPattern("(red|green|blue)\\s(red|green|blue)\\s(red|green|blue)[\\n]");
332 std::smatch results;
333 std::array<LightColor, COLOR_NUM> colors;
334 if (!std::regex_match(indexStr, results, indexPattern)) {
335 return std::nullopt;
336 }
337
338 for (size_t i = 1; i < results.size(); i++) {
339 const auto it = LIGHT_COLORS.find(results[i].str());
340 if (it != LIGHT_COLORS.end()) {
341 // intensities.emplace(it->second, 0);
342 colors[i - 1] = it->second;
Kim Low03ea0352020-11-06 12:45:07 -0800343 }
344 }
Chris Ye3fdbfef2021-01-06 18:45:18 -0800345 return colors;
Kim Low03ea0352020-11-06 12:45:07 -0800346}
347
Prabir Pradhancb42b472022-08-23 16:01:19 +0000348/**
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000349 * Read country code information exposed through the sysfs path and convert it to Layout info.
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000350 */
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000351static std::optional<RawLayoutInfo> readLayoutConfiguration(
352 const std::filesystem::path& sysfsRootPath) {
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000353 // Check the sysfs root path
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000354 int32_t hidCountryCode = -1;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000355 std::string str;
356 if (base::ReadFileToString(sysfsRootPath / "country", &str)) {
357 hidCountryCode = std::stoi(str, nullptr, 16);
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000358 // Update this condition if new supported country codes are added to HID spec.
Vaibhav Devmurari990ff7b2022-12-22 18:23:21 +0000359 if (hidCountryCode > 35 || hidCountryCode < 0) {
360 ALOGE("HID country code should be in range [0, 35], but for sysfs path %s it was %d",
361 sysfsRootPath.c_str(), hidCountryCode);
Vaibhav Devmurari990ff7b2022-12-22 18:23:21 +0000362 }
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000363 }
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000364 const auto it = LAYOUT_INFOS.find(hidCountryCode);
365 if (it != LAYOUT_INFOS.end()) {
366 return it->second;
367 }
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000368
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000369 return std::nullopt;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000370}
371
372/**
Prabir Pradhancb42b472022-08-23 16:01:19 +0000373 * Read information about batteries exposed through the sysfs path.
374 */
375static std::unordered_map<int32_t /*batteryId*/, RawBatteryInfo> readBatteryConfiguration(
376 const std::filesystem::path& sysfsRootPath) {
377 std::unordered_map<int32_t, RawBatteryInfo> batteryInfos;
378 int32_t nextBatteryId = 0;
379 // Check if device has any battery.
380 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::POWER_SUPPLY);
381 for (const auto& nodePath : paths) {
382 RawBatteryInfo info;
383 info.id = ++nextBatteryId;
384 info.path = nodePath;
385 info.name = nodePath.filename();
386
387 // Scan the path for all the files
388 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
389 const auto& files = allFilesInPath(nodePath);
390 for (const auto& file : files) {
391 const auto it = BATTERY_CLASSES.find(file.filename().string());
392 if (it != BATTERY_CLASSES.end()) {
393 info.flags |= it->second;
394 }
395 }
396 batteryInfos.insert_or_assign(info.id, info);
397 ALOGD("configureBatteryLocked rawBatteryId %d name %s", info.id, info.name.c_str());
398 }
399 return batteryInfos;
400}
401
402/**
403 * Read information about lights exposed through the sysfs path.
404 */
405static std::unordered_map<int32_t /*lightId*/, RawLightInfo> readLightsConfiguration(
406 const std::filesystem::path& sysfsRootPath) {
407 std::unordered_map<int32_t, RawLightInfo> lightInfos;
408 int32_t nextLightId = 0;
409 // Check if device has any lights.
410 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::LEDS);
411 for (const auto& nodePath : paths) {
412 RawLightInfo info;
413 info.id = ++nextLightId;
414 info.path = nodePath;
415 info.name = nodePath.filename();
416 info.maxBrightness = std::nullopt;
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000417
418 // Light name should follow the naming pattern <name>:<color>:<function>
419 // Refer kernel docs /leds/leds-class.html for valid supported LED names.
420 std::regex indexPattern("([a-zA-Z0-9_.:]*:)?([a-zA-Z0-9_.]*):([a-zA-Z0-9_.]*)");
421 std::smatch results;
422
423 if (std::regex_match(info.name, results, indexPattern)) {
424 // regex_match will return full match at index 0 and <name> at index 1. For RawLightInfo
425 // we only care about sections <color> and <function> which will be at index 2 and 3.
426 for (int i = 2; i <= 3; i++) {
427 const auto it = LIGHT_CLASSES.find(results.str(i));
428 if (it != LIGHT_CLASSES.end()) {
429 info.flags |= it->second;
430 }
Prabir Pradhancb42b472022-08-23 16:01:19 +0000431 }
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000432
433 // Set name of the raw light to <function> which represents playerIDs for LEDs that
434 // turn on/off based on the current player ID (Refer to PeripheralController.cpp for
435 // player ID logic)
436 info.name = results.str(3);
Prabir Pradhancb42b472022-08-23 16:01:19 +0000437 }
438 // Scan the path for all the files
439 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
440 const auto& files = allFilesInPath(nodePath);
441 for (const auto& file : files) {
442 const auto it = LIGHT_CLASSES.find(file.filename().string());
443 if (it != LIGHT_CLASSES.end()) {
444 info.flags |= it->second;
445 // If the node has maximum brightness, read it
446 if (it->second == InputLightClass::MAX_BRIGHTNESS) {
447 std::string str;
448 if (base::ReadFileToString(file, &str)) {
449 info.maxBrightness = std::stoi(str);
450 }
451 }
452 }
453 }
454 lightInfos.insert_or_assign(info.id, info);
455 ALOGD("configureLightsLocked rawLightId %d name %s", info.id, info.name.c_str());
456 }
457 return lightInfos;
458}
459
Michael Wrightd02c5b62014-02-10 15:10:22 -0800460// --- Global Functions ---
461
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700462ftl::Flags<InputDeviceClass> getAbsAxisUsage(int32_t axis,
463 ftl::Flags<InputDeviceClass> deviceClasses) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800464 // Touch devices get dibs on touch-related axes.
Chris Ye1b0c7342020-07-28 21:57:03 -0700465 if (deviceClasses.test(InputDeviceClass::TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800466 switch (axis) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700467 case ABS_X:
468 case ABS_Y:
469 case ABS_PRESSURE:
470 case ABS_TOOL_WIDTH:
471 case ABS_DISTANCE:
472 case ABS_TILT_X:
473 case ABS_TILT_Y:
474 case ABS_MT_SLOT:
475 case ABS_MT_TOUCH_MAJOR:
476 case ABS_MT_TOUCH_MINOR:
477 case ABS_MT_WIDTH_MAJOR:
478 case ABS_MT_WIDTH_MINOR:
479 case ABS_MT_ORIENTATION:
480 case ABS_MT_POSITION_X:
481 case ABS_MT_POSITION_Y:
482 case ABS_MT_TOOL_TYPE:
483 case ABS_MT_BLOB_ID:
484 case ABS_MT_TRACKING_ID:
485 case ABS_MT_PRESSURE:
486 case ABS_MT_DISTANCE:
Chris Ye1b0c7342020-07-28 21:57:03 -0700487 return InputDeviceClass::TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800488 }
489 }
490
Chris Yef59a2f42020-10-16 12:55:26 -0700491 if (deviceClasses.test(InputDeviceClass::SENSOR)) {
492 switch (axis) {
493 case ABS_X:
494 case ABS_Y:
495 case ABS_Z:
496 case ABS_RX:
497 case ABS_RY:
498 case ABS_RZ:
499 return InputDeviceClass::SENSOR;
500 }
501 }
502
Michael Wright842500e2015-03-13 17:32:02 -0700503 // External stylus gets the pressure axis
Chris Ye1b0c7342020-07-28 21:57:03 -0700504 if (deviceClasses.test(InputDeviceClass::EXTERNAL_STYLUS)) {
Michael Wright842500e2015-03-13 17:32:02 -0700505 if (axis == ABS_PRESSURE) {
Chris Ye1b0c7342020-07-28 21:57:03 -0700506 return InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -0700507 }
508 }
509
Michael Wrightd02c5b62014-02-10 15:10:22 -0800510 // Joystick devices get the rest.
Chris Ye1b0c7342020-07-28 21:57:03 -0700511 return deviceClasses & InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800512}
513
Harry Cuttsea73eaa2023-01-16 17:55:46 +0000514// --- RawAbsoluteAxisInfo ---
515
516std::ostream& operator<<(std::ostream& out, const RawAbsoluteAxisInfo& info) {
517 if (info.valid) {
518 out << "min=" << info.minValue << ", max=" << info.maxValue << ", flat=" << info.flat
519 << ", fuzz=" << info.fuzz << ", resolution=" << info.resolution;
520 } else {
521 out << "unknown range";
522 }
523 return out;
524}
525
Michael Wrightd02c5b62014-02-10 15:10:22 -0800526// --- EventHub::Device ---
527
Prabir Pradhancb42b472022-08-23 16:01:19 +0000528EventHub::Device::Device(int fd, int32_t id, std::string path, InputDeviceIdentifier identifier,
529 std::shared_ptr<const AssociatedDevice> assocDev)
Chris Ye989bb932020-07-04 16:18:59 -0700530 : fd(fd),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700531 id(id),
Prabir Pradhancb42b472022-08-23 16:01:19 +0000532 path(std::move(path)),
533 identifier(std::move(identifier)),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700534 classes(0),
535 configuration(nullptr),
536 virtualKeyMap(nullptr),
537 ffEffectPlaying(false),
538 ffEffectId(-1),
Prabir Pradhancb42b472022-08-23 16:01:19 +0000539 associatedDevice(std::move(assocDev)),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700540 controllerNumber(0),
541 enabled(true),
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000542 isVirtual(fd < 0),
543 currentFrameDropped(false) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800544
545EventHub::Device::~Device() {
546 close();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800547}
548
549void EventHub::Device::close() {
550 if (fd >= 0) {
551 ::close(fd);
552 fd = -1;
553 }
554}
555
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700556status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100557 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700558 if (fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100559 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700560 return -errno;
561 }
562 enabled = true;
563 return OK;
564}
565
566status_t EventHub::Device::disable() {
567 close();
568 enabled = false;
569 return OK;
570}
571
Chris Ye989bb932020-07-04 16:18:59 -0700572bool EventHub::Device::hasValidFd() const {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700573 return !isVirtual && enabled;
574}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800575
Chris Ye3a1e4462020-08-12 10:13:15 -0700576const std::shared_ptr<KeyCharacterMap> EventHub::Device::getKeyCharacterMap() const {
Chris Ye989bb932020-07-04 16:18:59 -0700577 return keyMap.keyCharacterMap;
578}
579
580template <std::size_t N>
581status_t EventHub::Device::readDeviceBitMask(unsigned long ioctlCode, BitArray<N>& bitArray) {
582 if (!hasValidFd()) {
583 return BAD_VALUE;
584 }
585 if ((_IOC_SIZE(ioctlCode) == 0)) {
586 ioctlCode |= _IOC(0, 0, 0, bitArray.bytes());
587 }
588
589 typename BitArray<N>::Buffer buffer;
590 status_t ret = ioctl(fd, ioctlCode, buffer.data());
591 bitArray.loadFromBuffer(buffer);
592 return ret;
593}
594
595void EventHub::Device::configureFd() {
596 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
597 if (classes.test(InputDeviceClass::KEYBOARD)) {
598 // Disable kernel key repeat since we handle it ourselves
599 unsigned int repeatRate[] = {0, 0};
600 if (ioctl(fd, EVIOCSREP, repeatRate)) {
601 ALOGW("Unable to disable kernel key repeat for %s: %s", path.c_str(), strerror(errno));
602 }
603 }
604
605 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
606 // associated with input events. This is important because the input system
607 // uses the timestamps extensively and assumes they were recorded using the monotonic
608 // clock.
609 int clockId = CLOCK_MONOTONIC;
Chris Yef59a2f42020-10-16 12:55:26 -0700610 if (classes.test(InputDeviceClass::SENSOR)) {
611 // Each new sensor event should use the same time base as
612 // SystemClock.elapsedRealtimeNanos().
613 clockId = CLOCK_BOOTTIME;
614 }
Chris Ye989bb932020-07-04 16:18:59 -0700615 bool usingClockIoctl = !ioctl(fd, EVIOCSCLOCKID, &clockId);
616 ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000617
618 // Query the initial state of keys and switches, which is tracked by EventHub.
619 readDeviceState();
620}
621
622void EventHub::Device::readDeviceState() {
623 if (readDeviceBitMask(EVIOCGKEY(0), keyState) < 0) {
624 ALOGD("Unable to query the global key state for %s: %s", path.c_str(), strerror(errno));
625 }
626 if (readDeviceBitMask(EVIOCGSW(0), swState) < 0) {
627 ALOGD("Unable to query the global switch state for %s: %s", path.c_str(), strerror(errno));
628 }
Prabir Pradhan341d0782023-07-14 19:04:10 +0000629
630 // Read absolute axis info and values for all available axes for the device.
631 populateAbsoluteAxisStates();
632}
633
634void EventHub::Device::populateAbsoluteAxisStates() {
635 absState.clear();
636
637 for (int axis = 0; axis <= ABS_MAX; axis++) {
638 if (!absBitmask.test(axis)) {
639 continue;
640 }
641 struct input_absinfo info {};
642 if (ioctl(fd, EVIOCGABS(axis), &info)) {
643 ALOGE("Error reading absolute controller %d for device %s fd %d: %s", axis,
644 identifier.name.c_str(), fd, strerror(errno));
645 continue;
646 }
Prabir Pradhan341d0782023-07-14 19:04:10 +0000647 auto& [axisInfo, value] = absState[axis];
648 axisInfo.valid = true;
649 axisInfo.minValue = info.minimum;
650 axisInfo.maxValue = info.maximum;
651 axisInfo.flat = info.flat;
652 axisInfo.fuzz = info.fuzz;
653 axisInfo.resolution = info.resolution;
654 value = info.value;
655 }
Chris Ye989bb932020-07-04 16:18:59 -0700656}
657
658bool EventHub::Device::hasKeycodeLocked(int keycode) const {
659 if (!keyMap.haveKeyLayout()) {
660 return false;
661 }
662
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700663 std::vector<int32_t> scanCodes = keyMap.keyLayoutMap->findScanCodesForKey(keycode);
Chris Ye989bb932020-07-04 16:18:59 -0700664 const size_t N = scanCodes.size();
665 for (size_t i = 0; i < N && i <= KEY_MAX; i++) {
666 int32_t sc = scanCodes[i];
667 if (sc >= 0 && sc <= KEY_MAX && keyBitmask.test(sc)) {
668 return true;
669 }
670 }
671
Charles Linaadf8d52023-03-30 13:34:54 +0800672 std::vector<int32_t> usageCodes = keyMap.keyLayoutMap->findUsageCodesForKey(keycode);
673 if (usageCodes.size() > 0 && mscBitmask.test(MSC_SCAN)) {
674 return true;
675 }
676
Chris Ye989bb932020-07-04 16:18:59 -0700677 return false;
678}
679
680void EventHub::Device::loadConfigurationLocked() {
681 configurationFile =
682 getInputDeviceConfigurationFilePathByDeviceIdentifier(identifier,
683 InputDeviceConfigurationFileType::
684 CONFIGURATION);
685 if (configurationFile.empty()) {
686 ALOGD("No input device configuration file found for device '%s'.", identifier.name.c_str());
687 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500688 android::base::Result<std::unique_ptr<PropertyMap>> propertyMap =
689 PropertyMap::load(configurationFile.c_str());
690 if (!propertyMap.ok()) {
Chris Ye989bb932020-07-04 16:18:59 -0700691 ALOGE("Error loading input device configuration file for device '%s'. "
692 "Using default configuration.",
693 identifier.name.c_str());
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500694 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500695 configuration = std::move(*propertyMap);
Chris Ye989bb932020-07-04 16:18:59 -0700696 }
697 }
698}
699
700bool EventHub::Device::loadVirtualKeyMapLocked() {
701 // The virtual key map is supplied by the kernel as a system board property file.
702 std::string propPath = "/sys/board_properties/virtualkeys.";
703 propPath += identifier.getCanonicalName();
704 if (access(propPath.c_str(), R_OK)) {
705 return false;
706 }
707 virtualKeyMap = VirtualKeyMap::load(propPath);
708 return virtualKeyMap != nullptr;
709}
710
711status_t EventHub::Device::loadKeyMapLocked() {
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500712 return keyMap.load(identifier, configuration.get());
Chris Ye989bb932020-07-04 16:18:59 -0700713}
714
715bool EventHub::Device::isExternalDeviceLocked() {
716 if (configuration) {
Harry Cuttsf13161a2023-03-08 14:15:49 +0000717 std::optional<bool> isInternal = configuration->getBool("device.internal");
718 if (isInternal.has_value()) {
719 return !isInternal.value();
Chris Ye989bb932020-07-04 16:18:59 -0700720 }
721 }
722 return identifier.bus == BUS_USB || identifier.bus == BUS_BLUETOOTH;
723}
724
725bool EventHub::Device::deviceHasMicLocked() {
726 if (configuration) {
Harry Cuttsf13161a2023-03-08 14:15:49 +0000727 std::optional<bool> hasMic = configuration->getBool("audio.mic");
728 if (hasMic.has_value()) {
729 return hasMic.value();
Chris Ye989bb932020-07-04 16:18:59 -0700730 }
731 }
732 return false;
733}
734
735void EventHub::Device::setLedStateLocked(int32_t led, bool on) {
736 int32_t sc;
737 if (hasValidFd() && mapLed(led, &sc) != NAME_NOT_FOUND) {
738 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -0700739 ev.input_event_sec = 0;
740 ev.input_event_usec = 0;
Chris Ye989bb932020-07-04 16:18:59 -0700741 ev.type = EV_LED;
742 ev.code = sc;
743 ev.value = on ? 1 : 0;
744
745 ssize_t nWrite;
746 do {
747 nWrite = write(fd, &ev, sizeof(struct input_event));
748 } while (nWrite == -1 && errno == EINTR);
749 }
750}
751
752void EventHub::Device::setLedForControllerLocked() {
753 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
754 setLedStateLocked(ALED_CONTROLLER_1 + i, controllerNumber == i + 1);
755 }
756}
757
758status_t EventHub::Device::mapLed(int32_t led, int32_t* outScanCode) const {
759 if (!keyMap.haveKeyLayout()) {
760 return NAME_NOT_FOUND;
761 }
762
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700763 std::optional<int32_t> scanCode = keyMap.keyLayoutMap->findScanCodeForLed(led);
764 if (scanCode.has_value()) {
765 if (*scanCode >= 0 && *scanCode <= LED_MAX && ledBitmask.test(*scanCode)) {
766 *outScanCode = *scanCode;
Chris Ye989bb932020-07-04 16:18:59 -0700767 return NO_ERROR;
768 }
769 }
770 return NAME_NOT_FOUND;
771}
772
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000773void EventHub::Device::trackInputEvent(const struct input_event& event) {
774 switch (event.type) {
775 case EV_KEY: {
776 LOG_ALWAYS_FATAL_IF(!currentFrameDropped &&
777 !keyState.set(static_cast<size_t>(event.code),
778 event.value != 0),
Prabir Pradhan10301422023-07-26 21:48:30 +0000779 "%s: device '%s' received invalid EV_KEY event code: %s value: %d",
780 __func__, identifier.name.c_str(),
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000781 InputEventLookup::getLinuxEvdevLabel(EV_KEY, event.code, 1)
Prabir Pradhan10301422023-07-26 21:48:30 +0000782 .code.c_str(),
783 event.value);
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000784 break;
785 }
786 case EV_SW: {
787 LOG_ALWAYS_FATAL_IF(!currentFrameDropped &&
788 !swState.set(static_cast<size_t>(event.code),
789 event.value != 0),
Prabir Pradhan10301422023-07-26 21:48:30 +0000790 "%s: device '%s' received invalid EV_SW event code: %s value: %d",
791 __func__, identifier.name.c_str(),
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000792 InputEventLookup::getLinuxEvdevLabel(EV_SW, event.code, 1)
Prabir Pradhan10301422023-07-26 21:48:30 +0000793 .code.c_str(),
794 event.value);
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000795 break;
796 }
Prabir Pradhan341d0782023-07-14 19:04:10 +0000797 case EV_ABS: {
Prabir Pradhan10301422023-07-26 21:48:30 +0000798 if (currentFrameDropped) {
799 break;
800 }
Prabir Pradhan341d0782023-07-14 19:04:10 +0000801 auto it = absState.find(event.code);
Prabir Pradhan10301422023-07-26 21:48:30 +0000802 LOG_ALWAYS_FATAL_IF(it == absState.end(),
803 "%s: device '%s' received invalid EV_ABS event code: %s value: %d",
804 __func__, identifier.name.c_str(),
Prabir Pradhan341d0782023-07-14 19:04:10 +0000805 InputEventLookup::getLinuxEvdevLabel(EV_ABS, event.code, 0)
Prabir Pradhan10301422023-07-26 21:48:30 +0000806 .code.c_str(),
807 event.value);
Prabir Pradhan341d0782023-07-14 19:04:10 +0000808 it->second.value = event.value;
809 break;
810 }
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000811 case EV_SYN: {
812 switch (event.code) {
813 case SYN_REPORT:
Arpit Singh1c3d8552024-01-08 14:16:28 +0000814 if (currentFrameDropped) {
815 // To recover after a SYN_DROPPED, we need to query the state of the device
816 // to synchronize our device state with the kernel's to account for the
817 // dropped events on receiving the next SYN_REPORT.
818 // Note we don't drop the SYN_REPORT at this point but it is used by the
819 // InputDevice to reset and repopulate mapper state
820 readDeviceState();
821 currentFrameDropped = false;
822 }
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000823 break;
824 case SYN_DROPPED:
825 // When we receive SYN_DROPPED, all events in the current frame should be
Arpit Singh1c3d8552024-01-08 14:16:28 +0000826 // dropped up to and including next SYN_REPORT
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000827 currentFrameDropped = true;
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000828 break;
829 default:
830 break;
831 }
832 break;
833 }
834 default:
835 break;
836 }
837}
838
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100839/**
840 * Get the capabilities for the current process.
841 * Crashes the system if unable to create / check / destroy the capabilities object.
842 */
843class Capabilities final {
844public:
845 explicit Capabilities() {
846 mCaps = cap_get_proc();
847 LOG_ALWAYS_FATAL_IF(mCaps == nullptr, "Could not get capabilities of the current process");
848 }
849
850 /**
851 * Check whether the current process has a specific capability
852 * in the set of effective capabilities.
853 * Return CAP_SET if the process has the requested capability
854 * Return CAP_CLEAR otherwise.
855 */
856 cap_flag_value_t checkEffectiveCapability(cap_value_t capability) {
857 cap_flag_value_t value;
858 const int result = cap_get_flag(mCaps, capability, CAP_EFFECTIVE, &value);
859 LOG_ALWAYS_FATAL_IF(result == -1, "Could not obtain the requested capability");
860 return value;
861 }
862
863 ~Capabilities() {
864 const int result = cap_free(mCaps);
865 LOG_ALWAYS_FATAL_IF(result == -1, "Could not release the capabilities structure");
866 }
867
868private:
869 cap_t mCaps;
870};
871
872static void ensureProcessCanBlockSuspend() {
873 Capabilities capabilities;
874 const bool canBlockSuspend =
875 capabilities.checkEffectiveCapability(CAP_BLOCK_SUSPEND) == CAP_SET;
876 LOG_ALWAYS_FATAL_IF(!canBlockSuspend,
877 "Input must be able to block suspend to properly process events");
878}
879
Michael Wrightd02c5b62014-02-10 15:10:22 -0800880// --- EventHub ---
881
Michael Wrightd02c5b62014-02-10 15:10:22 -0800882const int EventHub::EPOLL_MAX_EVENTS;
883
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700884EventHub::EventHub(void)
885 : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
886 mNextDeviceId(1),
887 mControllerNumbers(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800888 mNeedToSendFinishedDeviceScan(false),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700889 mNeedToReopenDevices(false),
890 mNeedToScanDevices(true),
891 mPendingEventCount(0),
892 mPendingEventIndex(0),
893 mPendingINotify(false) {
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100894 ensureProcessCanBlockSuspend();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800895
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800896 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800897 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800898
Michael Wright8e9a8562022-02-09 13:44:29 +0000899 mINotifyFd = inotify_init1(IN_CLOEXEC);
Prabir Pradhan952e65b2022-06-23 17:49:55 +0000900 LOG_ALWAYS_FATAL_IF(mINotifyFd < 0, "Could not create inotify instance: %s", strerror(errno));
Usama Arifb27c8e62021-06-03 16:44:09 +0100901
902 std::error_code errorCode;
903 bool isDeviceInotifyAdded = false;
904 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
905 addDeviceInputInotify();
Philip Quinn39b81682019-01-09 22:20:39 -0800906 } else {
Usama Arifb27c8e62021-06-03 16:44:09 +0100907 addDeviceInotify();
908 isDeviceInotifyAdded = true;
909 if (errorCode) {
910 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
911 errorCode.message().c_str());
912 }
913 }
914
915 if (isV4lScanningEnabled() && !isDeviceInotifyAdded) {
916 addDeviceInotify();
917 } else {
Philip Quinn39b81682019-01-09 22:20:39 -0800918 ALOGI("Video device scanning disabled");
919 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800920
Siarhei Vishniakou2d0e9482019-09-24 12:52:47 +0100921 struct epoll_event eventItem = {};
922 eventItem.events = EPOLLIN | EPOLLWAKEUP;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700923 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800924 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800925 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
926
927 int wakeFds[2];
Michael Wright8e9a8562022-02-09 13:44:29 +0000928 result = pipe2(wakeFds, O_CLOEXEC);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800929 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
930
931 mWakeReadPipeFd = wakeFds[0];
932 mWakeWritePipeFd = wakeFds[1];
933
934 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
935 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700936 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800937
938 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
939 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700940 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800941
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700942 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800943 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
944 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700945 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800946}
947
948EventHub::~EventHub(void) {
949 closeAllDevicesLocked();
950
Michael Wrightd02c5b62014-02-10 15:10:22 -0800951 ::close(mEpollFd);
952 ::close(mINotifyFd);
953 ::close(mWakeReadPipeFd);
954 ::close(mWakeWritePipeFd);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800955}
956
Usama Arifb27c8e62021-06-03 16:44:09 +0100957/**
958 * On devices that don't have any input devices (like some development boards), the /dev/input
959 * directory will be absent. However, the user may still plug in an input device at a later time.
960 * Add watch for contents of /dev/input only when /dev/input appears.
961 */
962void EventHub::addDeviceInputInotify() {
963 mDeviceInputWd = inotify_add_watch(mINotifyFd, DEVICE_INPUT_PATH, IN_DELETE | IN_CREATE);
964 LOG_ALWAYS_FATAL_IF(mDeviceInputWd < 0, "Could not register INotify for %s: %s",
965 DEVICE_INPUT_PATH, strerror(errno));
966}
967
968void EventHub::addDeviceInotify() {
969 mDeviceWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
970 LOG_ALWAYS_FATAL_IF(mDeviceWd < 0, "Could not register INotify for %s: %s", DEVICE_PATH,
971 strerror(errno));
972}
973
Michael Wrightd02c5b62014-02-10 15:10:22 -0800974InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000975 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800976 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700977 return device != nullptr ? device->identifier : InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800978}
979
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700980ftl::Flags<InputDeviceClass> EventHub::getDeviceClasses(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000981 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800982 Device* device = getDeviceLocked(deviceId);
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700983 return device != nullptr ? device->classes : ftl::Flags<InputDeviceClass>(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800984}
985
986int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000987 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800988 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700989 return device != nullptr ? device->controllerNumber : 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800990}
991
Harry Cuttsc34f7582023-03-07 16:23:30 +0000992std::optional<PropertyMap> EventHub::getConfiguration(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000993 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800994 Device* device = getDeviceLocked(deviceId);
Harry Cuttsc34f7582023-03-07 16:23:30 +0000995 if (device == nullptr || device->configuration == nullptr) {
996 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -0800997 }
Harry Cuttsc34f7582023-03-07 16:23:30 +0000998 return *device->configuration;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800999}
1000
Harry Cutts207674d2024-06-06 18:53:41 +00001001std::optional<RawAbsoluteAxisInfo> EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis) const {
Arpit Singh77140f42023-06-13 11:35:27 +00001002 if (axis < 0 || axis > ABS_MAX) {
Harry Cutts207674d2024-06-06 18:53:41 +00001003 return std::nullopt;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001004 }
Arpit Singh77140f42023-06-13 11:35:27 +00001005 std::scoped_lock _l(mLock);
Prabir Pradhan341d0782023-07-14 19:04:10 +00001006 const Device* device = getDeviceLocked(deviceId);
Arpit Singh77140f42023-06-13 11:35:27 +00001007 if (device == nullptr) {
Harry Cutts207674d2024-06-06 18:53:41 +00001008 return std::nullopt;
Arpit Singh77140f42023-06-13 11:35:27 +00001009 }
Prabir Pradhan341d0782023-07-14 19:04:10 +00001010 // We can read the RawAbsoluteAxisInfo even if the device is disabled and doesn't have a valid
1011 // fd, because the info is populated once when the device is first opened, and it doesn't change
1012 // throughout the device lifecycle.
1013 auto it = device->absState.find(axis);
1014 if (it == device->absState.end()) {
Harry Cutts207674d2024-06-06 18:53:41 +00001015 return std::nullopt;
Arpit Singh77140f42023-06-13 11:35:27 +00001016 }
Harry Cutts207674d2024-06-06 18:53:41 +00001017 return it->second.info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001018}
1019
1020bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
1021 if (axis >= 0 && axis <= REL_MAX) {
Chris Ye87143712020-11-10 05:05:58 +00001022 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001023 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001024 return device != nullptr ? device->relBitmask.test(axis) : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001025 }
1026 return false;
1027}
1028
1029bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
Chris Ye87143712020-11-10 05:05:58 +00001030 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001031
Chris Ye989bb932020-07-04 16:18:59 -07001032 Device* device = getDeviceLocked(deviceId);
1033 return property >= 0 && property <= INPUT_PROP_MAX && device != nullptr
1034 ? device->propBitmask.test(property)
1035 : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001036}
1037
Chris Yef59a2f42020-10-16 12:55:26 -07001038bool EventHub::hasMscEvent(int32_t deviceId, int mscEvent) const {
1039 std::scoped_lock _l(mLock);
1040
1041 Device* device = getDeviceLocked(deviceId);
1042 return mscEvent >= 0 && mscEvent <= MSC_MAX && device != nullptr
1043 ? device->mscBitmask.test(mscEvent)
1044 : false;
1045}
1046
Michael Wrightd02c5b62014-02-10 15:10:22 -08001047int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001048 if (scanCode < 0 || scanCode > KEY_MAX) {
1049 return AKEY_STATE_UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001050 }
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001051 std::scoped_lock _l(mLock);
1052 const Device* device = getDeviceLocked(deviceId);
1053 if (device == nullptr || !device->hasValidFd() || !device->keyBitmask.test(scanCode)) {
1054 return AKEY_STATE_UNKNOWN;
1055 }
1056 return device->keyState.test(scanCode) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001057}
1058
1059int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
Chris Ye87143712020-11-10 05:05:58 +00001060 std::scoped_lock _l(mLock);
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001061 const Device* device = getDeviceLocked(deviceId);
1062 if (device == nullptr || !device->hasValidFd() || !device->keyMap.haveKeyLayout()) {
1063 return AKEY_STATE_UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001064 }
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001065 const std::vector<int32_t> scanCodes =
1066 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode);
1067 if (scanCodes.empty()) {
1068 return AKEY_STATE_UNKNOWN;
1069 }
1070 return std::any_of(scanCodes.begin(), scanCodes.end(),
1071 [&device](const int32_t sc) {
1072 return sc >= 0 && sc <= KEY_MAX && device->keyState.test(sc);
1073 })
1074 ? AKEY_STATE_DOWN
1075 : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001076}
1077
Philip Junker4af3b3d2021-12-14 10:36:55 +01001078int32_t EventHub::getKeyCodeForKeyLocation(int32_t deviceId, int32_t locationKeyCode) const {
1079 std::scoped_lock _l(mLock);
1080
1081 Device* device = getDeviceLocked(deviceId);
1082 if (device == nullptr || !device->hasValidFd() || device->keyMap.keyCharacterMap == nullptr ||
1083 device->keyMap.keyLayoutMap == nullptr) {
1084 return AKEYCODE_UNKNOWN;
1085 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001086 std::vector<int32_t> scanCodes =
1087 device->keyMap.keyLayoutMap->findScanCodesForKey(locationKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +01001088 if (scanCodes.empty()) {
1089 ALOGW("Failed to get key code for key location: no scan code maps to key code %d for input"
1090 "device %d",
1091 locationKeyCode, deviceId);
1092 return AKEYCODE_UNKNOWN;
1093 }
1094 if (scanCodes.size() > 1) {
1095 ALOGW("Multiple scan codes map to the same key code %d, returning only the first match",
1096 locationKeyCode);
1097 }
1098 int32_t outKeyCode;
1099 status_t mapKeyRes =
Harry Cutts33476232023-01-30 19:57:29 +00001100 device->getKeyCharacterMap()->mapKey(scanCodes[0], /*usageCode=*/0, &outKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +01001101 switch (mapKeyRes) {
1102 case OK:
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001103 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +01001104 case NAME_NOT_FOUND:
1105 // key character map doesn't re-map this scanCode, hence the keyCode remains the same
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001106 outKeyCode = locationKeyCode;
1107 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +01001108 default:
1109 ALOGW("Failed to get key code for key location: Key character map returned error %s",
1110 statusToString(mapKeyRes).c_str());
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001111 outKeyCode = AKEYCODE_UNKNOWN;
1112 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +01001113 }
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001114 // Remap if there is a Key remapping added to the KCM and return the remapped key
1115 return device->getKeyCharacterMap()->applyKeyRemapping(outKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +01001116}
1117
Michael Wrightd02c5b62014-02-10 15:10:22 -08001118int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001119 if (sw < 0 || sw > SW_MAX) {
1120 return AKEY_STATE_UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001121 }
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001122 std::scoped_lock _l(mLock);
1123 const Device* device = getDeviceLocked(deviceId);
1124 if (device == nullptr || !device->hasValidFd() || !device->swBitmask.test(sw)) {
1125 return AKEY_STATE_UNKNOWN;
1126 }
1127 return device->swState.test(sw) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001128}
1129
1130status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
1131 *outValue = 0;
Prabir Pradhan341d0782023-07-14 19:04:10 +00001132 if (axis < 0 || axis > ABS_MAX) {
1133 return NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001134 }
Prabir Pradhan341d0782023-07-14 19:04:10 +00001135 std::scoped_lock _l(mLock);
1136 const Device* device = getDeviceLocked(deviceId);
1137 if (device == nullptr || !device->hasValidFd()) {
1138 return NAME_NOT_FOUND;
1139 }
1140 const auto it = device->absState.find(axis);
1141 if (it == device->absState.end()) {
1142 return NAME_NOT_FOUND;
1143 }
1144 *outValue = it->second.value;
1145 return OK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001146}
1147
Arpit Singh4b4a4572023-11-24 18:19:56 +00001148base::Result<std::vector<int32_t>> EventHub::getMtSlotValues(int32_t deviceId, int32_t axis,
1149 size_t slotCount) const {
1150 std::scoped_lock _l(mLock);
1151 const Device* device = getDeviceLocked(deviceId);
1152 if (device == nullptr || !device->hasValidFd() || !device->absBitmask.test(axis)) {
1153 return base::ResultError("device problem or axis not supported", NAME_NOT_FOUND);
1154 }
1155 std::vector<int32_t> outValues(slotCount + 1);
1156 outValues[0] = axis;
1157 const size_t bufferSize = outValues.size() * sizeof(int32_t);
1158 if (ioctl(device->fd, EVIOCGMTSLOTS(bufferSize), outValues.data()) != OK) {
1159 return base::ErrnoError();
1160 }
1161 return std::move(outValues);
1162}
1163
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001164bool EventHub::markSupportedKeyCodes(int32_t deviceId, const std::vector<int32_t>& keyCodes,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001165 uint8_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +00001166 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001167
1168 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001169 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001170 for (size_t codeIndex = 0; codeIndex < keyCodes.size(); codeIndex++) {
Sergej Salnikove5420e72023-05-11 11:52:54 +00001171 if (device->hasKeycodeLocked(keyCodes[codeIndex])) {
1172 outFlags[codeIndex] = 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001173 }
1174 }
1175 return true;
1176 }
1177 return false;
1178}
1179
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001180void EventHub::addKeyRemapping(int32_t deviceId, int32_t fromKeyCode, int32_t toKeyCode) const {
1181 std::scoped_lock _l(mLock);
1182 Device* device = getDeviceLocked(deviceId);
1183 if (device == nullptr) {
1184 return;
1185 }
1186 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
1187 if (kcm) {
1188 kcm->addKeyRemapping(fromKeyCode, toKeyCode);
1189 }
1190}
1191
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001192status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
1193 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +00001194 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001195 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001196 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001197
Chris Ye66fbac32020-07-06 20:36:43 -07001198 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001199 // Check the key character map first.
Chris Ye3a1e4462020-08-12 10:13:15 -07001200 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
1201 if (kcm) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001202 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
1203 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001204 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001205 }
1206 }
1207
1208 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001209 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -08001210 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001211 status = NO_ERROR;
1212 }
1213 }
1214
1215 if (status == NO_ERROR) {
Chris Ye3a1e4462020-08-12 10:13:15 -07001216 if (kcm) {
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001217 // Remap keys based on user-defined key remappings and key behavior defined in the
1218 // corresponding kcm file
1219 *outKeycode = kcm->applyKeyRemapping(*outKeycode);
1220
1221 // Remap keys based on Key behavior defined in KCM file
1222 std::tie(*outKeycode, *outMetaState) =
1223 kcm->applyKeyBehavior(*outKeycode, metaState);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001224 } else {
1225 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001226 }
1227 }
1228 }
1229
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001230 if (status != NO_ERROR) {
1231 *outKeycode = 0;
1232 *outFlags = 0;
1233 *outMetaState = metaState;
1234 }
1235
1236 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237}
1238
1239status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
Chris Ye87143712020-11-10 05:05:58 +00001240 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001241 Device* device = getDeviceLocked(deviceId);
1242
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001243 if (device == nullptr || !device->keyMap.haveKeyLayout()) {
1244 return NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001245 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001246 std::optional<AxisInfo> info = device->keyMap.keyLayoutMap->mapAxis(scanCode);
1247 if (!info.has_value()) {
1248 return NAME_NOT_FOUND;
1249 }
1250 *outAxisInfo = *info;
1251 return NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001252}
1253
Chris Yef59a2f42020-10-16 12:55:26 -07001254base::Result<std::pair<InputDeviceSensorType, int32_t>> EventHub::mapSensor(int32_t deviceId,
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001255 int32_t absCode) const {
Chris Yef59a2f42020-10-16 12:55:26 -07001256 std::scoped_lock _l(mLock);
1257 Device* device = getDeviceLocked(deviceId);
1258
1259 if (device != nullptr && device->keyMap.haveKeyLayout()) {
1260 return device->keyMap.keyLayoutMap->mapSensor(absCode);
1261 }
1262 return Errorf("Device not found or device has no key layout.");
1263}
1264
Chris Yee2b1e5c2021-03-10 22:45:12 -08001265// Gets the battery info map from battery ID to RawBatteryInfo of the miscellaneous device
1266// associated with the device ID. Returns an empty map if no miscellaneous device found.
1267const std::unordered_map<int32_t, RawBatteryInfo>& EventHub::getBatteryInfoLocked(
1268 int32_t deviceId) const {
1269 static const std::unordered_map<int32_t, RawBatteryInfo> EMPTY_BATTERY_INFO = {};
1270 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001271 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001272 return EMPTY_BATTERY_INFO;
1273 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001274 return device->associatedDevice->batteryInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001275}
1276
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001277std::vector<int32_t> EventHub::getRawBatteryIds(int32_t deviceId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001278 std::scoped_lock _l(mLock);
1279 std::vector<int32_t> batteryIds;
1280
Prabir Pradhan51894782022-08-23 16:29:10 +00001281 for (const auto& [id, info] : getBatteryInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001282 batteryIds.push_back(id);
1283 }
1284
1285 return batteryIds;
1286}
1287
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001288std::optional<RawBatteryInfo> EventHub::getRawBatteryInfo(int32_t deviceId,
1289 int32_t batteryId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001290 std::scoped_lock _l(mLock);
1291
1292 const auto infos = getBatteryInfoLocked(deviceId);
1293
1294 auto it = infos.find(batteryId);
1295 if (it != infos.end()) {
1296 return it->second;
1297 }
1298
1299 return std::nullopt;
1300}
1301
1302// Gets the light info map from light ID to RawLightInfo of the miscellaneous device associated
Prabir Pradhan51894782022-08-23 16:29:10 +00001303// with the device ID. Returns an empty map if no miscellaneous device found.
Chris Yee2b1e5c2021-03-10 22:45:12 -08001304const std::unordered_map<int32_t, RawLightInfo>& EventHub::getLightInfoLocked(
1305 int32_t deviceId) const {
1306 static const std::unordered_map<int32_t, RawLightInfo> EMPTY_LIGHT_INFO = {};
1307 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001308 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001309 return EMPTY_LIGHT_INFO;
1310 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001311 return device->associatedDevice->lightInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001312}
1313
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001314std::vector<int32_t> EventHub::getRawLightIds(int32_t deviceId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001315 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001316 std::vector<int32_t> lightIds;
1317
Prabir Pradhan51894782022-08-23 16:29:10 +00001318 for (const auto& [id, info] : getLightInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001319 lightIds.push_back(id);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001320 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001321
Chris Ye3fdbfef2021-01-06 18:45:18 -08001322 return lightIds;
1323}
1324
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001325std::optional<RawLightInfo> EventHub::getRawLightInfo(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001326 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001327
Chris Yee2b1e5c2021-03-10 22:45:12 -08001328 const auto infos = getLightInfoLocked(deviceId);
1329
1330 auto it = infos.find(lightId);
1331 if (it != infos.end()) {
1332 return it->second;
Chris Ye3fdbfef2021-01-06 18:45:18 -08001333 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001334
Chris Ye3fdbfef2021-01-06 18:45:18 -08001335 return std::nullopt;
1336}
1337
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001338std::optional<int32_t> EventHub::getLightBrightness(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001339 std::scoped_lock _l(mLock);
1340
Chris Yee2b1e5c2021-03-10 22:45:12 -08001341 const auto infos = getLightInfoLocked(deviceId);
1342 auto it = infos.find(lightId);
1343 if (it == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001344 return std::nullopt;
1345 }
1346 std::string buffer;
1347 if (!base::ReadFileToString(it->second.path / LIGHT_NODES.at(InputLightClass::BRIGHTNESS),
1348 &buffer)) {
1349 return std::nullopt;
1350 }
1351 return std::stoi(buffer);
1352}
1353
1354std::optional<std::unordered_map<LightColor, int32_t>> EventHub::getLightIntensities(
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001355 int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001356 std::scoped_lock _l(mLock);
1357
Chris Yee2b1e5c2021-03-10 22:45:12 -08001358 const auto infos = getLightInfoLocked(deviceId);
1359 auto lightIt = infos.find(lightId);
1360 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001361 return std::nullopt;
1362 }
1363
1364 auto ret =
1365 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1366
1367 if (!ret.has_value()) {
1368 return std::nullopt;
1369 }
1370 std::array<LightColor, COLOR_NUM> colors = ret.value();
1371
1372 std::string intensityStr;
1373 if (!base::ReadFileToString(lightIt->second.path /
1374 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY),
1375 &intensityStr)) {
1376 return std::nullopt;
1377 }
1378
1379 // Intensity node outputs 3 color values
1380 std::regex intensityPattern("([0-9]+)\\s([0-9]+)\\s([0-9]+)[\\n]");
1381 std::smatch results;
1382
1383 if (!std::regex_match(intensityStr, results, intensityPattern)) {
1384 return std::nullopt;
1385 }
1386 std::unordered_map<LightColor, int32_t> intensities;
1387 for (size_t i = 1; i < results.size(); i++) {
1388 int value = std::stoi(results[i].str());
1389 intensities.emplace(colors[i - 1], value);
1390 }
1391 return intensities;
1392}
1393
1394void EventHub::setLightBrightness(int32_t deviceId, int32_t lightId, int32_t brightness) {
1395 std::scoped_lock _l(mLock);
1396
Chris Yee2b1e5c2021-03-10 22:45:12 -08001397 const auto infos = getLightInfoLocked(deviceId);
1398 auto lightIt = infos.find(lightId);
1399 if (lightIt == infos.end()) {
1400 ALOGE("%s lightId %d not found ", __func__, lightId);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001401 return;
1402 }
1403
1404 if (!base::WriteStringToFile(std::to_string(brightness),
1405 lightIt->second.path /
1406 LIGHT_NODES.at(InputLightClass::BRIGHTNESS))) {
1407 ALOGE("Can not write to file, error: %s", strerror(errno));
1408 }
1409}
1410
1411void EventHub::setLightIntensities(int32_t deviceId, int32_t lightId,
1412 std::unordered_map<LightColor, int32_t> intensities) {
1413 std::scoped_lock _l(mLock);
1414
Chris Yee2b1e5c2021-03-10 22:45:12 -08001415 const auto infos = getLightInfoLocked(deviceId);
1416 auto lightIt = infos.find(lightId);
1417 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001418 ALOGE("Light Id %d does not exist.", lightId);
1419 return;
1420 }
1421
1422 auto ret =
1423 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1424
1425 if (!ret.has_value()) {
1426 return;
1427 }
1428 std::array<LightColor, COLOR_NUM> colors = ret.value();
1429
1430 std::string rgbStr;
1431 for (size_t i = 0; i < COLOR_NUM; i++) {
1432 auto it = intensities.find(colors[i]);
1433 if (it != intensities.end()) {
1434 rgbStr += std::to_string(it->second);
1435 // Insert space between colors
1436 if (i < COLOR_NUM - 1) {
1437 rgbStr += " ";
1438 }
1439 }
1440 }
1441 // Append new line
1442 rgbStr += "\n";
1443
1444 if (!base::WriteStringToFile(rgbStr,
1445 lightIt->second.path /
1446 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY))) {
1447 ALOGE("Can not write to file, error: %s", strerror(errno));
1448 }
1449}
1450
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001451std::optional<RawLayoutInfo> EventHub::getRawLayoutInfo(int32_t deviceId) const {
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001452 std::scoped_lock _l(mLock);
1453 Device* device = getDeviceLocked(deviceId);
1454 if (device == nullptr || !device->associatedDevice) {
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001455 return std::nullopt;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001456 }
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001457 return device->associatedDevice->layoutInfo;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001458}
1459
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001460void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Chris Ye87143712020-11-10 05:05:58 +00001461 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001462
1463 mExcludedDevices = devices;
1464}
1465
1466bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
Chris Ye87143712020-11-10 05:05:58 +00001467 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001468 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001469 if (device != nullptr && scanCode >= 0 && scanCode <= KEY_MAX) {
1470 return device->keyBitmask.test(scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001471 }
1472 return false;
1473}
1474
Arthur Hungcb40a002021-08-03 14:31:01 +00001475bool EventHub::hasKeyCode(int32_t deviceId, int32_t keyCode) const {
1476 std::scoped_lock _l(mLock);
1477 Device* device = getDeviceLocked(deviceId);
1478 if (device != nullptr) {
1479 return device->hasKeycodeLocked(keyCode);
1480 }
1481 return false;
1482}
1483
Michael Wrightd02c5b62014-02-10 15:10:22 -08001484bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
Chris Ye87143712020-11-10 05:05:58 +00001485 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001486 Device* device = getDeviceLocked(deviceId);
1487 int32_t sc;
Chris Ye989bb932020-07-04 16:18:59 -07001488 if (device != nullptr && device->mapLed(led, &sc) == NO_ERROR) {
Chris Ye66fbac32020-07-06 20:36:43 -07001489 return device->ledBitmask.test(sc);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001490 }
1491 return false;
1492}
1493
1494void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
Chris Ye87143712020-11-10 05:05:58 +00001495 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001496 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -07001497 if (device != nullptr && device->hasValidFd()) {
1498 device->setLedStateLocked(led, on);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001499 }
1500}
1501
1502void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001503 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001504 outVirtualKeys.clear();
1505
Chris Ye87143712020-11-10 05:05:58 +00001506 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001507 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001508 if (device != nullptr && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001509 const std::vector<VirtualKeyDefinition> virtualKeys =
1510 device->virtualKeyMap->getVirtualKeys();
1511 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001512 }
1513}
1514
Chris Ye3a1e4462020-08-12 10:13:15 -07001515const std::shared_ptr<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001516 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001517 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001518 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001519 return device->getKeyCharacterMap();
1520 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001521 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001522}
1523
Vaibhav Devmurari23e8ae92022-12-29 12:07:56 +00001524// If provided map is null, it will reset key character map to default KCM.
Chris Ye3a1e4462020-08-12 10:13:15 -07001525bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, std::shared_ptr<KeyCharacterMap> map) {
Chris Ye87143712020-11-10 05:05:58 +00001526 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001527 Device* device = getDeviceLocked(deviceId);
Vaibhav Devmurari23e8ae92022-12-29 12:07:56 +00001528 if (device == nullptr || device->keyMap.keyCharacterMap == nullptr) {
Philip Junker90bc9492021-12-10 18:39:42 +01001529 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001530 }
Vaibhav Devmurari23e8ae92022-12-29 12:07:56 +00001531 if (map == nullptr) {
1532 device->keyMap.keyCharacterMap->clearLayoutOverlay();
1533 return true;
1534 }
Philip Junker90bc9492021-12-10 18:39:42 +01001535 device->keyMap.keyCharacterMap->combine(*map);
1536 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001537}
1538
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001539static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
1540 std::string rawDescriptor;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001541 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001542 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001543 if (!identifier.uniqueId.empty()) {
1544 rawDescriptor += "uniqueId:";
1545 rawDescriptor += identifier.uniqueId;
Josh Bartel938632f2022-07-19 15:34:22 -05001546 }
1547 if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001548 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001549 }
1550
1551 if (identifier.vendor == 0 && identifier.product == 0) {
1552 // If we don't know the vendor and product id, then the device is probably
1553 // built-in so we need to rely on other information to uniquely identify
1554 // the input device. Usually we try to avoid relying on the device name or
1555 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001556 if (!identifier.name.empty()) {
1557 rawDescriptor += "name:";
1558 rawDescriptor += identifier.name;
1559 } else if (!identifier.location.empty()) {
1560 rawDescriptor += "location:";
1561 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001562 }
1563 }
1564 identifier.descriptor = sha1(rawDescriptor);
1565 return rawDescriptor;
1566}
1567
1568void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
1569 // Compute a device descriptor that uniquely identifies the device.
1570 // The descriptor is assumed to be a stable identifier. Its value should not
1571 // change between reboots, reconnections, firmware updates or new releases
1572 // of Android. In practice we sometimes get devices that cannot be uniquely
1573 // identified. In this case we enforce uniqueness between connected devices.
1574 // Ideally, we also want the descriptor to be short and relatively opaque.
Josh Bartel938632f2022-07-19 15:34:22 -05001575 // Note that we explicitly do not use the path or location for external devices
1576 // as their path or location will change as they are plugged/unplugged or moved
1577 // to different ports. We do fallback to using name and location in the case of
1578 // internal devices which are detected by the vendor and product being 0 in
1579 // generateDescriptor. If two identical descriptors are detected we will fallback
1580 // to using a 'nonce' and incrementing it until the new descriptor no longer has
1581 // a match with any existing descriptors.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001582
1583 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001584 std::string rawDescriptor = generateDescriptor(identifier);
Josh Bartel938632f2022-07-19 15:34:22 -05001585 // Enforce that the generated descriptor is unique.
1586 while (hasDeviceWithDescriptorLocked(identifier.descriptor)) {
1587 identifier.nonce++;
1588 rawDescriptor = generateDescriptor(identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001589 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001590 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001591 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001592}
1593
Prabir Pradhancb42b472022-08-23 16:01:19 +00001594std::shared_ptr<const EventHub::AssociatedDevice> EventHub::obtainAssociatedDeviceLocked(
1595 const std::filesystem::path& devicePath) const {
1596 const std::optional<std::filesystem::path> sysfsRootPathOpt =
1597 getSysfsRootPath(devicePath.c_str());
1598 if (!sysfsRootPathOpt) {
1599 return nullptr;
1600 }
1601
1602 const auto& path = *sysfsRootPathOpt;
Prabir Pradhancb42b472022-08-23 16:01:19 +00001603
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00001604 std::shared_ptr<const AssociatedDevice> associatedDevice = std::make_shared<AssociatedDevice>(
Prabir Pradhancb42b472022-08-23 16:01:19 +00001605 AssociatedDevice{.sysfsRootPath = path,
1606 .batteryInfos = readBatteryConfiguration(path),
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001607 .lightInfos = readLightsConfiguration(path),
1608 .layoutInfo = readLayoutConfiguration(path)});
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00001609
1610 bool associatedDeviceChanged = false;
1611 for (const auto& [id, dev] : mDevices) {
1612 if (dev->associatedDevice && dev->associatedDevice->sysfsRootPath == path) {
1613 if (*associatedDevice != *dev->associatedDevice) {
1614 associatedDeviceChanged = true;
1615 dev->associatedDevice = associatedDevice;
1616 }
1617 associatedDevice = dev->associatedDevice;
1618 }
1619 }
1620 ALOGI_IF(associatedDeviceChanged,
1621 "The AssociatedDevice changed for path '%s'. Using new AssociatedDevice: %s",
1622 path.c_str(), associatedDevice->dump().c_str());
1623
1624 return associatedDevice;
Prabir Pradhancb42b472022-08-23 16:01:19 +00001625}
1626
Vaibhav Devmurari5fc7d852023-03-17 18:43:33 +00001627bool EventHub::AssociatedDevice::isChanged() const {
1628 std::unordered_map<int32_t, RawBatteryInfo> newBatteryInfos =
1629 readBatteryConfiguration(sysfsRootPath);
1630 std::unordered_map<int32_t, RawLightInfo> newLightInfos =
1631 readLightsConfiguration(sysfsRootPath);
1632 std::optional<RawLayoutInfo> newLayoutInfo = readLayoutConfiguration(sysfsRootPath);
1633
1634 if (newBatteryInfos == batteryInfos && newLightInfos == lightInfos &&
1635 newLayoutInfo == layoutInfo) {
1636 return false;
1637 }
1638 return true;
1639}
1640
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001641void EventHub::vibrate(int32_t deviceId, const VibrationElement& element) {
Chris Ye87143712020-11-10 05:05:58 +00001642 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001643 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001644 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001645 ff_effect effect;
1646 memset(&effect, 0, sizeof(effect));
1647 effect.type = FF_RUMBLE;
1648 effect.id = device->ffEffectId;
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001649 // evdev FF_RUMBLE effect only supports two channels of vibration.
Chris Ye6393a262020-08-04 19:41:36 -07001650 effect.u.rumble.strong_magnitude = element.getMagnitude(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1651 effect.u.rumble.weak_magnitude = element.getMagnitude(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001652 effect.replay.length = element.duration.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001653 effect.replay.delay = 0;
1654 if (ioctl(device->fd, EVIOCSFF, &effect)) {
1655 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001656 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001657 return;
1658 }
1659 device->ffEffectId = effect.id;
1660
1661 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -07001662 ev.input_event_sec = 0;
1663 ev.input_event_usec = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001664 ev.type = EV_FF;
1665 ev.code = device->ffEffectId;
1666 ev.value = 1;
1667 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1668 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001669 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001670 return;
1671 }
1672 device->ffEffectPlaying = true;
1673 }
1674}
1675
1676void EventHub::cancelVibrate(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001677 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001678 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001679 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001680 if (device->ffEffectPlaying) {
1681 device->ffEffectPlaying = false;
1682
1683 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -07001684 ev.input_event_sec = 0;
1685 ev.input_event_usec = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001686 ev.type = EV_FF;
1687 ev.code = device->ffEffectId;
1688 ev.value = 0;
1689 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1690 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001691 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001692 return;
1693 }
1694 }
1695 }
1696}
1697
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001698std::vector<int32_t> EventHub::getVibratorIds(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001699 std::scoped_lock _l(mLock);
1700 std::vector<int32_t> vibrators;
1701 Device* device = getDeviceLocked(deviceId);
1702 if (device != nullptr && device->hasValidFd() &&
1703 device->classes.test(InputDeviceClass::VIBRATOR)) {
1704 vibrators.push_back(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1705 vibrators.push_back(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
1706 }
1707 return vibrators;
1708}
1709
Josh Bartel938632f2022-07-19 15:34:22 -05001710/**
1711 * Checks both mDevices and mOpeningDevices for a device with the descriptor passed.
1712 */
1713bool EventHub::hasDeviceWithDescriptorLocked(const std::string& descriptor) const {
1714 for (const auto& device : mOpeningDevices) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001715 if (descriptor == device->identifier.descriptor) {
Josh Bartel938632f2022-07-19 15:34:22 -05001716 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001717 }
1718 }
Josh Bartel938632f2022-07-19 15:34:22 -05001719
1720 for (const auto& [id, device] : mDevices) {
1721 if (descriptor == device->identifier.descriptor) {
1722 return true;
1723 }
1724 }
1725 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001726}
1727
1728EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001729 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001730 deviceId = mBuiltInKeyboardId;
1731 }
Chris Ye989bb932020-07-04 16:18:59 -07001732 const auto& it = mDevices.find(deviceId);
1733 return it != mDevices.end() ? it->second.get() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001734}
1735
Chris Ye8594e192020-07-14 10:34:06 -07001736EventHub::Device* EventHub::getDeviceByPathLocked(const std::string& devicePath) const {
Chris Ye989bb932020-07-04 16:18:59 -07001737 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001738 if (device->path == devicePath) {
Chris Ye989bb932020-07-04 16:18:59 -07001739 return device.get();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001740 }
1741 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001742 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001743}
1744
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001745/**
1746 * The file descriptor could be either input device, or a video device (associated with a
1747 * specific input device). Check both cases here, and return the device that this event
1748 * belongs to. Caller can compare the fd's once more to determine event type.
1749 * Looks through all input devices, and only attached video devices. Unattached video
1750 * devices are ignored.
1751 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001752EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
Chris Ye989bb932020-07-04 16:18:59 -07001753 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001754 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001755 // This is an input device event
Chris Ye989bb932020-07-04 16:18:59 -07001756 return device.get();
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001757 }
1758 if (device->videoDevice && device->videoDevice->getFd() == fd) {
1759 // This is a video device event
Chris Ye989bb932020-07-04 16:18:59 -07001760 return device.get();
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001761 }
1762 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001763 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
1764 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001765 return nullptr;
1766}
1767
Chris Yee2b1e5c2021-03-10 22:45:12 -08001768std::optional<int32_t> EventHub::getBatteryCapacity(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001769 std::filesystem::path batteryPath;
1770 {
1771 // Do not read the sysfs node to get the battery state while holding
1772 // the EventHub lock. For some peripheral devices, reading battery state
1773 // can be broken and take 5+ seconds. Holding the lock in this case would
1774 // block all other event processing during this time. For now, we assume this
1775 // call never happens on the InputReader thread and read the sysfs node outside
1776 // the lock to prevent event processing from being blocked by this call.
1777 std::scoped_lock _l(mLock);
Kim Low03ea0352020-11-06 12:45:07 -08001778
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001779 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001780 auto it = infos.find(batteryId);
1781 if (it == infos.end()) {
1782 return std::nullopt;
1783 }
1784 batteryPath = it->second.path;
1785 } // release lock
1786
Chris Yee2b1e5c2021-03-10 22:45:12 -08001787 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001788
1789 // Some devices report battery capacity as an integer through the "capacity" file
Andy Chenf9f1a022022-08-29 20:07:10 -04001790 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001791 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001792 return std::stoi(base::Trim(buffer));
Kim Low03ea0352020-11-06 12:45:07 -08001793 }
1794
1795 // Other devices report capacity as an enum value POWER_SUPPLY_CAPACITY_LEVEL_XXX
1796 // These values are taken from kernel source code include/linux/power_supply.h
Andy Chenf9f1a022022-08-29 20:07:10 -04001797 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY_LEVEL),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001798 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001799 // Remove any white space such as trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001800 const auto levelIt = BATTERY_LEVEL.find(base::Trim(buffer));
1801 if (levelIt != BATTERY_LEVEL.end()) {
1802 return levelIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001803 }
1804 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001805
Kim Low03ea0352020-11-06 12:45:07 -08001806 return std::nullopt;
1807}
1808
Chris Yee2b1e5c2021-03-10 22:45:12 -08001809std::optional<int32_t> EventHub::getBatteryStatus(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001810 std::filesystem::path batteryPath;
1811 {
1812 // Do not read the sysfs node to get the battery state while holding
1813 // the EventHub lock. For some peripheral devices, reading battery state
1814 // can be broken and take 5+ seconds. Holding the lock in this case would
1815 // block all other event processing during this time. For now, we assume this
1816 // call never happens on the InputReader thread and read the sysfs node outside
1817 // the lock to prevent event processing from being blocked by this call.
1818 std::scoped_lock _l(mLock);
1819
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001820 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001821 auto it = infos.find(batteryId);
1822 if (it == infos.end()) {
1823 return std::nullopt;
1824 }
1825 batteryPath = it->second.path;
1826 } // release lock
1827
Chris Yee2b1e5c2021-03-10 22:45:12 -08001828 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001829
Andy Chenf9f1a022022-08-29 20:07:10 -04001830 if (!base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::STATUS),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001831 &buffer)) {
Kim Low03ea0352020-11-06 12:45:07 -08001832 ALOGE("Failed to read sysfs battery info: %s", strerror(errno));
1833 return std::nullopt;
1834 }
1835
Chris Yed1936772021-02-22 10:30:40 -08001836 // Remove white space like trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001837 const auto statusIt = BATTERY_STATUS.find(base::Trim(buffer));
1838 if (statusIt != BATTERY_STATUS.end()) {
1839 return statusIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001840 }
1841
1842 return std::nullopt;
1843}
1844
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001845std::vector<RawEvent> EventHub::getEvents(int timeoutMillis) {
Chris Ye87143712020-11-10 05:05:58 +00001846 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001847
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001848 std::array<input_event, EVENT_BUFFER_SIZE> readBuffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001849
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001850 std::vector<RawEvent> events;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001851 bool awoken = false;
1852 for (;;) {
1853 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
1854
1855 // Reopen input devices if needed.
1856 if (mNeedToReopenDevices) {
1857 mNeedToReopenDevices = false;
1858
1859 ALOGI("Reopening all input devices due to a configuration change.");
1860
1861 closeAllDevicesLocked();
1862 mNeedToScanDevices = true;
1863 break; // return to the caller before we actually rescan
1864 }
1865
1866 // Report any devices that had last been added/removed.
Chris Ye989bb932020-07-04 16:18:59 -07001867 for (auto it = mClosingDevices.begin(); it != mClosingDevices.end();) {
1868 std::unique_ptr<Device> device = std::move(*it);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001869 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001870 const int32_t deviceId = (device->id == mBuiltInKeyboardId)
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001871 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
1872 : device->id;
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001873 events.push_back({
1874 .when = now,
1875 .deviceId = deviceId,
1876 .type = DEVICE_REMOVED,
1877 });
Chris Ye989bb932020-07-04 16:18:59 -07001878 it = mClosingDevices.erase(it);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001879 mNeedToSendFinishedDeviceScan = true;
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001880 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001881 break;
1882 }
1883 }
1884
1885 if (mNeedToScanDevices) {
1886 mNeedToScanDevices = false;
1887 scanDevicesLocked();
1888 mNeedToSendFinishedDeviceScan = true;
1889 }
1890
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001891 while (!mOpeningDevices.empty()) {
1892 std::unique_ptr<Device> device = std::move(*mOpeningDevices.rbegin());
1893 mOpeningDevices.pop_back();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001894 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001895 const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1896 events.push_back({
1897 .when = now,
1898 .deviceId = deviceId,
1899 .type = DEVICE_ADDED,
1900 });
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001901
1902 // Try to find a matching video device by comparing device names
1903 for (auto it = mUnattachedVideoDevices.begin(); it != mUnattachedVideoDevices.end();
1904 it++) {
1905 std::unique_ptr<TouchVideoDevice>& videoDevice = *it;
Chris Yed3fef462021-03-07 17:10:08 -08001906 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001907 // videoDevice was transferred to 'device'
1908 it = mUnattachedVideoDevices.erase(it);
1909 break;
1910 }
1911 }
1912
1913 auto [dev_it, inserted] = mDevices.insert_or_assign(device->id, std::move(device));
1914 if (!inserted) {
Chris Ye989bb932020-07-04 16:18:59 -07001915 ALOGW("Device id %d exists, replaced.", device->id);
1916 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001917 mNeedToSendFinishedDeviceScan = true;
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001918 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001919 break;
1920 }
1921 }
1922
1923 if (mNeedToSendFinishedDeviceScan) {
1924 mNeedToSendFinishedDeviceScan = false;
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001925 events.push_back({
1926 .when = now,
1927 .type = FINISHED_DEVICE_SCAN,
1928 });
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001929 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001930 break;
1931 }
1932 }
1933
1934 // Grab the next input event.
1935 bool deviceChanged = false;
1936 while (mPendingEventIndex < mPendingEventCount) {
1937 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001938 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001939 if (eventItem.events & EPOLLIN) {
1940 mPendingINotify = true;
1941 } else {
1942 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
1943 }
1944 continue;
1945 }
1946
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001947 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001948 if (eventItem.events & EPOLLIN) {
1949 ALOGV("awoken after wake()");
1950 awoken = true;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001951 char wakeReadBuffer[16];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001952 ssize_t nRead;
1953 do {
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001954 nRead = read(mWakeReadPipeFd, wakeReadBuffer, sizeof(wakeReadBuffer));
1955 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(wakeReadBuffer));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001956 } else {
1957 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001958 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001959 }
1960 continue;
1961 }
1962
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001963 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Chris Ye989bb932020-07-04 16:18:59 -07001964 if (device == nullptr) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001965 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
1966 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001967 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001968 continue;
1969 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001970 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
1971 if (eventItem.events & EPOLLIN) {
1972 size_t numFrames = device->videoDevice->readAndQueueFrames();
1973 if (numFrames == 0) {
1974 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001975 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001976 }
1977 } else if (eventItem.events & EPOLLHUP) {
1978 // TODO(b/121395353) - consider adding EPOLLRDHUP
1979 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001980 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001981 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1982 device->videoDevice = nullptr;
1983 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001984 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1985 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001986 ALOG_ASSERT(!DEBUG);
1987 }
1988 continue;
1989 }
1990 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -08001991 if (eventItem.events & EPOLLIN) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001992 int32_t readSize =
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001993 read(device->fd, readBuffer.data(),
1994 sizeof(decltype(readBuffer)::value_type) * readBuffer.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001995 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
1996 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -07001997 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001998 " capacity: %zu errno: %d)\n",
1999 device->fd, readSize, readBuffer.size(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002000 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07002001 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002002 } else if (readSize < 0) {
2003 if (errno != EAGAIN && errno != EINTR) {
2004 ALOGW("could not get event (errno=%d)", errno);
2005 }
2006 } else if ((readSize % sizeof(struct input_event)) != 0) {
2007 ALOGE("could not get event (wrong size: %d)", readSize);
2008 } else {
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002009 const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002010
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002011 const size_t count = size_t(readSize) / sizeof(struct input_event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002012 for (size_t i = 0; i < count; i++) {
2013 struct input_event& iev = readBuffer[i];
Prabir Pradhan9762ac92023-07-13 21:45:12 +00002014 device->trackInputEvent(iev);
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002015 events.push_back({
2016 .when = processEventTimestamp(iev),
2017 .readTime = systemTime(SYSTEM_TIME_MONOTONIC),
2018 .deviceId = deviceId,
2019 .type = iev.type,
2020 .code = iev.code,
2021 .value = iev.value,
2022 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08002023 }
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07002024 if (events.size() >= EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002025 // The result buffer is full. Reset the pending event index
2026 // so we will try to read the device again on the next iteration.
2027 mPendingEventIndex -= 1;
2028 break;
2029 }
2030 }
2031 } else if (eventItem.events & EPOLLHUP) {
2032 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002033 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002034 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07002035 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002036 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002037 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
2038 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002039 }
2040 }
2041
2042 // readNotify() will modify the list of devices so this must be done after
2043 // processing all other events to ensure that we read all remaining events
2044 // before closing the devices.
2045 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
2046 mPendingINotify = false;
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002047 const auto res = readNotifyLocked();
2048 if (!res.ok()) {
2049 ALOGW("Failed to read from inotify: %s", res.error().message().c_str());
2050 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002051 deviceChanged = true;
2052 }
2053
2054 // Report added or removed devices immediately.
2055 if (deviceChanged) {
2056 continue;
2057 }
2058
2059 // Return now if we have collected any events or if we were explicitly awoken.
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002060 if (!events.empty() || awoken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002061 break;
2062 }
2063
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01002064 // Poll for events.
2065 // When a device driver has pending (unread) events, it acquires
2066 // a kernel wake lock. Once the last pending event has been read, the device
2067 // driver will release the kernel wake lock, but the epoll will hold the wakelock,
2068 // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
2069 // is called again for the same fd that produced the event.
2070 // Thus the system can only sleep if there are no events pending or
2071 // currently being processed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002072 //
2073 // The timeout is advisory only. If the device is asleep, it will not wake just to
2074 // service the timeout.
2075 mPendingEventIndex = 0;
2076
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01002077 mLock.unlock(); // release lock before poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08002078
2079 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
2080
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01002081 mLock.lock(); // reacquire lock after poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08002082
2083 if (pollResult == 0) {
2084 // Timed out.
2085 mPendingEventCount = 0;
2086 break;
2087 }
2088
2089 if (pollResult < 0) {
2090 // An error occurred.
2091 mPendingEventCount = 0;
2092
2093 // Sleep after errors to avoid locking up the system.
2094 // Hopefully the error is transient.
2095 if (errno != EINTR) {
2096 ALOGW("poll failed (errno=%d)\n", errno);
2097 usleep(100000);
2098 }
2099 } else {
2100 // Some events occurred.
2101 mPendingEventCount = size_t(pollResult);
2102 }
2103 }
2104
2105 // All done, return the number of events we read.
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002106 return events;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002107}
2108
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08002109std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002110 std::scoped_lock _l(mLock);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08002111
2112 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07002113 if (device == nullptr || !device->videoDevice) {
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08002114 return {};
2115 }
2116 return device->videoDevice->consumeFrames();
2117}
2118
Michael Wrightd02c5b62014-02-10 15:10:22 -08002119void EventHub::wake() {
2120 ALOGV("wake() called");
2121
2122 ssize_t nWrite;
2123 do {
2124 nWrite = write(mWakeWritePipeFd, "W", 1);
2125 } while (nWrite == -1 && errno == EINTR);
2126
2127 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002128 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002129 }
2130}
2131
2132void EventHub::scanDevicesLocked() {
Usama Arifb27c8e62021-06-03 16:44:09 +01002133 status_t result;
2134 std::error_code errorCode;
2135
2136 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
2137 result = scanDirLocked(DEVICE_INPUT_PATH);
2138 if (result < 0) {
2139 ALOGE("scan dir failed for %s", DEVICE_INPUT_PATH);
2140 }
2141 } else {
2142 if (errorCode) {
2143 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
2144 errorCode.message().c_str());
2145 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002146 }
Philip Quinn39b81682019-01-09 22:20:39 -08002147 if (isV4lScanningEnabled()) {
Usama Arifb27c8e62021-06-03 16:44:09 +01002148 result = scanVideoDirLocked(DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08002149 if (result != OK) {
Usama Arifb27c8e62021-06-03 16:44:09 +01002150 ALOGE("scan video dir failed for %s", DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08002151 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002152 }
Chris Ye989bb932020-07-04 16:18:59 -07002153 if (mDevices.find(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) == mDevices.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002154 createVirtualKeyboardLocked();
2155 }
2156}
2157
2158// ----------------------------------------------------------------------------
2159
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002160status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002161 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002162 struct epoll_event eventItem = {};
2163 eventItem.events = EPOLLIN | EPOLLWAKEUP;
2164 eventItem.data.fd = fd;
2165 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
2166 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002167 return -errno;
2168 }
2169 return OK;
2170}
2171
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002172status_t EventHub::unregisterFdFromEpoll(int fd) {
2173 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
2174 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
2175 return -errno;
2176 }
2177 return OK;
2178}
2179
Chris Ye989bb932020-07-04 16:18:59 -07002180status_t EventHub::registerDeviceForEpollLocked(Device& device) {
2181 status_t result = registerFdForEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002182 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07002183 ALOGE("Could not add input device fd to epoll for device %" PRId32, device.id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002184 return result;
2185 }
Chris Ye989bb932020-07-04 16:18:59 -07002186 if (device.videoDevice) {
2187 registerVideoDeviceForEpollLocked(*device.videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002188 }
2189 return result;
2190}
2191
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002192void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
2193 status_t result = registerFdForEpoll(videoDevice.getFd());
2194 if (result != OK) {
2195 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
2196 }
2197}
2198
Chris Ye989bb932020-07-04 16:18:59 -07002199status_t EventHub::unregisterDeviceFromEpollLocked(Device& device) {
2200 if (device.hasValidFd()) {
2201 status_t result = unregisterFdFromEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002202 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07002203 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device.id);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002204 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002205 }
2206 }
Chris Ye989bb932020-07-04 16:18:59 -07002207 if (device.videoDevice) {
2208 unregisterVideoDeviceFromEpollLocked(*device.videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002209 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002210 return OK;
2211}
2212
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002213void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
2214 if (videoDevice.hasValidFd()) {
2215 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
2216 if (result != OK) {
2217 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002218 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002219 }
2220 }
2221}
2222
Chris Yed3fef462021-03-07 17:10:08 -08002223void EventHub::reportDeviceAddedForStatisticsLocked(const InputDeviceIdentifier& identifier,
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002224 ftl::Flags<InputDeviceClass> classes) {
Chris Ye657c2f02021-05-25 16:24:37 -07002225 SHA256_CTX ctx;
2226 SHA256_Init(&ctx);
2227 SHA256_Update(&ctx, reinterpret_cast<const uint8_t*>(identifier.uniqueId.c_str()),
2228 identifier.uniqueId.size());
2229 std::array<uint8_t, SHA256_DIGEST_LENGTH> digest;
2230 SHA256_Final(digest.data(), &ctx);
2231
2232 std::string obfuscatedId;
2233 for (size_t i = 0; i < OBFUSCATED_LENGTH; i++) {
2234 obfuscatedId += StringPrintf("%02x", digest[i]);
2235 }
2236
Chris Yed3fef462021-03-07 17:10:08 -08002237 android::util::stats_write(android::util::INPUTDEVICE_REGISTERED, identifier.name.c_str(),
2238 identifier.vendor, identifier.product, identifier.version,
Chris Ye657c2f02021-05-25 16:24:37 -07002239 identifier.bus, obfuscatedId.c_str(), classes.get());
Chris Yed3fef462021-03-07 17:10:08 -08002240}
2241
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002242void EventHub::openDeviceLocked(const std::string& devicePath) {
2243 // If an input device happens to register around the time when EventHub's constructor runs, it
2244 // is possible that the same input event node (for example, /dev/input/event3) will be noticed
2245 // in both 'inotify' callback and also in the 'scanDirLocked' pass. To prevent duplicate devices
2246 // from getting registered, ensure that this path is not already covered by an existing device.
2247 for (const auto& [deviceId, device] : mDevices) {
2248 if (device->path == devicePath) {
2249 return; // device was already registered
2250 }
2251 }
2252
Michael Wrightd02c5b62014-02-10 15:10:22 -08002253 char buffer[80];
2254
Chris Ye8594e192020-07-14 10:34:06 -07002255 ALOGV("Opening device: %s", devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002256
Chris Ye8594e192020-07-14 10:34:06 -07002257 int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002258 if (fd < 0) {
Chris Ye8594e192020-07-14 10:34:06 -07002259 ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002260 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002261 }
2262
2263 InputDeviceIdentifier identifier;
2264
2265 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002266 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Chris Ye8594e192020-07-14 10:34:06 -07002267 ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002268 } else {
2269 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002270 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002271 }
2272
2273 // Check to see if the device is on our excluded list
2274 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002275 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002276 if (identifier.name == item) {
Chris Ye8594e192020-07-14 10:34:06 -07002277 ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002278 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002279 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002280 }
2281 }
2282
2283 // Get device driver version.
2284 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002285 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Chris Ye8594e192020-07-14 10:34:06 -07002286 ALOGE("could not get driver version for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002287 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002288 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002289 }
2290
2291 // Get device identifier.
2292 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002293 if (ioctl(fd, EVIOCGID, &inputId)) {
Chris Ye8594e192020-07-14 10:34:06 -07002294 ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002295 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002296 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002297 }
2298 identifier.bus = inputId.bustype;
2299 identifier.product = inputId.product;
2300 identifier.vendor = inputId.vendor;
2301 identifier.version = inputId.version;
2302
2303 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002304 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
2305 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002306 } else {
2307 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002308 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002309 }
2310
2311 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002312 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
2313 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002314 } else {
2315 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002316 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002317 }
2318
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002319 // Attempt to get the bluetooth address of an input device from the uniqueId.
2320 if (identifier.bus == BUS_BLUETOOTH &&
2321 std::regex_match(identifier.uniqueId,
2322 std::regex("^[A-Fa-f0-9]{2}(?::[A-Fa-f0-9]{2}){5}$"))) {
2323 identifier.bluetoothAddress = identifier.uniqueId;
2324 // The Bluetooth stack requires alphabetic characters to be uppercase in a valid address.
2325 for (auto& c : *identifier.bluetoothAddress) {
2326 c = ::toupper(c);
2327 }
2328 }
2329
Michael Wrightd02c5b62014-02-10 15:10:22 -08002330 // Fill in the descriptor.
2331 assignDescriptorLocked(identifier);
2332
Michael Wrightd02c5b62014-02-10 15:10:22 -08002333 // Allocate device. (The device object takes ownership of the fd at this point.)
2334 int32_t deviceId = mNextDeviceId++;
Prabir Pradhancb42b472022-08-23 16:01:19 +00002335 std::unique_ptr<Device> device =
2336 std::make_unique<Device>(fd, deviceId, devicePath, identifier,
2337 obtainAssociatedDeviceLocked(devicePath));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002338
Chris Ye8594e192020-07-14 10:34:06 -07002339 ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002340 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002341 " vendor %04x\n"
2342 " product %04x\n"
2343 " version %04x\n",
2344 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002345 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
2346 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
2347 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
2348 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002349 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
2350 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002351
2352 // Load the configuration file for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002353 device->loadConfigurationLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002354
2355 // Figure out the kinds of events the device reports.
Chris Ye66fbac32020-07-06 20:36:43 -07002356 device->readDeviceBitMask(EVIOCGBIT(EV_KEY, 0), device->keyBitmask);
2357 device->readDeviceBitMask(EVIOCGBIT(EV_ABS, 0), device->absBitmask);
2358 device->readDeviceBitMask(EVIOCGBIT(EV_REL, 0), device->relBitmask);
2359 device->readDeviceBitMask(EVIOCGBIT(EV_SW, 0), device->swBitmask);
2360 device->readDeviceBitMask(EVIOCGBIT(EV_LED, 0), device->ledBitmask);
2361 device->readDeviceBitMask(EVIOCGBIT(EV_FF, 0), device->ffBitmask);
Chris Yef59a2f42020-10-16 12:55:26 -07002362 device->readDeviceBitMask(EVIOCGBIT(EV_MSC, 0), device->mscBitmask);
Chris Ye66fbac32020-07-06 20:36:43 -07002363 device->readDeviceBitMask(EVIOCGPROP(0), device->propBitmask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002364
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002365 // See if this is a device with keys. This could be full keyboard, or other devices like
2366 // gamepads, joysticks, and styluses with buttons that should generate key presses.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002367 bool haveKeyboardKeys =
Chris Ye66fbac32020-07-06 20:36:43 -07002368 device->keyBitmask.any(0, BTN_MISC) || device->keyBitmask.any(BTN_WHEEL, KEY_MAX + 1);
2369 bool haveGamepadButtons = device->keyBitmask.any(BTN_MISC, BTN_MOUSE) ||
2370 device->keyBitmask.any(BTN_JOYSTICK, BTN_DIGI);
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002371 bool haveStylusButtons = device->keyBitmask.test(BTN_STYLUS) ||
2372 device->keyBitmask.test(BTN_STYLUS2) || device->keyBitmask.test(BTN_STYLUS3);
2373 if (haveKeyboardKeys || haveGamepadButtons || haveStylusButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002374 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002375 }
2376
2377 // See if this is a cursor device such as a trackball or mouse.
Chris Ye66fbac32020-07-06 20:36:43 -07002378 if (device->keyBitmask.test(BTN_MOUSE) && device->relBitmask.test(REL_X) &&
2379 device->relBitmask.test(REL_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002380 device->classes |= InputDeviceClass::CURSOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002381 }
2382
Prabir Pradhana3621852022-10-14 18:57:23 +00002383 // See if the device is specially configured to be of a certain type.
Harry Cuttsf13161a2023-03-08 14:15:49 +00002384 if (device->configuration) {
2385 std::string deviceType = device->configuration->getString("device.type").value_or("");
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07002386 if (deviceType == "rotaryEncoder") {
Chris Ye1b0c7342020-07-28 21:57:03 -07002387 device->classes |= InputDeviceClass::ROTARY_ENCODER;
Prabir Pradhana3621852022-10-14 18:57:23 +00002388 } else if (deviceType == "externalStylus") {
2389 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002390 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002391 }
2392
Michael Wrightd02c5b62014-02-10 15:10:22 -08002393 // See if this is a touch pad.
2394 // Is this a new modern multi-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002395 if (device->absBitmask.test(ABS_MT_POSITION_X) && device->absBitmask.test(ABS_MT_POSITION_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002396 // Some joysticks such as the PS3 controller report axes that conflict
2397 // with the ABS_MT range. Try to confirm that the device really is
2398 // a touch screen.
Chris Ye66fbac32020-07-06 20:36:43 -07002399 if (device->keyBitmask.test(BTN_TOUCH) || !haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002400 device->classes |= (InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT);
Harry Cutts79cc9fa2022-10-28 15:32:39 +00002401 if (device->propBitmask.test(INPUT_PROP_POINTER) &&
2402 !device->keyBitmask.any(BTN_TOOL_PEN, BTN_TOOL_FINGER) && !haveStylusButtons) {
2403 device->classes |= InputDeviceClass::TOUCHPAD;
2404 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002405 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002406 // Is this an old style single-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002407 } else if (device->keyBitmask.test(BTN_TOUCH) && device->absBitmask.test(ABS_X) &&
2408 device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002409 device->classes |= InputDeviceClass::TOUCH;
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002410 // Is this a stylus that reports contact/pressure independently of touch coordinates?
Chris Ye66fbac32020-07-06 20:36:43 -07002411 } else if ((device->absBitmask.test(ABS_PRESSURE) || device->keyBitmask.test(BTN_TOUCH)) &&
2412 !device->absBitmask.test(ABS_X) && !device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002413 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002414 }
2415
2416 // See if this device is a joystick.
2417 // Assumes that joysticks always have gamepad buttons in order to distinguish them
2418 // from other devices such as accelerometers that also have absolute axes.
2419 if (haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002420 auto assumedClasses = device->classes | InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002421 for (int i = 0; i <= ABS_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002422 if (device->absBitmask.test(i) &&
Chris Ye1b0c7342020-07-28 21:57:03 -07002423 (getAbsAxisUsage(i, assumedClasses).test(InputDeviceClass::JOYSTICK))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002424 device->classes = assumedClasses;
2425 break;
2426 }
2427 }
2428 }
2429
Chris Yef59a2f42020-10-16 12:55:26 -07002430 // Check whether this device is an accelerometer.
2431 if (device->propBitmask.test(INPUT_PROP_ACCELEROMETER)) {
2432 device->classes |= InputDeviceClass::SENSOR;
2433 }
2434
Michael Wrightd02c5b62014-02-10 15:10:22 -08002435 // Check whether this device has switches.
2436 for (int i = 0; i <= SW_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002437 if (device->swBitmask.test(i)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002438 device->classes |= InputDeviceClass::SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002439 break;
2440 }
2441 }
2442
2443 // Check whether this device supports the vibrator.
Chris Ye66fbac32020-07-06 20:36:43 -07002444 if (device->ffBitmask.test(FF_RUMBLE)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002445 device->classes |= InputDeviceClass::VIBRATOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002446 }
2447
2448 // Configure virtual keys.
Chris Ye1b0c7342020-07-28 21:57:03 -07002449 if ((device->classes.test(InputDeviceClass::TOUCH))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002450 // Load the virtual keys for the touch screen, if any.
2451 // We do this now so that we can make sure to load the keymap if necessary.
Chris Ye989bb932020-07-04 16:18:59 -07002452 bool success = device->loadVirtualKeyMapLocked();
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06002453 if (success) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002454 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002455 }
2456 }
2457
2458 // Load the key map.
Chris Yef59a2f42020-10-16 12:55:26 -07002459 // We need to do this for joysticks too because the key layout may specify axes, and for
2460 // sensor as well because the key layout may specify the axes to sensor data mapping.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002461 status_t keyMapStatus = NAME_NOT_FOUND;
Chris Yef59a2f42020-10-16 12:55:26 -07002462 if (device->classes.any(InputDeviceClass::KEYBOARD | InputDeviceClass::JOYSTICK |
2463 InputDeviceClass::SENSOR)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002464 // Load the keymap for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002465 keyMapStatus = device->loadKeyMapLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002466 }
2467
2468 // Configure the keyboard, gamepad or virtual keyboard.
Chris Ye1b0c7342020-07-28 21:57:03 -07002469 if (device->classes.test(InputDeviceClass::KEYBOARD)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002470 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002471 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002472 isEligibleBuiltInKeyboard(device->identifier, device->configuration.get(),
2473 &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002474 mBuiltInKeyboardId = device->id;
2475 }
2476
2477 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
Chris Ye989bb932020-07-04 16:18:59 -07002478 if (device->hasKeycodeLocked(AKEYCODE_Q)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002479 device->classes |= InputDeviceClass::ALPHAKEY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002480 }
2481
Prabir Pradhanae10ee62023-05-12 19:44:18 +00002482 // See if this device has a D-pad.
2483 if (std::all_of(DPAD_REQUIRED_KEYCODES.begin(), DPAD_REQUIRED_KEYCODES.end(),
2484 [&](int32_t keycode) { return device->hasKeycodeLocked(keycode); })) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002485 device->classes |= InputDeviceClass::DPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002486 }
2487
2488 // See if this device has a gamepad.
Prabir Pradhanae10ee62023-05-12 19:44:18 +00002489 if (std::any_of(GAMEPAD_KEYCODES.begin(), GAMEPAD_KEYCODES.end(),
2490 [&](int32_t keycode) { return device->hasKeycodeLocked(keycode); })) {
2491 device->classes |= InputDeviceClass::GAMEPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002492 }
Prabir Pradhana3621852022-10-14 18:57:23 +00002493
2494 // See if this device has any stylus buttons that we would want to fuse with touch data.
Prabir Pradhanae10ee62023-05-12 19:44:18 +00002495 if (!device->classes.any(InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT) &&
Prabir Pradhan3c28b942023-08-18 20:02:01 +00002496 !device->classes.any(InputDeviceClass::ALPHAKEY) &&
Prabir Pradhanae10ee62023-05-12 19:44:18 +00002497 std::any_of(STYLUS_BUTTON_KEYCODES.begin(), STYLUS_BUTTON_KEYCODES.end(),
2498 [&](int32_t keycode) { return device->hasKeycodeLocked(keycode); })) {
2499 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Prabir Pradhana3621852022-10-14 18:57:23 +00002500 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002501 }
2502
2503 // If the device isn't recognized as something we handle, don't monitor it.
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002504 if (device->classes == ftl::Flags<InputDeviceClass>(0)) {
Chris Ye8594e192020-07-14 10:34:06 -07002505 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002506 device->identifier.name.c_str());
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002507 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002508 }
2509
Chris Ye3fdbfef2021-01-06 18:45:18 -08002510 // Classify InputDeviceClass::BATTERY.
Prabir Pradhan51894782022-08-23 16:29:10 +00002511 if (device->associatedDevice && !device->associatedDevice->batteryInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002512 device->classes |= InputDeviceClass::BATTERY;
2513 }
Kim Low03ea0352020-11-06 12:45:07 -08002514
Chris Ye3fdbfef2021-01-06 18:45:18 -08002515 // Classify InputDeviceClass::LIGHT.
Prabir Pradhan51894782022-08-23 16:29:10 +00002516 if (device->associatedDevice && !device->associatedDevice->lightInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002517 device->classes |= InputDeviceClass::LIGHT;
Kim Low03ea0352020-11-06 12:45:07 -08002518 }
2519
Tim Kilbourn063ff532015-04-08 10:26:18 -07002520 // Determine whether the device has a mic.
Chris Ye989bb932020-07-04 16:18:59 -07002521 if (device->deviceHasMicLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002522 device->classes |= InputDeviceClass::MIC;
Tim Kilbourn063ff532015-04-08 10:26:18 -07002523 }
2524
Michael Wrightd02c5b62014-02-10 15:10:22 -08002525 // Determine whether the device is external or internal.
Chris Ye989bb932020-07-04 16:18:59 -07002526 if (device->isExternalDeviceLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002527 device->classes |= InputDeviceClass::EXTERNAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002528 }
2529
Chris Ye1b0c7342020-07-28 21:57:03 -07002530 if (device->classes.any(InputDeviceClass::JOYSTICK | InputDeviceClass::DPAD) &&
2531 device->classes.test(InputDeviceClass::GAMEPAD)) {
Chris Ye989bb932020-07-04 16:18:59 -07002532 device->controllerNumber = getNextControllerNumberLocked(device->identifier.name);
2533 device->setLedForControllerLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002534 }
2535
Chris Ye989bb932020-07-04 16:18:59 -07002536 if (registerDeviceForEpollLocked(*device) != OK) {
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002537 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002538 }
2539
Chris Ye989bb932020-07-04 16:18:59 -07002540 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002541
Chris Ye1b0c7342020-07-28 21:57:03 -07002542 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=%s, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002543 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Chris Ye1b0c7342020-07-28 21:57:03 -07002544 deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(),
2545 device->classes.string().c_str(), device->configurationFile.c_str(),
2546 device->keyMap.keyLayoutFile.c_str(), device->keyMap.keyCharacterMapFile.c_str(),
2547 toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002548
Chris Ye989bb932020-07-04 16:18:59 -07002549 addDeviceLocked(std::move(device));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002550}
2551
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002552void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
2553 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
2554 if (!videoDevice) {
2555 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
2556 return;
2557 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002558 // Transfer ownership of this video device to a matching input device
Chris Ye989bb932020-07-04 16:18:59 -07002559 for (const auto& [id, device] : mDevices) {
Chris Yed3fef462021-03-07 17:10:08 -08002560 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002561 return; // 'device' now owns 'videoDevice'
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002562 }
2563 }
2564
2565 // Couldn't find a matching input device, so just add it to a temporary holding queue.
2566 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002567 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002568 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002569 mUnattachedVideoDevices.push_back(std::move(videoDevice));
2570}
2571
Chris Yed3fef462021-03-07 17:10:08 -08002572bool EventHub::tryAddVideoDeviceLocked(EventHub::Device& device,
2573 std::unique_ptr<TouchVideoDevice>& videoDevice) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002574 if (videoDevice->getName() != device.identifier.name) {
2575 return false;
2576 }
2577 device.videoDevice = std::move(videoDevice);
2578 if (device.enabled) {
2579 registerVideoDeviceForEpollLocked(*device.videoDevice);
2580 }
2581 return true;
2582}
2583
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002584bool EventHub::isDeviceEnabled(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00002585 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002586 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002587 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002588 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2589 return false;
2590 }
2591 return device->enabled;
2592}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002593
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002594status_t EventHub::enableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002595 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002596 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002597 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002598 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2599 return BAD_VALUE;
2600 }
2601 if (device->enabled) {
2602 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
2603 return OK;
2604 }
2605 status_t result = device->enable();
2606 if (result != OK) {
2607 ALOGE("Failed to enable device %" PRId32, deviceId);
2608 return result;
2609 }
2610
Chris Ye989bb932020-07-04 16:18:59 -07002611 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002612
Chris Ye989bb932020-07-04 16:18:59 -07002613 return registerDeviceForEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002614}
2615
2616status_t EventHub::disableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002617 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002618 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002619 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002620 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2621 return BAD_VALUE;
2622 }
2623 if (!device->enabled) {
2624 ALOGW("Duplicate call to %s, input device already disabled", __func__);
2625 return OK;
2626 }
Chris Ye989bb932020-07-04 16:18:59 -07002627 unregisterDeviceFromEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002628 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002629}
2630
Vaibhav Devmurari5fc7d852023-03-17 18:43:33 +00002631// TODO(b/274755573): Shift to uevent handling on native side and remove this method
2632// Currently using Java UEventObserver to trigger this which uses UEvent infrastructure that uses a
2633// NETLINK socket to observe UEvents. We can create similar infrastructure on Eventhub side to
2634// directly observe UEvents instead of triggering from Java side.
2635void EventHub::sysfsNodeChanged(const std::string& sysfsNodePath) {
2636 std::scoped_lock _l(mLock);
2637
2638 // Check in opening devices
2639 for (auto it = mOpeningDevices.begin(); it != mOpeningDevices.end(); it++) {
2640 std::unique_ptr<Device>& device = *it;
2641 if (device->associatedDevice &&
2642 sysfsNodePath.find(device->associatedDevice->sysfsRootPath.string()) !=
2643 std::string::npos &&
2644 device->associatedDevice->isChanged()) {
2645 it = mOpeningDevices.erase(it);
2646 openDeviceLocked(device->path);
2647 }
2648 }
2649
2650 // Check in already added device
2651 std::vector<Device*> devicesToReopen;
2652 for (const auto& [id, device] : mDevices) {
2653 if (device->associatedDevice &&
2654 sysfsNodePath.find(device->associatedDevice->sysfsRootPath.string()) !=
2655 std::string::npos &&
2656 device->associatedDevice->isChanged()) {
2657 devicesToReopen.push_back(device.get());
2658 }
2659 }
2660 for (const auto& device : devicesToReopen) {
2661 closeDeviceLocked(*device);
2662 openDeviceLocked(device->path);
2663 }
2664 devicesToReopen.clear();
2665}
2666
Michael Wrightd02c5b62014-02-10 15:10:22 -08002667void EventHub::createVirtualKeyboardLocked() {
2668 InputDeviceIdentifier identifier;
2669 identifier.name = "Virtual";
2670 identifier.uniqueId = "<virtual>";
2671 assignDescriptorLocked(identifier);
2672
Chris Ye989bb932020-07-04 16:18:59 -07002673 std::unique_ptr<Device> device =
2674 std::make_unique<Device>(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
Harry Cutts33476232023-01-30 19:57:29 +00002675 identifier, /*associatedDevice=*/nullptr);
Chris Ye1b0c7342020-07-28 21:57:03 -07002676 device->classes = InputDeviceClass::KEYBOARD | InputDeviceClass::ALPHAKEY |
2677 InputDeviceClass::DPAD | InputDeviceClass::VIRTUAL;
Chris Ye989bb932020-07-04 16:18:59 -07002678 device->loadKeyMapLocked();
2679 addDeviceLocked(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002680}
2681
Chris Ye989bb932020-07-04 16:18:59 -07002682void EventHub::addDeviceLocked(std::unique_ptr<Device> device) {
Chris Yed3fef462021-03-07 17:10:08 -08002683 reportDeviceAddedForStatisticsLocked(device->identifier, device->classes);
Chris Ye989bb932020-07-04 16:18:59 -07002684 mOpeningDevices.push_back(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002685}
2686
Chris Ye989bb932020-07-04 16:18:59 -07002687int32_t EventHub::getNextControllerNumberLocked(const std::string& name) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002688 if (mControllerNumbers.isFull()) {
2689 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Chris Ye989bb932020-07-04 16:18:59 -07002690 name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002691 return 0;
2692 }
2693 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
2694 // one
2695 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
2696}
2697
Chris Ye989bb932020-07-04 16:18:59 -07002698void EventHub::releaseControllerNumberLocked(int32_t num) {
2699 if (num > 0) {
2700 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002701 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002702}
2703
Chris Ye8594e192020-07-14 10:34:06 -07002704void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002705 Device* device = getDeviceByPathLocked(devicePath);
Chris Ye989bb932020-07-04 16:18:59 -07002706 if (device != nullptr) {
2707 closeDeviceLocked(*device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002708 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002709 }
Chris Ye8594e192020-07-14 10:34:06 -07002710 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002711}
2712
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002713/**
2714 * Find the video device by filename, and close it.
2715 * The video device is closed by path during an inotify event, where we don't have the
2716 * additional context about the video device fd, or the associated input device.
2717 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002718void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002719 // A video device may be owned by an existing input device, or it may be stored in
2720 // the mUnattachedVideoDevices queue. Check both locations.
Chris Ye989bb932020-07-04 16:18:59 -07002721 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002722 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002723 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002724 device->videoDevice = nullptr;
2725 return;
2726 }
2727 }
Siarhei Vishniakouf47c339e2021-12-30 11:22:26 -08002728 std::erase_if(mUnattachedVideoDevices,
2729 [&devicePath](const std::unique_ptr<TouchVideoDevice>& videoDevice) {
2730 return videoDevice->getPath() == devicePath;
2731 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08002732}
2733
2734void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002735 mUnattachedVideoDevices.clear();
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002736 while (!mDevices.empty()) {
2737 closeDeviceLocked(*(mDevices.begin()->second));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002738 }
2739}
2740
Chris Ye989bb932020-07-04 16:18:59 -07002741void EventHub::closeDeviceLocked(Device& device) {
2742 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=%s", device.path.c_str(),
2743 device.identifier.name.c_str(), device.id, device.fd, device.classes.string().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002744
Chris Ye989bb932020-07-04 16:18:59 -07002745 if (device.id == mBuiltInKeyboardId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002746 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Chris Ye989bb932020-07-04 16:18:59 -07002747 device.path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002748 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
2749 }
2750
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002751 unregisterDeviceFromEpollLocked(device);
Chris Ye989bb932020-07-04 16:18:59 -07002752 if (device.videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002753 // This must be done after the video device is removed from epoll
Chris Ye989bb932020-07-04 16:18:59 -07002754 mUnattachedVideoDevices.push_back(std::move(device.videoDevice));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002755 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002756
Chris Ye989bb932020-07-04 16:18:59 -07002757 releaseControllerNumberLocked(device.controllerNumber);
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002758 device.controllerNumber = 0;
Chris Ye989bb932020-07-04 16:18:59 -07002759 device.close();
Chris Ye989bb932020-07-04 16:18:59 -07002760 mClosingDevices.push_back(std::move(mDevices[device.id]));
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002761
Chris Ye989bb932020-07-04 16:18:59 -07002762 mDevices.erase(device.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002763}
2764
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002765base::Result<void> EventHub::readNotifyLocked() {
2766 static constexpr auto EVENT_SIZE = static_cast<ssize_t>(sizeof(inotify_event));
2767 uint8_t eventBuffer[512];
2768 ssize_t sizeRead;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002769
2770 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002771 do {
2772 sizeRead = read(mINotifyFd, eventBuffer, sizeof(eventBuffer));
2773 } while (sizeRead < 0 && errno == EINTR);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002774
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002775 if (sizeRead < EVENT_SIZE) return Errorf("could not get event, %s", strerror(errno));
2776
2777 for (ssize_t eventPos = 0; sizeRead >= EVENT_SIZE;) {
2778 const inotify_event* event;
2779 event = (const inotify_event*)(eventBuffer + eventPos);
2780 if (event->len == 0) continue;
2781
2782 handleNotifyEventLocked(*event);
2783
2784 const ssize_t eventSize = EVENT_SIZE + event->len;
2785 sizeRead -= eventSize;
2786 eventPos += eventSize;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002787 }
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002788 return {};
2789}
2790
2791void EventHub::handleNotifyEventLocked(const inotify_event& event) {
2792 if (event.wd == mDeviceInputWd) {
2793 std::string filename = std::string(DEVICE_INPUT_PATH) + "/" + event.name;
2794 if (event.mask & IN_CREATE) {
2795 openDeviceLocked(filename);
2796 } else {
2797 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
2798 closeDeviceByPathLocked(filename);
2799 }
2800 } else if (event.wd == mDeviceWd) {
2801 if (isV4lTouchNode(event.name)) {
2802 std::string filename = std::string(DEVICE_PATH) + "/" + event.name;
2803 if (event.mask & IN_CREATE) {
2804 openVideoDeviceLocked(filename);
2805 } else {
2806 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
2807 closeVideoDeviceByPathLocked(filename);
2808 }
2809 } else if (strcmp(event.name, "input") == 0 && event.mask & IN_CREATE) {
2810 addDeviceInputInotify();
2811 }
2812 } else {
2813 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event.wd);
2814 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002815}
2816
Chris Ye8594e192020-07-14 10:34:06 -07002817status_t EventHub::scanDirLocked(const std::string& dirname) {
2818 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2819 openDeviceLocked(entry.path());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002820 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002821 return 0;
2822}
2823
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002824/**
2825 * Look for all dirname/v4l-touch* devices, and open them.
2826 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002827status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Chris Ye8594e192020-07-14 10:34:06 -07002828 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2829 if (isV4lTouchNode(entry.path())) {
2830 ALOGI("Found touch video device %s", entry.path().c_str());
2831 openVideoDeviceLocked(entry.path());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002832 }
2833 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002834 return OK;
2835}
2836
Michael Wrightd02c5b62014-02-10 15:10:22 -08002837void EventHub::requestReopenDevices() {
2838 ALOGV("requestReopenDevices() called");
2839
Chris Ye87143712020-11-10 05:05:58 +00002840 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002841 mNeedToReopenDevices = true;
2842}
2843
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002844void EventHub::dump(std::string& dump) const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002845 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002846
2847 { // acquire lock
Chris Ye87143712020-11-10 05:05:58 +00002848 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002849
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002850 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002851
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002852 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002853
Chris Ye989bb932020-07-04 16:18:59 -07002854 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002855 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002856 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002857 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002858 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002859 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002860 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002861 }
Chris Ye1b0c7342020-07-28 21:57:03 -07002862 dump += StringPrintf(INDENT3 "Classes: %s\n", device->classes.string().c_str());
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002863 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002864 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002865 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
2866 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002867 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002868 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002869 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002870 "product=0x%04x, version=0x%04x, bluetoothAddress=%s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002871 device->identifier.bus, device->identifier.vendor,
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002872 device->identifier.product, device->identifier.version,
2873 toString(device->identifier.bluetoothAddress).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002874 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002875 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002876 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002877 device->keyMap.keyCharacterMapFile.c_str());
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00002878 if (device->associatedDevice && device->associatedDevice->layoutInfo) {
2879 dump += StringPrintf(INDENT3 "LanguageTag: %s\n",
2880 device->associatedDevice->layoutInfo->languageTag.c_str());
2881 dump += StringPrintf(INDENT3 "LayoutType: %s\n",
2882 device->associatedDevice->layoutInfo->layoutType.c_str());
2883 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002884 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002885 device->configurationFile.c_str());
Prabir Pradhan51894782022-08-23 16:29:10 +00002886 dump += StringPrintf(INDENT3 "VideoDevice: %s\n",
2887 device->videoDevice ? device->videoDevice->dump().c_str()
2888 : "<none>");
2889 dump += StringPrintf(INDENT3 "SysfsDevicePath: %s\n",
2890 device->associatedDevice
2891 ? device->associatedDevice->sysfsRootPath.c_str()
2892 : "<none>");
Prabir Pradhan955b6132023-07-14 19:44:34 +00002893 if (device->keyBitmask.any(0, KEY_MAX + 1)) {
2894 const auto pressedKeys = device->keyState.dumpSetIndices(", ", [](int i) {
2895 return InputEventLookup::getLinuxEvdevLabel(EV_KEY, i, 1).code;
2896 });
2897 dump += StringPrintf(INDENT3 "KeyState (pressed): %s\n", pressedKeys.c_str());
2898 }
2899 if (device->swBitmask.any(0, SW_MAX + 1)) {
2900 const auto pressedSwitches = device->swState.dumpSetIndices(", ", [](int i) {
2901 return InputEventLookup::getLinuxEvdevLabel(EV_SW, i, 1).code;
2902 });
2903 dump += StringPrintf(INDENT3 "SwState (pressed): %s\n", pressedSwitches.c_str());
2904 }
2905 if (!device->absState.empty()) {
2906 std::string axisValues;
2907 for (const auto& [axis, state] : device->absState) {
2908 if (!axisValues.empty()) {
2909 axisValues += ", ";
2910 }
2911 axisValues += StringPrintf("%s=%d",
2912 InputEventLookup::getLinuxEvdevLabel(EV_ABS, axis, 0)
2913 .code.c_str(),
2914 state.value);
2915 }
2916 dump += INDENT3 "AbsState: " + axisValues + "\n";
2917 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002918 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002919
2920 dump += INDENT "Unattached video devices:\n";
2921 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
2922 dump += INDENT2 + videoDevice->dump() + "\n";
2923 }
2924 if (mUnattachedVideoDevices.empty()) {
2925 dump += INDENT2 "<none>\n";
2926 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002927 } // release lock
2928}
2929
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002930void EventHub::monitor() const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002931 // Acquire and release the lock to ensure that the event hub has not deadlocked.
Chris Ye1c2e0892020-11-30 21:41:44 -08002932 std::unique_lock<std::mutex> lock(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002933}
2934
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00002935std::string EventHub::AssociatedDevice::dump() const {
2936 return StringPrintf("path=%s, numBatteries=%zu, numLight=%zu", sysfsRootPath.c_str(),
2937 batteryInfos.size(), lightInfos.size());
2938}
2939
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002940} // namespace android