blob: f6543125c86440f636bd1e8af4d40e5c5739eb20 [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
Vladimir Komsiyskidd438e22024-02-13 11:47:54 +010036#include <android_companion_virtualdevice_flags.h>
37
Michael Wrightd02c5b62014-02-10 15:10:22 -080038#define LOG_TAG "EventHub"
39
40// #define LOG_NDEBUG 0
Kim Low03ea0352020-11-06 12:45:07 -080041#include <android-base/file.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080042#include <android-base/stringprintf.h>
Chris Yed3fef462021-03-07 17:10:08 -080043#include <android-base/strings.h>
Philip Quinn39b81682019-01-09 22:20:39 -080044#include <cutils/properties.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080045#include <ftl/enum.h>
Harry Cuttsd6a3fb52024-10-23 09:48:55 +000046#include <input/InputEventLabels.h>
Chris Ye8594e192020-07-14 10:34:06 -070047#include <input/KeyCharacterMap.h>
48#include <input/KeyLayoutMap.h>
Prabir Pradhan07525ef2022-10-03 21:51:26 +000049#include <input/PrintTools.h>
Chris Ye8594e192020-07-14 10:34:06 -070050#include <input/VirtualKeyMap.h>
Dan Albert677d87e2014-06-16 17:31:28 -070051#include <openssl/sha.h>
Chris Yed3fef462021-03-07 17:10:08 -080052#include <statslog.h>
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070053#include <utils/Errors.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080054#include <utils/Log.h>
55#include <utils/Timers.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080056
Chris Ye8594e192020-07-14 10:34:06 -070057#include <filesystem>
Harry Cuttsf13161a2023-03-08 14:15:49 +000058#include <optional>
Chris Ye3fdbfef2021-01-06 18:45:18 -080059#include <regex>
Prabir Pradhancb42b472022-08-23 16:01:19 +000060#include <utility>
Chris Ye8594e192020-07-14 10:34:06 -070061
62#include "EventHub.h"
Michael Wrightd02c5b62014-02-10 15:10:22 -080063
Prabir Pradhanae10ee62023-05-12 19:44:18 +000064#include "KeyCodeClassifications.h"
65
Michael Wrightd02c5b62014-02-10 15:10:22 -080066#define INDENT " "
67#define INDENT2 " "
68#define INDENT3 " "
69
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080070using android::base::StringPrintf;
71
Michael Wrightd02c5b62014-02-10 15:10:22 -080072namespace android {
73
Vladimir Komsiyskidd438e22024-02-13 11:47:54 +010074namespace vd_flags = android::companion::virtualdevice::flags;
75
Dominik Laskowski2f01d772022-03-23 16:01:29 -070076using namespace ftl::flag_operators;
77
Usama Arifb27c8e62021-06-03 16:44:09 +010078static const char* DEVICE_INPUT_PATH = "/dev/input";
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080079// v4l2 devices go directly into /dev
Usama Arifb27c8e62021-06-03 16:44:09 +010080static const char* DEVICE_PATH = "/dev";
Michael Wrightd02c5b62014-02-10 15:10:22 -080081
Chris Ye657c2f02021-05-25 16:24:37 -070082static constexpr size_t OBFUSCATED_LENGTH = 8;
83
Chris Ye87143712020-11-10 05:05:58 +000084static constexpr int32_t FF_STRONG_MAGNITUDE_CHANNEL_IDX = 0;
85static constexpr int32_t FF_WEAK_MAGNITUDE_CHANNEL_IDX = 1;
Chris Ye6393a262020-08-04 19:41:36 -070086
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -070087static constexpr size_t EVENT_BUFFER_SIZE = 256;
88
Chris Yee2b1e5c2021-03-10 22:45:12 -080089// Mapping for input battery class node IDs lookup.
90// https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
91static const std::unordered_map<std::string, InputBatteryClass> BATTERY_CLASSES =
92 {{"capacity", InputBatteryClass::CAPACITY},
93 {"capacity_level", InputBatteryClass::CAPACITY_LEVEL},
94 {"status", InputBatteryClass::STATUS}};
95
96// Mapping for input battery class node names lookup.
97// https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
98static const std::unordered_map<InputBatteryClass, std::string> BATTERY_NODES =
99 {{InputBatteryClass::CAPACITY, "capacity"},
100 {InputBatteryClass::CAPACITY_LEVEL, "capacity_level"},
101 {InputBatteryClass::STATUS, "status"}};
102
Kim Low03ea0352020-11-06 12:45:07 -0800103// must be kept in sync with definitions in kernel /drivers/power/supply/power_supply_sysfs.c
104static const std::unordered_map<std::string, int32_t> BATTERY_STATUS =
105 {{"Unknown", BATTERY_STATUS_UNKNOWN},
106 {"Charging", BATTERY_STATUS_CHARGING},
107 {"Discharging", BATTERY_STATUS_DISCHARGING},
108 {"Not charging", BATTERY_STATUS_NOT_CHARGING},
109 {"Full", BATTERY_STATUS_FULL}};
110
111// Mapping taken from
112// https://gitlab.freedesktop.org/upower/upower/-/blob/master/src/linux/up-device-supply.c#L484
113static const std::unordered_map<std::string, int32_t> BATTERY_LEVEL = {{"Critical", 5},
114 {"Low", 10},
115 {"Normal", 55},
116 {"High", 70},
117 {"Full", 100},
118 {"Unknown", 50}};
119
Chris Ye3fdbfef2021-01-06 18:45:18 -0800120// Mapping for input led class node names lookup.
121// https://www.kernel.org/doc/html/latest/leds/leds-class.html
122static const std::unordered_map<std::string, InputLightClass> LIGHT_CLASSES =
123 {{"red", InputLightClass::RED},
124 {"green", InputLightClass::GREEN},
125 {"blue", InputLightClass::BLUE},
126 {"global", InputLightClass::GLOBAL},
127 {"brightness", InputLightClass::BRIGHTNESS},
128 {"multi_index", InputLightClass::MULTI_INDEX},
129 {"multi_intensity", InputLightClass::MULTI_INTENSITY},
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000130 {"max_brightness", InputLightClass::MAX_BRIGHTNESS},
DingYong99f2c3c2023-12-20 15:46:06 +0800131 {"kbd_backlight", InputLightClass::KEYBOARD_BACKLIGHT},
132 {"mic_mute", InputLightClass::KEYBOARD_MIC_MUTE}};
Chris Ye3fdbfef2021-01-06 18:45:18 -0800133
134// Mapping for input multicolor led class node names.
135// https://www.kernel.org/doc/html/latest/leds/leds-class-multicolor.html
136static const std::unordered_map<InputLightClass, std::string> LIGHT_NODES =
137 {{InputLightClass::BRIGHTNESS, "brightness"},
138 {InputLightClass::MULTI_INDEX, "multi_index"},
139 {InputLightClass::MULTI_INTENSITY, "multi_intensity"}};
140
141// Mapping for light color name and the light color
142const std::unordered_map<std::string, LightColor> LIGHT_COLORS = {{"red", LightColor::RED},
143 {"green", LightColor::GREEN},
144 {"blue", LightColor::BLUE}};
145
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000146// Mapping for country code to Layout info.
147// See bCountryCode in 6.2.1 of https://usb.org/sites/default/files/hid1_11.pdf.
148const std::unordered_map<std::int32_t, RawLayoutInfo> LAYOUT_INFOS =
149 {{0, RawLayoutInfo{.languageTag = "", .layoutType = ""}}, // NOT_SUPPORTED
150 {1, RawLayoutInfo{.languageTag = "ar-Arab", .layoutType = ""}}, // ARABIC
151 {2, RawLayoutInfo{.languageTag = "fr-BE", .layoutType = ""}}, // BELGIAN
152 {3, RawLayoutInfo{.languageTag = "fr-CA", .layoutType = ""}}, // CANADIAN_BILINGUAL
153 {4, RawLayoutInfo{.languageTag = "fr-CA", .layoutType = ""}}, // CANADIAN_FRENCH
154 {5, RawLayoutInfo{.languageTag = "cs", .layoutType = ""}}, // CZECH_REPUBLIC
155 {6, RawLayoutInfo{.languageTag = "da", .layoutType = ""}}, // DANISH
156 {7, RawLayoutInfo{.languageTag = "fi", .layoutType = ""}}, // FINNISH
157 {8, RawLayoutInfo{.languageTag = "fr-FR", .layoutType = ""}}, // FRENCH
158 {9, RawLayoutInfo{.languageTag = "de", .layoutType = ""}}, // GERMAN
159 {10, RawLayoutInfo{.languageTag = "el", .layoutType = ""}}, // GREEK
160 {11, RawLayoutInfo{.languageTag = "iw", .layoutType = ""}}, // HEBREW
161 {12, RawLayoutInfo{.languageTag = "hu", .layoutType = ""}}, // HUNGARY
162 {13, RawLayoutInfo{.languageTag = "en", .layoutType = "extended"}}, // INTERNATIONAL (ISO)
163 {14, RawLayoutInfo{.languageTag = "it", .layoutType = ""}}, // ITALIAN
164 {15, RawLayoutInfo{.languageTag = "ja", .layoutType = ""}}, // JAPAN
165 {16, RawLayoutInfo{.languageTag = "ko", .layoutType = ""}}, // KOREAN
166 {17, RawLayoutInfo{.languageTag = "es-419", .layoutType = ""}}, // LATIN_AMERICA
167 {18, RawLayoutInfo{.languageTag = "nl", .layoutType = ""}}, // DUTCH
168 {19, RawLayoutInfo{.languageTag = "nb", .layoutType = ""}}, // NORWEGIAN
169 {20, RawLayoutInfo{.languageTag = "fa", .layoutType = ""}}, // PERSIAN
170 {21, RawLayoutInfo{.languageTag = "pl", .layoutType = ""}}, // POLAND
171 {22, RawLayoutInfo{.languageTag = "pt", .layoutType = ""}}, // PORTUGUESE
172 {23, RawLayoutInfo{.languageTag = "ru", .layoutType = ""}}, // RUSSIA
173 {24, RawLayoutInfo{.languageTag = "sk", .layoutType = ""}}, // SLOVAKIA
174 {25, RawLayoutInfo{.languageTag = "es-ES", .layoutType = ""}}, // SPANISH
175 {26, RawLayoutInfo{.languageTag = "sv", .layoutType = ""}}, // SWEDISH
176 {27, RawLayoutInfo{.languageTag = "fr-CH", .layoutType = ""}}, // SWISS_FRENCH
177 {28, RawLayoutInfo{.languageTag = "de-CH", .layoutType = ""}}, // SWISS_GERMAN
178 {29, RawLayoutInfo{.languageTag = "de-CH", .layoutType = ""}}, // SWITZERLAND
179 {30, RawLayoutInfo{.languageTag = "zh-TW", .layoutType = ""}}, // TAIWAN
180 {31, RawLayoutInfo{.languageTag = "tr", .layoutType = "turkish_q"}}, // TURKISH_Q
181 {32, RawLayoutInfo{.languageTag = "en-GB", .layoutType = ""}}, // UK
182 {33, RawLayoutInfo{.languageTag = "en-US", .layoutType = ""}}, // US
183 {34, RawLayoutInfo{.languageTag = "", .layoutType = ""}}, // YUGOSLAVIA
184 {35, RawLayoutInfo{.languageTag = "tr", .layoutType = "turkish_f"}}}; // TURKISH_F
185
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100186static std::string sha1(const std::string& in) {
Dan Albert677d87e2014-06-16 17:31:28 -0700187 SHA_CTX ctx;
188 SHA1_Init(&ctx);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100189 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
Dan Albert677d87e2014-06-16 17:31:28 -0700190 u_char digest[SHA_DIGEST_LENGTH];
191 SHA1_Final(digest, &ctx);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800192
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100193 std::string out;
Dan Albert677d87e2014-06-16 17:31:28 -0700194 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100195 out += StringPrintf("%02x", digest[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800196 }
197 return out;
198}
199
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800200/**
201 * Return true if name matches "v4l-touch*"
202 */
Chris Ye8594e192020-07-14 10:34:06 -0700203static bool isV4lTouchNode(std::string name) {
204 return name.find("v4l-touch") != std::string::npos;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800205}
206
Philip Quinn39b81682019-01-09 22:20:39 -0800207/**
208 * Returns true if V4L devices should be scanned.
209 *
210 * The system property ro.input.video_enabled can be used to control whether
211 * EventHub scans and opens V4L devices. As V4L does not support multiple
212 * clients, EventHub effectively blocks access to these devices when it opens
Siarhei Vishniakou29f88492019-04-05 14:11:43 -0700213 * them.
214 *
215 * Setting this to "false" would prevent any video devices from being discovered and
216 * associated with input devices.
217 *
218 * This property can be used as follows:
219 * 1. To turn off features that are dependent on video device presence.
220 * 2. During testing and development, to allow other clients to read video devices
221 * directly from /dev.
Philip Quinn39b81682019-01-09 22:20:39 -0800222 */
223static bool isV4lScanningEnabled() {
Harry Cutts33476232023-01-30 19:57:29 +0000224 return property_get_bool("ro.input.video_enabled", /*default_value=*/true);
Philip Quinn39b81682019-01-09 22:20:39 -0800225}
226
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800227static nsecs_t processEventTimestamp(const struct input_event& event) {
228 // Use the time specified in the event instead of the current time
229 // so that downstream code can get more accurate estimates of
230 // event dispatch latency from the time the event is enqueued onto
231 // the evdev client buffer.
232 //
233 // The event's timestamp fortuitously uses the same monotonic clock
234 // time base as the rest of Android. The kernel event device driver
235 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
236 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
237 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
238 // system call that also queries ktime_get_ts().
239
Colin Cross5b799302022-10-18 21:52:41 -0700240 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.input_event_sec) +
241 microseconds_to_nanoseconds(event.input_event_usec);
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800242 return inputEventTime;
243}
244
Kim Low03ea0352020-11-06 12:45:07 -0800245/**
Prabir Pradhancb42b472022-08-23 16:01:19 +0000246 * Returns the sysfs root path of the input device.
Kim Low03ea0352020-11-06 12:45:07 -0800247 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800248static std::optional<std::filesystem::path> getSysfsRootPath(const char* devicePath) {
Kim Low03ea0352020-11-06 12:45:07 -0800249 std::error_code errorCode;
250
251 // Stat the device path to get the major and minor number of the character file
252 struct stat statbuf;
253 if (stat(devicePath, &statbuf) == -1) {
254 ALOGE("Could not stat device %s due to error: %s.", devicePath, std::strerror(errno));
Chris Ye3fdbfef2021-01-06 18:45:18 -0800255 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800256 }
257
258 unsigned int major_num = major(statbuf.st_rdev);
259 unsigned int minor_num = minor(statbuf.st_rdev);
260
261 // Realpath "/sys/dev/char/{major}:{minor}" to get the sysfs path to the input event
262 auto sysfsPath = std::filesystem::path("/sys/dev/char/");
263 sysfsPath /= std::to_string(major_num) + ":" + std::to_string(minor_num);
264 sysfsPath = std::filesystem::canonical(sysfsPath, errorCode);
265
266 // Make sure nothing went wrong in call to canonical()
267 if (errorCode) {
268 ALOGW("Could not run filesystem::canonical() due to error %d : %s.", errorCode.value(),
269 errorCode.message().c_str());
Chris Ye3fdbfef2021-01-06 18:45:18 -0800270 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800271 }
272
273 // Continue to go up a directory until we reach a directory named "input"
274 while (sysfsPath != "/" && sysfsPath.filename() != "input") {
275 sysfsPath = sysfsPath.parent_path();
276 }
277
278 // Then go up one more and you will be at the sysfs root of the device
279 sysfsPath = sysfsPath.parent_path();
280
281 // Make sure we didn't reach root path and that directory actually exists
282 if (sysfsPath == "/" || !std::filesystem::exists(sysfsPath, errorCode)) {
283 if (errorCode) {
284 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
285 errorCode.message().c_str());
286 }
287
288 // Not found
Chris Ye3fdbfef2021-01-06 18:45:18 -0800289 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800290 }
291
292 return sysfsPath;
293}
294
295/**
Chris Ye3fdbfef2021-01-06 18:45:18 -0800296 * Returns the list of files under a specified path.
Kim Low03ea0352020-11-06 12:45:07 -0800297 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800298static std::vector<std::filesystem::path> allFilesInPath(const std::filesystem::path& path) {
299 std::vector<std::filesystem::path> nodes;
300 std::error_code errorCode;
301 auto iter = std::filesystem::directory_iterator(path, errorCode);
302 while (!errorCode && iter != std::filesystem::directory_iterator()) {
303 nodes.push_back(iter->path());
304 iter++;
305 }
306 return nodes;
307}
308
309/**
310 * Returns the list of files under a specified directory in a sysfs path.
311 * Example:
312 * findSysfsNodes(sysfsRootPath, SysfsClass::LEDS) will return all led nodes under "leds" directory
313 * in the sysfs path.
314 */
315static std::vector<std::filesystem::path> findSysfsNodes(const std::filesystem::path& sysfsRoot,
316 SysfsClass clazz) {
Dominik Laskowski75788452021-02-09 18:51:25 -0800317 std::string nodeStr = ftl::enum_string(clazz);
Chris Ye3fdbfef2021-01-06 18:45:18 -0800318 std::for_each(nodeStr.begin(), nodeStr.end(),
319 [](char& c) { c = std::tolower(static_cast<unsigned char>(c)); });
320 std::vector<std::filesystem::path> nodes;
321 for (auto path = sysfsRoot; path != "/" && nodes.empty(); path = path.parent_path()) {
322 nodes = allFilesInPath(path / nodeStr);
323 }
324 return nodes;
325}
326
327static std::optional<std::array<LightColor, COLOR_NUM>> getColorIndexArray(
328 std::filesystem::path path) {
329 std::string indexStr;
330 if (!base::ReadFileToString(path, &indexStr)) {
331 return std::nullopt;
332 }
333
334 // Parse the multi color LED index file, refer to kernel docs
335 // leds/leds-class-multicolor.html
336 std::regex indexPattern("(red|green|blue)\\s(red|green|blue)\\s(red|green|blue)[\\n]");
337 std::smatch results;
338 std::array<LightColor, COLOR_NUM> colors;
339 if (!std::regex_match(indexStr, results, indexPattern)) {
340 return std::nullopt;
341 }
342
343 for (size_t i = 1; i < results.size(); i++) {
344 const auto it = LIGHT_COLORS.find(results[i].str());
345 if (it != LIGHT_COLORS.end()) {
346 // intensities.emplace(it->second, 0);
347 colors[i - 1] = it->second;
Kim Low03ea0352020-11-06 12:45:07 -0800348 }
349 }
Chris Ye3fdbfef2021-01-06 18:45:18 -0800350 return colors;
Kim Low03ea0352020-11-06 12:45:07 -0800351}
352
Prabir Pradhancb42b472022-08-23 16:01:19 +0000353/**
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000354 * Read country code information exposed through the sysfs path and convert it to Layout info.
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000355 */
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000356static std::optional<RawLayoutInfo> readLayoutConfiguration(
357 const std::filesystem::path& sysfsRootPath) {
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000358 // Check the sysfs root path
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000359 int32_t hidCountryCode = -1;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000360 std::string str;
361 if (base::ReadFileToString(sysfsRootPath / "country", &str)) {
362 hidCountryCode = std::stoi(str, nullptr, 16);
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000363 // Update this condition if new supported country codes are added to HID spec.
Vaibhav Devmurari990ff7b2022-12-22 18:23:21 +0000364 if (hidCountryCode > 35 || hidCountryCode < 0) {
365 ALOGE("HID country code should be in range [0, 35], but for sysfs path %s it was %d",
366 sysfsRootPath.c_str(), hidCountryCode);
Vaibhav Devmurari990ff7b2022-12-22 18:23:21 +0000367 }
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000368 }
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000369 const auto it = LAYOUT_INFOS.find(hidCountryCode);
370 if (it != LAYOUT_INFOS.end()) {
371 return it->second;
372 }
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000373
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000374 return std::nullopt;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000375}
376
377/**
Prabir Pradhancb42b472022-08-23 16:01:19 +0000378 * Read information about batteries exposed through the sysfs path.
379 */
380static std::unordered_map<int32_t /*batteryId*/, RawBatteryInfo> readBatteryConfiguration(
381 const std::filesystem::path& sysfsRootPath) {
382 std::unordered_map<int32_t, RawBatteryInfo> batteryInfos;
383 int32_t nextBatteryId = 0;
384 // Check if device has any battery.
385 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::POWER_SUPPLY);
386 for (const auto& nodePath : paths) {
387 RawBatteryInfo info;
388 info.id = ++nextBatteryId;
389 info.path = nodePath;
390 info.name = nodePath.filename();
391
392 // Scan the path for all the files
393 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
394 const auto& files = allFilesInPath(nodePath);
395 for (const auto& file : files) {
396 const auto it = BATTERY_CLASSES.find(file.filename().string());
397 if (it != BATTERY_CLASSES.end()) {
398 info.flags |= it->second;
399 }
400 }
401 batteryInfos.insert_or_assign(info.id, info);
402 ALOGD("configureBatteryLocked rawBatteryId %d name %s", info.id, info.name.c_str());
403 }
404 return batteryInfos;
405}
406
407/**
408 * Read information about lights exposed through the sysfs path.
409 */
410static std::unordered_map<int32_t /*lightId*/, RawLightInfo> readLightsConfiguration(
411 const std::filesystem::path& sysfsRootPath) {
412 std::unordered_map<int32_t, RawLightInfo> lightInfos;
413 int32_t nextLightId = 0;
414 // Check if device has any lights.
415 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::LEDS);
416 for (const auto& nodePath : paths) {
417 RawLightInfo info;
418 info.id = ++nextLightId;
419 info.path = nodePath;
420 info.name = nodePath.filename();
421 info.maxBrightness = std::nullopt;
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000422
423 // Light name should follow the naming pattern <name>:<color>:<function>
424 // Refer kernel docs /leds/leds-class.html for valid supported LED names.
425 std::regex indexPattern("([a-zA-Z0-9_.:]*:)?([a-zA-Z0-9_.]*):([a-zA-Z0-9_.]*)");
426 std::smatch results;
427
428 if (std::regex_match(info.name, results, indexPattern)) {
429 // regex_match will return full match at index 0 and <name> at index 1. For RawLightInfo
430 // we only care about sections <color> and <function> which will be at index 2 and 3.
431 for (int i = 2; i <= 3; i++) {
432 const auto it = LIGHT_CLASSES.find(results.str(i));
433 if (it != LIGHT_CLASSES.end()) {
434 info.flags |= it->second;
435 }
Prabir Pradhancb42b472022-08-23 16:01:19 +0000436 }
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000437
438 // Set name of the raw light to <function> which represents playerIDs for LEDs that
439 // turn on/off based on the current player ID (Refer to PeripheralController.cpp for
440 // player ID logic)
441 info.name = results.str(3);
Prabir Pradhancb42b472022-08-23 16:01:19 +0000442 }
443 // Scan the path for all the files
444 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
445 const auto& files = allFilesInPath(nodePath);
446 for (const auto& file : files) {
447 const auto it = LIGHT_CLASSES.find(file.filename().string());
448 if (it != LIGHT_CLASSES.end()) {
449 info.flags |= it->second;
450 // If the node has maximum brightness, read it
451 if (it->second == InputLightClass::MAX_BRIGHTNESS) {
452 std::string str;
453 if (base::ReadFileToString(file, &str)) {
454 info.maxBrightness = std::stoi(str);
455 }
456 }
457 }
458 }
459 lightInfos.insert_or_assign(info.id, info);
460 ALOGD("configureLightsLocked rawLightId %d name %s", info.id, info.name.c_str());
461 }
462 return lightInfos;
463}
464
Michael Wrightd02c5b62014-02-10 15:10:22 -0800465// --- Global Functions ---
466
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700467ftl::Flags<InputDeviceClass> getAbsAxisUsage(int32_t axis,
468 ftl::Flags<InputDeviceClass> deviceClasses) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800469 // Touch devices get dibs on touch-related axes.
Chris Ye1b0c7342020-07-28 21:57:03 -0700470 if (deviceClasses.test(InputDeviceClass::TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800471 switch (axis) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700472 case ABS_X:
473 case ABS_Y:
474 case ABS_PRESSURE:
475 case ABS_TOOL_WIDTH:
476 case ABS_DISTANCE:
477 case ABS_TILT_X:
478 case ABS_TILT_Y:
479 case ABS_MT_SLOT:
480 case ABS_MT_TOUCH_MAJOR:
481 case ABS_MT_TOUCH_MINOR:
482 case ABS_MT_WIDTH_MAJOR:
483 case ABS_MT_WIDTH_MINOR:
484 case ABS_MT_ORIENTATION:
485 case ABS_MT_POSITION_X:
486 case ABS_MT_POSITION_Y:
487 case ABS_MT_TOOL_TYPE:
488 case ABS_MT_BLOB_ID:
489 case ABS_MT_TRACKING_ID:
490 case ABS_MT_PRESSURE:
491 case ABS_MT_DISTANCE:
Chris Ye1b0c7342020-07-28 21:57:03 -0700492 return InputDeviceClass::TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800493 }
494 }
495
Chris Yef59a2f42020-10-16 12:55:26 -0700496 if (deviceClasses.test(InputDeviceClass::SENSOR)) {
497 switch (axis) {
498 case ABS_X:
499 case ABS_Y:
500 case ABS_Z:
501 case ABS_RX:
502 case ABS_RY:
503 case ABS_RZ:
504 return InputDeviceClass::SENSOR;
505 }
506 }
507
Michael Wright842500e2015-03-13 17:32:02 -0700508 // External stylus gets the pressure axis
Chris Ye1b0c7342020-07-28 21:57:03 -0700509 if (deviceClasses.test(InputDeviceClass::EXTERNAL_STYLUS)) {
Michael Wright842500e2015-03-13 17:32:02 -0700510 if (axis == ABS_PRESSURE) {
Chris Ye1b0c7342020-07-28 21:57:03 -0700511 return InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -0700512 }
513 }
514
Michael Wrightd02c5b62014-02-10 15:10:22 -0800515 // Joystick devices get the rest.
Chris Ye1b0c7342020-07-28 21:57:03 -0700516 return deviceClasses & InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800517}
518
Harry Cuttsea73eaa2023-01-16 17:55:46 +0000519// --- RawAbsoluteAxisInfo ---
520
Prabir Pradhan132f21c2024-07-25 16:48:30 +0000521std::ostream& operator<<(std::ostream& out, const std::optional<RawAbsoluteAxisInfo>& info) {
522 if (info) {
523 out << "min=" << info->minValue << ", max=" << info->maxValue << ", flat=" << info->flat
524 << ", fuzz=" << info->fuzz << ", resolution=" << info->resolution;
Harry Cuttsea73eaa2023-01-16 17:55:46 +0000525 } else {
526 out << "unknown range";
527 }
528 return out;
529}
530
Michael Wrightd02c5b62014-02-10 15:10:22 -0800531// --- EventHub::Device ---
532
Prabir Pradhancb42b472022-08-23 16:01:19 +0000533EventHub::Device::Device(int fd, int32_t id, std::string path, InputDeviceIdentifier identifier,
534 std::shared_ptr<const AssociatedDevice> assocDev)
Chris Ye989bb932020-07-04 16:18:59 -0700535 : fd(fd),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700536 id(id),
Prabir Pradhancb42b472022-08-23 16:01:19 +0000537 path(std::move(path)),
538 identifier(std::move(identifier)),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700539 classes(0),
540 configuration(nullptr),
541 virtualKeyMap(nullptr),
542 ffEffectPlaying(false),
543 ffEffectId(-1),
Prabir Pradhancb42b472022-08-23 16:01:19 +0000544 associatedDevice(std::move(assocDev)),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700545 controllerNumber(0),
546 enabled(true),
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000547 isVirtual(fd < 0),
548 currentFrameDropped(false) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800549
550EventHub::Device::~Device() {
551 close();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800552}
553
554void EventHub::Device::close() {
555 if (fd >= 0) {
556 ::close(fd);
557 fd = -1;
558 }
559}
560
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700561status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100562 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700563 if (fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100564 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700565 return -errno;
566 }
567 enabled = true;
568 return OK;
569}
570
571status_t EventHub::Device::disable() {
572 close();
573 enabled = false;
574 return OK;
575}
576
Chris Ye989bb932020-07-04 16:18:59 -0700577bool EventHub::Device::hasValidFd() const {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700578 return !isVirtual && enabled;
579}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800580
Chris Ye3a1e4462020-08-12 10:13:15 -0700581const std::shared_ptr<KeyCharacterMap> EventHub::Device::getKeyCharacterMap() const {
Chris Ye989bb932020-07-04 16:18:59 -0700582 return keyMap.keyCharacterMap;
583}
584
585template <std::size_t N>
586status_t EventHub::Device::readDeviceBitMask(unsigned long ioctlCode, BitArray<N>& bitArray) {
587 if (!hasValidFd()) {
588 return BAD_VALUE;
589 }
590 if ((_IOC_SIZE(ioctlCode) == 0)) {
591 ioctlCode |= _IOC(0, 0, 0, bitArray.bytes());
592 }
593
594 typename BitArray<N>::Buffer buffer;
595 status_t ret = ioctl(fd, ioctlCode, buffer.data());
596 bitArray.loadFromBuffer(buffer);
597 return ret;
598}
599
600void EventHub::Device::configureFd() {
601 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
602 if (classes.test(InputDeviceClass::KEYBOARD)) {
603 // Disable kernel key repeat since we handle it ourselves
604 unsigned int repeatRate[] = {0, 0};
605 if (ioctl(fd, EVIOCSREP, repeatRate)) {
606 ALOGW("Unable to disable kernel key repeat for %s: %s", path.c_str(), strerror(errno));
607 }
608 }
609
610 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
611 // associated with input events. This is important because the input system
612 // uses the timestamps extensively and assumes they were recorded using the monotonic
613 // clock.
614 int clockId = CLOCK_MONOTONIC;
Chris Yef59a2f42020-10-16 12:55:26 -0700615 if (classes.test(InputDeviceClass::SENSOR)) {
616 // Each new sensor event should use the same time base as
617 // SystemClock.elapsedRealtimeNanos().
618 clockId = CLOCK_BOOTTIME;
619 }
Chris Ye989bb932020-07-04 16:18:59 -0700620 bool usingClockIoctl = !ioctl(fd, EVIOCSCLOCKID, &clockId);
621 ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000622
623 // Query the initial state of keys and switches, which is tracked by EventHub.
624 readDeviceState();
625}
626
627void EventHub::Device::readDeviceState() {
628 if (readDeviceBitMask(EVIOCGKEY(0), keyState) < 0) {
629 ALOGD("Unable to query the global key state for %s: %s", path.c_str(), strerror(errno));
630 }
631 if (readDeviceBitMask(EVIOCGSW(0), swState) < 0) {
632 ALOGD("Unable to query the global switch state for %s: %s", path.c_str(), strerror(errno));
633 }
Prabir Pradhan341d0782023-07-14 19:04:10 +0000634
635 // Read absolute axis info and values for all available axes for the device.
636 populateAbsoluteAxisStates();
637}
638
639void EventHub::Device::populateAbsoluteAxisStates() {
640 absState.clear();
641
642 for (int axis = 0; axis <= ABS_MAX; axis++) {
643 if (!absBitmask.test(axis)) {
644 continue;
645 }
646 struct input_absinfo info {};
647 if (ioctl(fd, EVIOCGABS(axis), &info)) {
648 ALOGE("Error reading absolute controller %d for device %s fd %d: %s", axis,
649 identifier.name.c_str(), fd, strerror(errno));
650 continue;
651 }
Prabir Pradhan341d0782023-07-14 19:04:10 +0000652 auto& [axisInfo, value] = absState[axis];
Prabir Pradhan341d0782023-07-14 19:04:10 +0000653 axisInfo.minValue = info.minimum;
654 axisInfo.maxValue = info.maximum;
655 axisInfo.flat = info.flat;
656 axisInfo.fuzz = info.fuzz;
657 axisInfo.resolution = info.resolution;
658 value = info.value;
659 }
Chris Ye989bb932020-07-04 16:18:59 -0700660}
661
662bool EventHub::Device::hasKeycodeLocked(int keycode) const {
Vaibhav Devmurari5a71e882024-09-30 15:54:41 +0000663 if (hasKeycodeInternalLocked(keycode)) {
664 return true;
665 }
Rishi Sikka956a6ce2024-10-10 11:31:18 +0000666 if (!keyMap.haveKeyCharacterMap()) {
Rishi Sikka8cb62fe2024-10-10 11:31:18 +0000667 return false;
668 }
Rishi Sikka956a6ce2024-10-10 11:31:18 +0000669 for (auto& fromKey : getKeyCharacterMap()->findKeyCodesMappedToKeyCode(keycode)) {
Vaibhav Devmurari5a71e882024-09-30 15:54:41 +0000670 if (hasKeycodeInternalLocked(fromKey)) {
671 return true;
672 }
673 }
674 return false;
675}
676
677bool EventHub::Device::hasKeycodeInternalLocked(int keycode) const {
Chris Ye989bb932020-07-04 16:18:59 -0700678 if (!keyMap.haveKeyLayout()) {
679 return false;
680 }
681
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700682 std::vector<int32_t> scanCodes = keyMap.keyLayoutMap->findScanCodesForKey(keycode);
Chris Ye989bb932020-07-04 16:18:59 -0700683 const size_t N = scanCodes.size();
684 for (size_t i = 0; i < N && i <= KEY_MAX; i++) {
685 int32_t sc = scanCodes[i];
686 if (sc >= 0 && sc <= KEY_MAX && keyBitmask.test(sc)) {
687 return true;
688 }
689 }
690
Charles Linaadf8d52023-03-30 13:34:54 +0800691 std::vector<int32_t> usageCodes = keyMap.keyLayoutMap->findUsageCodesForKey(keycode);
692 if (usageCodes.size() > 0 && mscBitmask.test(MSC_SCAN)) {
693 return true;
694 }
Chris Ye989bb932020-07-04 16:18:59 -0700695 return false;
696}
697
698void EventHub::Device::loadConfigurationLocked() {
699 configurationFile =
700 getInputDeviceConfigurationFilePathByDeviceIdentifier(identifier,
701 InputDeviceConfigurationFileType::
702 CONFIGURATION);
703 if (configurationFile.empty()) {
704 ALOGD("No input device configuration file found for device '%s'.", identifier.name.c_str());
705 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500706 android::base::Result<std::unique_ptr<PropertyMap>> propertyMap =
707 PropertyMap::load(configurationFile.c_str());
708 if (!propertyMap.ok()) {
Chris Ye989bb932020-07-04 16:18:59 -0700709 ALOGE("Error loading input device configuration file for device '%s'. "
710 "Using default configuration.",
711 identifier.name.c_str());
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500712 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500713 configuration = std::move(*propertyMap);
Chris Ye989bb932020-07-04 16:18:59 -0700714 }
715 }
716}
717
718bool EventHub::Device::loadVirtualKeyMapLocked() {
719 // The virtual key map is supplied by the kernel as a system board property file.
720 std::string propPath = "/sys/board_properties/virtualkeys.";
721 propPath += identifier.getCanonicalName();
722 if (access(propPath.c_str(), R_OK)) {
723 return false;
724 }
725 virtualKeyMap = VirtualKeyMap::load(propPath);
726 return virtualKeyMap != nullptr;
727}
728
729status_t EventHub::Device::loadKeyMapLocked() {
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500730 return keyMap.load(identifier, configuration.get());
Chris Ye989bb932020-07-04 16:18:59 -0700731}
732
733bool EventHub::Device::isExternalDeviceLocked() {
734 if (configuration) {
Harry Cuttsf13161a2023-03-08 14:15:49 +0000735 std::optional<bool> isInternal = configuration->getBool("device.internal");
736 if (isInternal.has_value()) {
737 return !isInternal.value();
Chris Ye989bb932020-07-04 16:18:59 -0700738 }
739 }
740 return identifier.bus == BUS_USB || identifier.bus == BUS_BLUETOOTH;
741}
742
743bool EventHub::Device::deviceHasMicLocked() {
744 if (configuration) {
Harry Cuttsf13161a2023-03-08 14:15:49 +0000745 std::optional<bool> hasMic = configuration->getBool("audio.mic");
746 if (hasMic.has_value()) {
747 return hasMic.value();
Chris Ye989bb932020-07-04 16:18:59 -0700748 }
749 }
750 return false;
751}
752
753void EventHub::Device::setLedStateLocked(int32_t led, bool on) {
754 int32_t sc;
755 if (hasValidFd() && mapLed(led, &sc) != NAME_NOT_FOUND) {
756 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -0700757 ev.input_event_sec = 0;
758 ev.input_event_usec = 0;
Chris Ye989bb932020-07-04 16:18:59 -0700759 ev.type = EV_LED;
760 ev.code = sc;
761 ev.value = on ? 1 : 0;
762
763 ssize_t nWrite;
764 do {
765 nWrite = write(fd, &ev, sizeof(struct input_event));
766 } while (nWrite == -1 && errno == EINTR);
767 }
768}
769
770void EventHub::Device::setLedForControllerLocked() {
771 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
772 setLedStateLocked(ALED_CONTROLLER_1 + i, controllerNumber == i + 1);
773 }
774}
775
776status_t EventHub::Device::mapLed(int32_t led, int32_t* outScanCode) const {
777 if (!keyMap.haveKeyLayout()) {
778 return NAME_NOT_FOUND;
779 }
780
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700781 std::optional<int32_t> scanCode = keyMap.keyLayoutMap->findScanCodeForLed(led);
782 if (scanCode.has_value()) {
783 if (*scanCode >= 0 && *scanCode <= LED_MAX && ledBitmask.test(*scanCode)) {
784 *outScanCode = *scanCode;
Chris Ye989bb932020-07-04 16:18:59 -0700785 return NO_ERROR;
786 }
787 }
788 return NAME_NOT_FOUND;
789}
790
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000791void EventHub::Device::trackInputEvent(const struct input_event& event) {
792 switch (event.type) {
793 case EV_KEY: {
794 LOG_ALWAYS_FATAL_IF(!currentFrameDropped &&
795 !keyState.set(static_cast<size_t>(event.code),
796 event.value != 0),
Prabir Pradhan10301422023-07-26 21:48:30 +0000797 "%s: device '%s' received invalid EV_KEY event code: %s value: %d",
798 __func__, identifier.name.c_str(),
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000799 InputEventLookup::getLinuxEvdevLabel(EV_KEY, event.code, 1)
Prabir Pradhan10301422023-07-26 21:48:30 +0000800 .code.c_str(),
801 event.value);
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000802 break;
803 }
804 case EV_SW: {
805 LOG_ALWAYS_FATAL_IF(!currentFrameDropped &&
806 !swState.set(static_cast<size_t>(event.code),
807 event.value != 0),
Prabir Pradhan10301422023-07-26 21:48:30 +0000808 "%s: device '%s' received invalid EV_SW event code: %s value: %d",
809 __func__, identifier.name.c_str(),
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000810 InputEventLookup::getLinuxEvdevLabel(EV_SW, event.code, 1)
Prabir Pradhan10301422023-07-26 21:48:30 +0000811 .code.c_str(),
812 event.value);
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000813 break;
814 }
Prabir Pradhan341d0782023-07-14 19:04:10 +0000815 case EV_ABS: {
Prabir Pradhan10301422023-07-26 21:48:30 +0000816 if (currentFrameDropped) {
817 break;
818 }
Prabir Pradhan341d0782023-07-14 19:04:10 +0000819 auto it = absState.find(event.code);
Prabir Pradhan10301422023-07-26 21:48:30 +0000820 LOG_ALWAYS_FATAL_IF(it == absState.end(),
821 "%s: device '%s' received invalid EV_ABS event code: %s value: %d",
822 __func__, identifier.name.c_str(),
Prabir Pradhan341d0782023-07-14 19:04:10 +0000823 InputEventLookup::getLinuxEvdevLabel(EV_ABS, event.code, 0)
Prabir Pradhan10301422023-07-26 21:48:30 +0000824 .code.c_str(),
825 event.value);
Prabir Pradhan341d0782023-07-14 19:04:10 +0000826 it->second.value = event.value;
827 break;
828 }
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000829 case EV_SYN: {
830 switch (event.code) {
831 case SYN_REPORT:
Arpit Singh1c3d8552024-01-08 14:16:28 +0000832 if (currentFrameDropped) {
833 // To recover after a SYN_DROPPED, we need to query the state of the device
834 // to synchronize our device state with the kernel's to account for the
835 // dropped events on receiving the next SYN_REPORT.
836 // Note we don't drop the SYN_REPORT at this point but it is used by the
837 // InputDevice to reset and repopulate mapper state
838 readDeviceState();
839 currentFrameDropped = false;
840 }
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000841 break;
842 case SYN_DROPPED:
843 // When we receive SYN_DROPPED, all events in the current frame should be
Arpit Singh1c3d8552024-01-08 14:16:28 +0000844 // dropped up to and including next SYN_REPORT
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000845 currentFrameDropped = true;
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000846 break;
847 default:
848 break;
849 }
850 break;
851 }
852 default:
853 break;
854 }
855}
856
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100857/**
858 * Get the capabilities for the current process.
859 * Crashes the system if unable to create / check / destroy the capabilities object.
860 */
861class Capabilities final {
862public:
863 explicit Capabilities() {
864 mCaps = cap_get_proc();
865 LOG_ALWAYS_FATAL_IF(mCaps == nullptr, "Could not get capabilities of the current process");
866 }
867
868 /**
869 * Check whether the current process has a specific capability
870 * in the set of effective capabilities.
871 * Return CAP_SET if the process has the requested capability
872 * Return CAP_CLEAR otherwise.
873 */
874 cap_flag_value_t checkEffectiveCapability(cap_value_t capability) {
875 cap_flag_value_t value;
876 const int result = cap_get_flag(mCaps, capability, CAP_EFFECTIVE, &value);
877 LOG_ALWAYS_FATAL_IF(result == -1, "Could not obtain the requested capability");
878 return value;
879 }
880
881 ~Capabilities() {
882 const int result = cap_free(mCaps);
883 LOG_ALWAYS_FATAL_IF(result == -1, "Could not release the capabilities structure");
884 }
885
886private:
887 cap_t mCaps;
888};
889
890static void ensureProcessCanBlockSuspend() {
891 Capabilities capabilities;
892 const bool canBlockSuspend =
893 capabilities.checkEffectiveCapability(CAP_BLOCK_SUSPEND) == CAP_SET;
894 LOG_ALWAYS_FATAL_IF(!canBlockSuspend,
895 "Input must be able to block suspend to properly process events");
896}
897
Michael Wrightd02c5b62014-02-10 15:10:22 -0800898// --- EventHub ---
899
Michael Wrightd02c5b62014-02-10 15:10:22 -0800900const int EventHub::EPOLL_MAX_EVENTS;
901
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700902EventHub::EventHub(void)
903 : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
904 mNextDeviceId(1),
905 mControllerNumbers(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700906 mNeedToReopenDevices(false),
907 mNeedToScanDevices(true),
908 mPendingEventCount(0),
909 mPendingEventIndex(0),
910 mPendingINotify(false) {
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100911 ensureProcessCanBlockSuspend();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800912
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800913 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800914 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800915
Michael Wright8e9a8562022-02-09 13:44:29 +0000916 mINotifyFd = inotify_init1(IN_CLOEXEC);
Prabir Pradhan952e65b2022-06-23 17:49:55 +0000917 LOG_ALWAYS_FATAL_IF(mINotifyFd < 0, "Could not create inotify instance: %s", strerror(errno));
Usama Arifb27c8e62021-06-03 16:44:09 +0100918
919 std::error_code errorCode;
920 bool isDeviceInotifyAdded = false;
921 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
922 addDeviceInputInotify();
Philip Quinn39b81682019-01-09 22:20:39 -0800923 } else {
Usama Arifb27c8e62021-06-03 16:44:09 +0100924 addDeviceInotify();
925 isDeviceInotifyAdded = true;
926 if (errorCode) {
927 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
928 errorCode.message().c_str());
929 }
930 }
931
932 if (isV4lScanningEnabled() && !isDeviceInotifyAdded) {
933 addDeviceInotify();
934 } else {
Philip Quinn39b81682019-01-09 22:20:39 -0800935 ALOGI("Video device scanning disabled");
936 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800937
Siarhei Vishniakou2d0e9482019-09-24 12:52:47 +0100938 struct epoll_event eventItem = {};
939 eventItem.events = EPOLLIN | EPOLLWAKEUP;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700940 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800941 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800942 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
943
944 int wakeFds[2];
Michael Wright8e9a8562022-02-09 13:44:29 +0000945 result = pipe2(wakeFds, O_CLOEXEC);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800946 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
947
948 mWakeReadPipeFd = wakeFds[0];
949 mWakeWritePipeFd = wakeFds[1];
950
951 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
952 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700953 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800954
955 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
956 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700957 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800958
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700959 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800960 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
961 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700962 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800963}
964
965EventHub::~EventHub(void) {
966 closeAllDevicesLocked();
967
Michael Wrightd02c5b62014-02-10 15:10:22 -0800968 ::close(mEpollFd);
969 ::close(mINotifyFd);
970 ::close(mWakeReadPipeFd);
971 ::close(mWakeWritePipeFd);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800972}
973
Usama Arifb27c8e62021-06-03 16:44:09 +0100974/**
975 * On devices that don't have any input devices (like some development boards), the /dev/input
976 * directory will be absent. However, the user may still plug in an input device at a later time.
977 * Add watch for contents of /dev/input only when /dev/input appears.
978 */
979void EventHub::addDeviceInputInotify() {
980 mDeviceInputWd = inotify_add_watch(mINotifyFd, DEVICE_INPUT_PATH, IN_DELETE | IN_CREATE);
981 LOG_ALWAYS_FATAL_IF(mDeviceInputWd < 0, "Could not register INotify for %s: %s",
982 DEVICE_INPUT_PATH, strerror(errno));
983}
984
985void EventHub::addDeviceInotify() {
986 mDeviceWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
987 LOG_ALWAYS_FATAL_IF(mDeviceWd < 0, "Could not register INotify for %s: %s", DEVICE_PATH,
988 strerror(errno));
989}
990
Michael Wrightd02c5b62014-02-10 15:10:22 -0800991InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000992 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800993 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700994 return device != nullptr ? device->identifier : InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800995}
996
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700997ftl::Flags<InputDeviceClass> EventHub::getDeviceClasses(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000998 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800999 Device* device = getDeviceLocked(deviceId);
Dominik Laskowski2f01d772022-03-23 16:01:29 -07001000 return device != nullptr ? device->classes : ftl::Flags<InputDeviceClass>(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001001}
1002
1003int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001004 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001005 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -07001006 return device != nullptr ? device->controllerNumber : 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001007}
1008
Harry Cuttsc34f7582023-03-07 16:23:30 +00001009std::optional<PropertyMap> EventHub::getConfiguration(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001010 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001011 Device* device = getDeviceLocked(deviceId);
Harry Cuttsc34f7582023-03-07 16:23:30 +00001012 if (device == nullptr || device->configuration == nullptr) {
1013 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001014 }
Harry Cuttsc34f7582023-03-07 16:23:30 +00001015 return *device->configuration;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001016}
1017
Harry Cutts207674d2024-06-06 18:53:41 +00001018std::optional<RawAbsoluteAxisInfo> EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis) const {
Arpit Singh77140f42023-06-13 11:35:27 +00001019 if (axis < 0 || axis > ABS_MAX) {
Harry Cutts207674d2024-06-06 18:53:41 +00001020 return std::nullopt;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001021 }
Arpit Singh77140f42023-06-13 11:35:27 +00001022 std::scoped_lock _l(mLock);
Prabir Pradhan341d0782023-07-14 19:04:10 +00001023 const Device* device = getDeviceLocked(deviceId);
Arpit Singh77140f42023-06-13 11:35:27 +00001024 if (device == nullptr) {
Harry Cuttsd6a3fb52024-10-23 09:48:55 +00001025 ALOGE("Couldn't find device with ID %d, so returning null axis info for axis %s", deviceId,
1026 InputEventLookup::getLinuxEvdevLabel(EV_ABS, axis, 0).code.c_str());
Harry Cutts207674d2024-06-06 18:53:41 +00001027 return std::nullopt;
Arpit Singh77140f42023-06-13 11:35:27 +00001028 }
Prabir Pradhan341d0782023-07-14 19:04:10 +00001029 // We can read the RawAbsoluteAxisInfo even if the device is disabled and doesn't have a valid
1030 // fd, because the info is populated once when the device is first opened, and it doesn't change
1031 // throughout the device lifecycle.
1032 auto it = device->absState.find(axis);
1033 if (it == device->absState.end()) {
Harry Cutts207674d2024-06-06 18:53:41 +00001034 return std::nullopt;
Arpit Singh77140f42023-06-13 11:35:27 +00001035 }
Harry Cutts207674d2024-06-06 18:53:41 +00001036 return it->second.info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001037}
1038
1039bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
1040 if (axis >= 0 && axis <= REL_MAX) {
Chris Ye87143712020-11-10 05:05:58 +00001041 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001042 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001043 return device != nullptr ? device->relBitmask.test(axis) : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001044 }
1045 return false;
1046}
1047
1048bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
Chris Ye87143712020-11-10 05:05:58 +00001049 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001050
Chris Ye989bb932020-07-04 16:18:59 -07001051 Device* device = getDeviceLocked(deviceId);
1052 return property >= 0 && property <= INPUT_PROP_MAX && device != nullptr
1053 ? device->propBitmask.test(property)
1054 : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001055}
1056
Chris Yef59a2f42020-10-16 12:55:26 -07001057bool EventHub::hasMscEvent(int32_t deviceId, int mscEvent) const {
1058 std::scoped_lock _l(mLock);
1059
1060 Device* device = getDeviceLocked(deviceId);
1061 return mscEvent >= 0 && mscEvent <= MSC_MAX && device != nullptr
1062 ? device->mscBitmask.test(mscEvent)
1063 : false;
1064}
1065
Michael Wrightd02c5b62014-02-10 15:10:22 -08001066int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001067 if (scanCode < 0 || scanCode > KEY_MAX) {
1068 return AKEY_STATE_UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001069 }
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001070 std::scoped_lock _l(mLock);
1071 const Device* device = getDeviceLocked(deviceId);
1072 if (device == nullptr || !device->hasValidFd() || !device->keyBitmask.test(scanCode)) {
1073 return AKEY_STATE_UNKNOWN;
1074 }
1075 return device->keyState.test(scanCode) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001076}
1077
1078int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
Chris Ye87143712020-11-10 05:05:58 +00001079 std::scoped_lock _l(mLock);
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001080 const Device* device = getDeviceLocked(deviceId);
1081 if (device == nullptr || !device->hasValidFd() || !device->keyMap.haveKeyLayout()) {
1082 return AKEY_STATE_UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001083 }
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001084 const std::vector<int32_t> scanCodes =
1085 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode);
1086 if (scanCodes.empty()) {
1087 return AKEY_STATE_UNKNOWN;
1088 }
1089 return std::any_of(scanCodes.begin(), scanCodes.end(),
1090 [&device](const int32_t sc) {
1091 return sc >= 0 && sc <= KEY_MAX && device->keyState.test(sc);
1092 })
1093 ? AKEY_STATE_DOWN
1094 : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001095}
1096
Philip Junker4af3b3d2021-12-14 10:36:55 +01001097int32_t EventHub::getKeyCodeForKeyLocation(int32_t deviceId, int32_t locationKeyCode) const {
1098 std::scoped_lock _l(mLock);
1099
1100 Device* device = getDeviceLocked(deviceId);
1101 if (device == nullptr || !device->hasValidFd() || device->keyMap.keyCharacterMap == nullptr ||
1102 device->keyMap.keyLayoutMap == nullptr) {
1103 return AKEYCODE_UNKNOWN;
1104 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001105 std::vector<int32_t> scanCodes =
1106 device->keyMap.keyLayoutMap->findScanCodesForKey(locationKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +01001107 if (scanCodes.empty()) {
1108 ALOGW("Failed to get key code for key location: no scan code maps to key code %d for input"
1109 "device %d",
1110 locationKeyCode, deviceId);
1111 return AKEYCODE_UNKNOWN;
1112 }
1113 if (scanCodes.size() > 1) {
1114 ALOGW("Multiple scan codes map to the same key code %d, returning only the first match",
1115 locationKeyCode);
1116 }
1117 int32_t outKeyCode;
1118 status_t mapKeyRes =
Harry Cutts33476232023-01-30 19:57:29 +00001119 device->getKeyCharacterMap()->mapKey(scanCodes[0], /*usageCode=*/0, &outKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +01001120 switch (mapKeyRes) {
1121 case OK:
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001122 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +01001123 case NAME_NOT_FOUND:
1124 // key character map doesn't re-map this scanCode, hence the keyCode remains the same
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001125 outKeyCode = locationKeyCode;
1126 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +01001127 default:
1128 ALOGW("Failed to get key code for key location: Key character map returned error %s",
1129 statusToString(mapKeyRes).c_str());
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001130 outKeyCode = AKEYCODE_UNKNOWN;
1131 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +01001132 }
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001133 // Remap if there is a Key remapping added to the KCM and return the remapped key
1134 return device->getKeyCharacterMap()->applyKeyRemapping(outKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +01001135}
1136
Michael Wrightd02c5b62014-02-10 15:10:22 -08001137int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001138 if (sw < 0 || sw > SW_MAX) {
1139 return AKEY_STATE_UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001140 }
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001141 std::scoped_lock _l(mLock);
1142 const Device* device = getDeviceLocked(deviceId);
1143 if (device == nullptr || !device->hasValidFd() || !device->swBitmask.test(sw)) {
1144 return AKEY_STATE_UNKNOWN;
1145 }
1146 return device->swState.test(sw) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001147}
1148
Harry Cuttse2c5e202024-06-21 17:08:48 +00001149std::optional<int32_t> EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis) const {
Prabir Pradhan341d0782023-07-14 19:04:10 +00001150 if (axis < 0 || axis > ABS_MAX) {
Harry Cuttse2c5e202024-06-21 17:08:48 +00001151 return std::nullopt;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001152 }
Prabir Pradhan341d0782023-07-14 19:04:10 +00001153 std::scoped_lock _l(mLock);
1154 const Device* device = getDeviceLocked(deviceId);
1155 if (device == nullptr || !device->hasValidFd()) {
Harry Cuttse2c5e202024-06-21 17:08:48 +00001156 return std::nullopt;
Prabir Pradhan341d0782023-07-14 19:04:10 +00001157 }
1158 const auto it = device->absState.find(axis);
1159 if (it == device->absState.end()) {
Harry Cuttse2c5e202024-06-21 17:08:48 +00001160 return std::nullopt;
Prabir Pradhan341d0782023-07-14 19:04:10 +00001161 }
Harry Cuttse2c5e202024-06-21 17:08:48 +00001162 return it->second.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001163}
1164
Arpit Singh4b4a4572023-11-24 18:19:56 +00001165base::Result<std::vector<int32_t>> EventHub::getMtSlotValues(int32_t deviceId, int32_t axis,
1166 size_t slotCount) const {
1167 std::scoped_lock _l(mLock);
1168 const Device* device = getDeviceLocked(deviceId);
1169 if (device == nullptr || !device->hasValidFd() || !device->absBitmask.test(axis)) {
1170 return base::ResultError("device problem or axis not supported", NAME_NOT_FOUND);
1171 }
1172 std::vector<int32_t> outValues(slotCount + 1);
1173 outValues[0] = axis;
1174 const size_t bufferSize = outValues.size() * sizeof(int32_t);
1175 if (ioctl(device->fd, EVIOCGMTSLOTS(bufferSize), outValues.data()) != OK) {
1176 return base::ErrnoError();
1177 }
1178 return std::move(outValues);
1179}
1180
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001181bool EventHub::markSupportedKeyCodes(int32_t deviceId, const std::vector<int32_t>& keyCodes,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001182 uint8_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +00001183 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001184
1185 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001186 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001187 for (size_t codeIndex = 0; codeIndex < keyCodes.size(); codeIndex++) {
Sergej Salnikove5420e72023-05-11 11:52:54 +00001188 if (device->hasKeycodeLocked(keyCodes[codeIndex])) {
1189 outFlags[codeIndex] = 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001190 }
1191 }
1192 return true;
1193 }
1194 return false;
1195}
1196
Linnan Lie5657f22024-09-13 21:54:37 +08001197void EventHub::setKeyRemapping(int32_t deviceId,
1198 const std::map<int32_t, int32_t>& keyRemapping) const {
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001199 std::scoped_lock _l(mLock);
1200 Device* device = getDeviceLocked(deviceId);
1201 if (device == nullptr) {
1202 return;
1203 }
1204 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
1205 if (kcm) {
Linnan Lie5657f22024-09-13 21:54:37 +08001206 kcm->setKeyRemapping(keyRemapping);
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001207 }
1208}
1209
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001210status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
1211 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +00001212 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001213 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001214 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001215
Chris Ye66fbac32020-07-06 20:36:43 -07001216 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001217 // Check the key character map first.
Chris Ye3a1e4462020-08-12 10:13:15 -07001218 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
1219 if (kcm) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001220 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
1221 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001222 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001223 }
1224 }
1225
1226 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001227 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -08001228 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001229 status = NO_ERROR;
1230 }
1231 }
1232
1233 if (status == NO_ERROR) {
Chris Ye3a1e4462020-08-12 10:13:15 -07001234 if (kcm) {
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001235 // Remap keys based on user-defined key remappings and key behavior defined in the
1236 // corresponding kcm file
1237 *outKeycode = kcm->applyKeyRemapping(*outKeycode);
1238
1239 // Remap keys based on Key behavior defined in KCM file
1240 std::tie(*outKeycode, *outMetaState) =
1241 kcm->applyKeyBehavior(*outKeycode, metaState);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001242 } else {
1243 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001244 }
1245 }
1246 }
1247
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001248 if (status != NO_ERROR) {
1249 *outKeycode = 0;
1250 *outFlags = 0;
1251 *outMetaState = metaState;
1252 }
1253
1254 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001255}
1256
1257status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
Chris Ye87143712020-11-10 05:05:58 +00001258 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001259 Device* device = getDeviceLocked(deviceId);
1260
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001261 if (device == nullptr || !device->keyMap.haveKeyLayout()) {
1262 return NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001263 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001264 std::optional<AxisInfo> info = device->keyMap.keyLayoutMap->mapAxis(scanCode);
1265 if (!info.has_value()) {
1266 return NAME_NOT_FOUND;
1267 }
1268 *outAxisInfo = *info;
1269 return NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001270}
1271
Chris Yef59a2f42020-10-16 12:55:26 -07001272base::Result<std::pair<InputDeviceSensorType, int32_t>> EventHub::mapSensor(int32_t deviceId,
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001273 int32_t absCode) const {
Chris Yef59a2f42020-10-16 12:55:26 -07001274 std::scoped_lock _l(mLock);
1275 Device* device = getDeviceLocked(deviceId);
1276
1277 if (device != nullptr && device->keyMap.haveKeyLayout()) {
1278 return device->keyMap.keyLayoutMap->mapSensor(absCode);
1279 }
1280 return Errorf("Device not found or device has no key layout.");
1281}
1282
Chris Yee2b1e5c2021-03-10 22:45:12 -08001283// Gets the battery info map from battery ID to RawBatteryInfo of the miscellaneous device
1284// associated with the device ID. Returns an empty map if no miscellaneous device found.
1285const std::unordered_map<int32_t, RawBatteryInfo>& EventHub::getBatteryInfoLocked(
1286 int32_t deviceId) const {
1287 static const std::unordered_map<int32_t, RawBatteryInfo> EMPTY_BATTERY_INFO = {};
1288 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001289 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001290 return EMPTY_BATTERY_INFO;
1291 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001292 return device->associatedDevice->batteryInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001293}
1294
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001295std::vector<int32_t> EventHub::getRawBatteryIds(int32_t deviceId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001296 std::scoped_lock _l(mLock);
1297 std::vector<int32_t> batteryIds;
1298
Prabir Pradhan51894782022-08-23 16:29:10 +00001299 for (const auto& [id, info] : getBatteryInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001300 batteryIds.push_back(id);
1301 }
1302
1303 return batteryIds;
1304}
1305
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001306std::optional<RawBatteryInfo> EventHub::getRawBatteryInfo(int32_t deviceId,
1307 int32_t batteryId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001308 std::scoped_lock _l(mLock);
1309
1310 const auto infos = getBatteryInfoLocked(deviceId);
1311
1312 auto it = infos.find(batteryId);
1313 if (it != infos.end()) {
1314 return it->second;
1315 }
1316
1317 return std::nullopt;
1318}
1319
1320// Gets the light info map from light ID to RawLightInfo of the miscellaneous device associated
Prabir Pradhan51894782022-08-23 16:29:10 +00001321// with the device ID. Returns an empty map if no miscellaneous device found.
Chris Yee2b1e5c2021-03-10 22:45:12 -08001322const std::unordered_map<int32_t, RawLightInfo>& EventHub::getLightInfoLocked(
1323 int32_t deviceId) const {
1324 static const std::unordered_map<int32_t, RawLightInfo> EMPTY_LIGHT_INFO = {};
1325 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001326 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001327 return EMPTY_LIGHT_INFO;
1328 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001329 return device->associatedDevice->lightInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001330}
1331
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001332std::vector<int32_t> EventHub::getRawLightIds(int32_t deviceId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001333 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001334 std::vector<int32_t> lightIds;
1335
Prabir Pradhan51894782022-08-23 16:29:10 +00001336 for (const auto& [id, info] : getLightInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001337 lightIds.push_back(id);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001338 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001339
Chris Ye3fdbfef2021-01-06 18:45:18 -08001340 return lightIds;
1341}
1342
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001343std::optional<RawLightInfo> EventHub::getRawLightInfo(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001344 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001345
Chris Yee2b1e5c2021-03-10 22:45:12 -08001346 const auto infos = getLightInfoLocked(deviceId);
1347
1348 auto it = infos.find(lightId);
1349 if (it != infos.end()) {
1350 return it->second;
Chris Ye3fdbfef2021-01-06 18:45:18 -08001351 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001352
Chris Ye3fdbfef2021-01-06 18:45:18 -08001353 return std::nullopt;
1354}
1355
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001356std::optional<int32_t> EventHub::getLightBrightness(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001357 std::scoped_lock _l(mLock);
1358
Chris Yee2b1e5c2021-03-10 22:45:12 -08001359 const auto infos = getLightInfoLocked(deviceId);
1360 auto it = infos.find(lightId);
1361 if (it == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001362 return std::nullopt;
1363 }
1364 std::string buffer;
1365 if (!base::ReadFileToString(it->second.path / LIGHT_NODES.at(InputLightClass::BRIGHTNESS),
1366 &buffer)) {
1367 return std::nullopt;
1368 }
1369 return std::stoi(buffer);
1370}
1371
1372std::optional<std::unordered_map<LightColor, int32_t>> EventHub::getLightIntensities(
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001373 int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001374 std::scoped_lock _l(mLock);
1375
Chris Yee2b1e5c2021-03-10 22:45:12 -08001376 const auto infos = getLightInfoLocked(deviceId);
1377 auto lightIt = infos.find(lightId);
1378 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001379 return std::nullopt;
1380 }
1381
1382 auto ret =
1383 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1384
1385 if (!ret.has_value()) {
1386 return std::nullopt;
1387 }
1388 std::array<LightColor, COLOR_NUM> colors = ret.value();
1389
1390 std::string intensityStr;
1391 if (!base::ReadFileToString(lightIt->second.path /
1392 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY),
1393 &intensityStr)) {
1394 return std::nullopt;
1395 }
1396
1397 // Intensity node outputs 3 color values
1398 std::regex intensityPattern("([0-9]+)\\s([0-9]+)\\s([0-9]+)[\\n]");
1399 std::smatch results;
1400
1401 if (!std::regex_match(intensityStr, results, intensityPattern)) {
1402 return std::nullopt;
1403 }
1404 std::unordered_map<LightColor, int32_t> intensities;
1405 for (size_t i = 1; i < results.size(); i++) {
1406 int value = std::stoi(results[i].str());
1407 intensities.emplace(colors[i - 1], value);
1408 }
1409 return intensities;
1410}
1411
1412void EventHub::setLightBrightness(int32_t deviceId, int32_t lightId, int32_t brightness) {
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()) {
1418 ALOGE("%s lightId %d not found ", __func__, lightId);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001419 return;
1420 }
1421
1422 if (!base::WriteStringToFile(std::to_string(brightness),
1423 lightIt->second.path /
1424 LIGHT_NODES.at(InputLightClass::BRIGHTNESS))) {
1425 ALOGE("Can not write to file, error: %s", strerror(errno));
1426 }
1427}
1428
1429void EventHub::setLightIntensities(int32_t deviceId, int32_t lightId,
1430 std::unordered_map<LightColor, int32_t> intensities) {
1431 std::scoped_lock _l(mLock);
1432
Chris Yee2b1e5c2021-03-10 22:45:12 -08001433 const auto infos = getLightInfoLocked(deviceId);
1434 auto lightIt = infos.find(lightId);
1435 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001436 ALOGE("Light Id %d does not exist.", lightId);
1437 return;
1438 }
1439
1440 auto ret =
1441 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1442
1443 if (!ret.has_value()) {
1444 return;
1445 }
1446 std::array<LightColor, COLOR_NUM> colors = ret.value();
1447
1448 std::string rgbStr;
1449 for (size_t i = 0; i < COLOR_NUM; i++) {
1450 auto it = intensities.find(colors[i]);
1451 if (it != intensities.end()) {
1452 rgbStr += std::to_string(it->second);
1453 // Insert space between colors
1454 if (i < COLOR_NUM - 1) {
1455 rgbStr += " ";
1456 }
1457 }
1458 }
1459 // Append new line
1460 rgbStr += "\n";
1461
1462 if (!base::WriteStringToFile(rgbStr,
1463 lightIt->second.path /
1464 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY))) {
1465 ALOGE("Can not write to file, error: %s", strerror(errno));
1466 }
1467}
1468
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001469std::optional<RawLayoutInfo> EventHub::getRawLayoutInfo(int32_t deviceId) const {
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001470 std::scoped_lock _l(mLock);
1471 Device* device = getDeviceLocked(deviceId);
1472 if (device == nullptr || !device->associatedDevice) {
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001473 return std::nullopt;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001474 }
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001475 return device->associatedDevice->layoutInfo;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001476}
1477
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001478void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Chris Ye87143712020-11-10 05:05:58 +00001479 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480
1481 mExcludedDevices = devices;
1482}
1483
1484bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) 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);
Chris Ye66fbac32020-07-06 20:36:43 -07001487 if (device != nullptr && scanCode >= 0 && scanCode <= KEY_MAX) {
1488 return device->keyBitmask.test(scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001489 }
1490 return false;
1491}
1492
Arthur Hungcb40a002021-08-03 14:31:01 +00001493bool EventHub::hasKeyCode(int32_t deviceId, int32_t keyCode) const {
1494 std::scoped_lock _l(mLock);
1495 Device* device = getDeviceLocked(deviceId);
1496 if (device != nullptr) {
1497 return device->hasKeycodeLocked(keyCode);
1498 }
1499 return false;
1500}
1501
Michael Wrightd02c5b62014-02-10 15:10:22 -08001502bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
Chris Ye87143712020-11-10 05:05:58 +00001503 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001504 Device* device = getDeviceLocked(deviceId);
1505 int32_t sc;
Chris Ye989bb932020-07-04 16:18:59 -07001506 if (device != nullptr && device->mapLed(led, &sc) == NO_ERROR) {
Chris Ye66fbac32020-07-06 20:36:43 -07001507 return device->ledBitmask.test(sc);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001508 }
1509 return false;
1510}
1511
1512void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
Chris Ye87143712020-11-10 05:05:58 +00001513 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001514 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -07001515 if (device != nullptr && device->hasValidFd()) {
1516 device->setLedStateLocked(led, on);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001517 }
1518}
1519
1520void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001521 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001522 outVirtualKeys.clear();
1523
Chris Ye87143712020-11-10 05:05:58 +00001524 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001525 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001526 if (device != nullptr && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001527 const std::vector<VirtualKeyDefinition> virtualKeys =
1528 device->virtualKeyMap->getVirtualKeys();
1529 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001530 }
1531}
1532
Chris Ye3a1e4462020-08-12 10:13:15 -07001533const std::shared_ptr<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001534 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001535 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001536 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001537 return device->getKeyCharacterMap();
1538 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001539 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001540}
1541
Vaibhav Devmurari23e8ae92022-12-29 12:07:56 +00001542// If provided map is null, it will reset key character map to default KCM.
Chris Ye3a1e4462020-08-12 10:13:15 -07001543bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, std::shared_ptr<KeyCharacterMap> map) {
Chris Ye87143712020-11-10 05:05:58 +00001544 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001545 Device* device = getDeviceLocked(deviceId);
Vaibhav Devmurari23e8ae92022-12-29 12:07:56 +00001546 if (device == nullptr || device->keyMap.keyCharacterMap == nullptr) {
Philip Junker90bc9492021-12-10 18:39:42 +01001547 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001548 }
Vaibhav Devmurari23e8ae92022-12-29 12:07:56 +00001549 if (map == nullptr) {
1550 device->keyMap.keyCharacterMap->clearLayoutOverlay();
1551 return true;
1552 }
Philip Junker90bc9492021-12-10 18:39:42 +01001553 device->keyMap.keyCharacterMap->combine(*map);
1554 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001555}
1556
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001557static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
1558 std::string rawDescriptor;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001559 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001560 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001561 if (!identifier.uniqueId.empty()) {
1562 rawDescriptor += "uniqueId:";
1563 rawDescriptor += identifier.uniqueId;
Josh Bartel938632f2022-07-19 15:34:22 -05001564 }
1565 if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001566 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001567 }
1568
1569 if (identifier.vendor == 0 && identifier.product == 0) {
1570 // If we don't know the vendor and product id, then the device is probably
1571 // built-in so we need to rely on other information to uniquely identify
1572 // the input device. Usually we try to avoid relying on the device name or
1573 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001574 if (!identifier.name.empty()) {
1575 rawDescriptor += "name:";
1576 rawDescriptor += identifier.name;
1577 } else if (!identifier.location.empty()) {
1578 rawDescriptor += "location:";
1579 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001580 }
1581 }
1582 identifier.descriptor = sha1(rawDescriptor);
1583 return rawDescriptor;
1584}
1585
1586void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
1587 // Compute a device descriptor that uniquely identifies the device.
1588 // The descriptor is assumed to be a stable identifier. Its value should not
1589 // change between reboots, reconnections, firmware updates or new releases
1590 // of Android. In practice we sometimes get devices that cannot be uniquely
1591 // identified. In this case we enforce uniqueness between connected devices.
1592 // Ideally, we also want the descriptor to be short and relatively opaque.
Josh Bartel938632f2022-07-19 15:34:22 -05001593 // Note that we explicitly do not use the path or location for external devices
1594 // as their path or location will change as they are plugged/unplugged or moved
1595 // to different ports. We do fallback to using name and location in the case of
1596 // internal devices which are detected by the vendor and product being 0 in
1597 // generateDescriptor. If two identical descriptors are detected we will fallback
1598 // to using a 'nonce' and incrementing it until the new descriptor no longer has
1599 // a match with any existing descriptors.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001600
1601 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001602 std::string rawDescriptor = generateDescriptor(identifier);
Josh Bartel938632f2022-07-19 15:34:22 -05001603 // Enforce that the generated descriptor is unique.
1604 while (hasDeviceWithDescriptorLocked(identifier.descriptor)) {
1605 identifier.nonce++;
1606 rawDescriptor = generateDescriptor(identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001607 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001608 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001609 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001610}
1611
Prabir Pradhancb42b472022-08-23 16:01:19 +00001612std::shared_ptr<const EventHub::AssociatedDevice> EventHub::obtainAssociatedDeviceLocked(
1613 const std::filesystem::path& devicePath) const {
1614 const std::optional<std::filesystem::path> sysfsRootPathOpt =
1615 getSysfsRootPath(devicePath.c_str());
1616 if (!sysfsRootPathOpt) {
1617 return nullptr;
1618 }
1619
1620 const auto& path = *sysfsRootPathOpt;
Prabir Pradhancb42b472022-08-23 16:01:19 +00001621
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00001622 std::shared_ptr<const AssociatedDevice> associatedDevice = std::make_shared<AssociatedDevice>(
Prabir Pradhancb42b472022-08-23 16:01:19 +00001623 AssociatedDevice{.sysfsRootPath = path,
1624 .batteryInfos = readBatteryConfiguration(path),
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001625 .lightInfos = readLightsConfiguration(path),
1626 .layoutInfo = readLayoutConfiguration(path)});
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00001627
1628 bool associatedDeviceChanged = false;
1629 for (const auto& [id, dev] : mDevices) {
1630 if (dev->associatedDevice && dev->associatedDevice->sysfsRootPath == path) {
1631 if (*associatedDevice != *dev->associatedDevice) {
1632 associatedDeviceChanged = true;
1633 dev->associatedDevice = associatedDevice;
1634 }
1635 associatedDevice = dev->associatedDevice;
1636 }
1637 }
1638 ALOGI_IF(associatedDeviceChanged,
1639 "The AssociatedDevice changed for path '%s'. Using new AssociatedDevice: %s",
1640 path.c_str(), associatedDevice->dump().c_str());
1641
1642 return associatedDevice;
Prabir Pradhancb42b472022-08-23 16:01:19 +00001643}
1644
Vaibhav Devmurari5fc7d852023-03-17 18:43:33 +00001645bool EventHub::AssociatedDevice::isChanged() const {
1646 std::unordered_map<int32_t, RawBatteryInfo> newBatteryInfos =
1647 readBatteryConfiguration(sysfsRootPath);
1648 std::unordered_map<int32_t, RawLightInfo> newLightInfos =
1649 readLightsConfiguration(sysfsRootPath);
1650 std::optional<RawLayoutInfo> newLayoutInfo = readLayoutConfiguration(sysfsRootPath);
1651
1652 if (newBatteryInfos == batteryInfos && newLightInfos == lightInfos &&
1653 newLayoutInfo == layoutInfo) {
1654 return false;
1655 }
1656 return true;
1657}
1658
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001659void EventHub::vibrate(int32_t deviceId, const VibrationElement& element) {
Chris Ye87143712020-11-10 05:05:58 +00001660 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001661 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001662 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001663 ff_effect effect;
1664 memset(&effect, 0, sizeof(effect));
1665 effect.type = FF_RUMBLE;
1666 effect.id = device->ffEffectId;
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001667 // evdev FF_RUMBLE effect only supports two channels of vibration.
Chris Ye6393a262020-08-04 19:41:36 -07001668 effect.u.rumble.strong_magnitude = element.getMagnitude(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1669 effect.u.rumble.weak_magnitude = element.getMagnitude(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001670 effect.replay.length = element.duration.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001671 effect.replay.delay = 0;
1672 if (ioctl(device->fd, EVIOCSFF, &effect)) {
1673 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001674 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001675 return;
1676 }
1677 device->ffEffectId = effect.id;
1678
1679 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -07001680 ev.input_event_sec = 0;
1681 ev.input_event_usec = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001682 ev.type = EV_FF;
1683 ev.code = device->ffEffectId;
1684 ev.value = 1;
1685 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1686 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001687 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001688 return;
1689 }
1690 device->ffEffectPlaying = true;
1691 }
1692}
1693
1694void EventHub::cancelVibrate(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001695 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001696 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001697 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001698 if (device->ffEffectPlaying) {
1699 device->ffEffectPlaying = false;
1700
1701 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -07001702 ev.input_event_sec = 0;
1703 ev.input_event_usec = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001704 ev.type = EV_FF;
1705 ev.code = device->ffEffectId;
1706 ev.value = 0;
1707 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1708 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001709 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001710 return;
1711 }
1712 }
1713 }
1714}
1715
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001716std::vector<int32_t> EventHub::getVibratorIds(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001717 std::scoped_lock _l(mLock);
1718 std::vector<int32_t> vibrators;
1719 Device* device = getDeviceLocked(deviceId);
1720 if (device != nullptr && device->hasValidFd() &&
1721 device->classes.test(InputDeviceClass::VIBRATOR)) {
1722 vibrators.push_back(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1723 vibrators.push_back(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
1724 }
1725 return vibrators;
1726}
1727
Josh Bartel938632f2022-07-19 15:34:22 -05001728/**
1729 * Checks both mDevices and mOpeningDevices for a device with the descriptor passed.
1730 */
1731bool EventHub::hasDeviceWithDescriptorLocked(const std::string& descriptor) const {
1732 for (const auto& device : mOpeningDevices) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001733 if (descriptor == device->identifier.descriptor) {
Josh Bartel938632f2022-07-19 15:34:22 -05001734 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001735 }
1736 }
Josh Bartel938632f2022-07-19 15:34:22 -05001737
1738 for (const auto& [id, device] : mDevices) {
1739 if (descriptor == device->identifier.descriptor) {
1740 return true;
1741 }
1742 }
1743 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001744}
1745
1746EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001747 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001748 deviceId = mBuiltInKeyboardId;
1749 }
Chris Ye989bb932020-07-04 16:18:59 -07001750 const auto& it = mDevices.find(deviceId);
1751 return it != mDevices.end() ? it->second.get() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001752}
1753
Chris Ye8594e192020-07-14 10:34:06 -07001754EventHub::Device* EventHub::getDeviceByPathLocked(const std::string& devicePath) const {
Chris Ye989bb932020-07-04 16:18:59 -07001755 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001756 if (device->path == devicePath) {
Chris Ye989bb932020-07-04 16:18:59 -07001757 return device.get();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001758 }
1759 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001760 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001761}
1762
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001763/**
1764 * The file descriptor could be either input device, or a video device (associated with a
1765 * specific input device). Check both cases here, and return the device that this event
1766 * belongs to. Caller can compare the fd's once more to determine event type.
1767 * Looks through all input devices, and only attached video devices. Unattached video
1768 * devices are ignored.
1769 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001770EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
Chris Ye989bb932020-07-04 16:18:59 -07001771 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001772 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001773 // This is an input device event
Chris Ye989bb932020-07-04 16:18:59 -07001774 return device.get();
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001775 }
1776 if (device->videoDevice && device->videoDevice->getFd() == fd) {
1777 // This is a video device event
Chris Ye989bb932020-07-04 16:18:59 -07001778 return device.get();
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001779 }
1780 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001781 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
1782 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001783 return nullptr;
1784}
1785
Chris Yee2b1e5c2021-03-10 22:45:12 -08001786std::optional<int32_t> EventHub::getBatteryCapacity(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001787 std::filesystem::path batteryPath;
1788 {
1789 // Do not read the sysfs node to get the battery state while holding
1790 // the EventHub lock. For some peripheral devices, reading battery state
1791 // can be broken and take 5+ seconds. Holding the lock in this case would
1792 // block all other event processing during this time. For now, we assume this
1793 // call never happens on the InputReader thread and read the sysfs node outside
1794 // the lock to prevent event processing from being blocked by this call.
1795 std::scoped_lock _l(mLock);
Kim Low03ea0352020-11-06 12:45:07 -08001796
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001797 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001798 auto it = infos.find(batteryId);
1799 if (it == infos.end()) {
1800 return std::nullopt;
1801 }
1802 batteryPath = it->second.path;
1803 } // release lock
1804
Chris Yee2b1e5c2021-03-10 22:45:12 -08001805 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001806
1807 // Some devices report battery capacity as an integer through the "capacity" file
Andy Chenf9f1a022022-08-29 20:07:10 -04001808 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001809 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001810 return std::stoi(base::Trim(buffer));
Kim Low03ea0352020-11-06 12:45:07 -08001811 }
1812
1813 // Other devices report capacity as an enum value POWER_SUPPLY_CAPACITY_LEVEL_XXX
1814 // These values are taken from kernel source code include/linux/power_supply.h
Andy Chenf9f1a022022-08-29 20:07:10 -04001815 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY_LEVEL),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001816 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001817 // Remove any white space such as trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001818 const auto levelIt = BATTERY_LEVEL.find(base::Trim(buffer));
1819 if (levelIt != BATTERY_LEVEL.end()) {
1820 return levelIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001821 }
1822 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001823
Kim Low03ea0352020-11-06 12:45:07 -08001824 return std::nullopt;
1825}
1826
Chris Yee2b1e5c2021-03-10 22:45:12 -08001827std::optional<int32_t> EventHub::getBatteryStatus(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001828 std::filesystem::path batteryPath;
1829 {
1830 // Do not read the sysfs node to get the battery state while holding
1831 // the EventHub lock. For some peripheral devices, reading battery state
1832 // can be broken and take 5+ seconds. Holding the lock in this case would
1833 // block all other event processing during this time. For now, we assume this
1834 // call never happens on the InputReader thread and read the sysfs node outside
1835 // the lock to prevent event processing from being blocked by this call.
1836 std::scoped_lock _l(mLock);
1837
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001838 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001839 auto it = infos.find(batteryId);
1840 if (it == infos.end()) {
1841 return std::nullopt;
1842 }
1843 batteryPath = it->second.path;
1844 } // release lock
1845
Chris Yee2b1e5c2021-03-10 22:45:12 -08001846 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001847
Andy Chenf9f1a022022-08-29 20:07:10 -04001848 if (!base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::STATUS),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001849 &buffer)) {
Kim Low03ea0352020-11-06 12:45:07 -08001850 ALOGE("Failed to read sysfs battery info: %s", strerror(errno));
1851 return std::nullopt;
1852 }
1853
Chris Yed1936772021-02-22 10:30:40 -08001854 // Remove white space like trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001855 const auto statusIt = BATTERY_STATUS.find(base::Trim(buffer));
1856 if (statusIt != BATTERY_STATUS.end()) {
1857 return statusIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001858 }
1859
1860 return std::nullopt;
1861}
1862
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001863std::vector<RawEvent> EventHub::getEvents(int timeoutMillis) {
Chris Ye87143712020-11-10 05:05:58 +00001864 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001865
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001866 std::array<input_event, EVENT_BUFFER_SIZE> readBuffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001867
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001868 std::vector<RawEvent> events;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001869 bool awoken = false;
1870 for (;;) {
1871 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
1872
1873 // Reopen input devices if needed.
1874 if (mNeedToReopenDevices) {
1875 mNeedToReopenDevices = false;
1876
1877 ALOGI("Reopening all input devices due to a configuration change.");
1878
1879 closeAllDevicesLocked();
1880 mNeedToScanDevices = true;
1881 break; // return to the caller before we actually rescan
1882 }
1883
1884 // Report any devices that had last been added/removed.
Chris Ye989bb932020-07-04 16:18:59 -07001885 for (auto it = mClosingDevices.begin(); it != mClosingDevices.end();) {
1886 std::unique_ptr<Device> device = std::move(*it);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001887 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001888 const int32_t deviceId = (device->id == mBuiltInKeyboardId)
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001889 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
1890 : device->id;
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001891 events.push_back({
1892 .when = now,
1893 .deviceId = deviceId,
1894 .type = DEVICE_REMOVED,
1895 });
Chris Ye989bb932020-07-04 16:18:59 -07001896 it = mClosingDevices.erase(it);
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001897 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001898 break;
1899 }
1900 }
1901
1902 if (mNeedToScanDevices) {
1903 mNeedToScanDevices = false;
1904 scanDevicesLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001905 }
1906
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001907 while (!mOpeningDevices.empty()) {
1908 std::unique_ptr<Device> device = std::move(*mOpeningDevices.rbegin());
1909 mOpeningDevices.pop_back();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001910 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001911 const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1912 events.push_back({
1913 .when = now,
1914 .deviceId = deviceId,
1915 .type = DEVICE_ADDED,
1916 });
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001917
1918 // Try to find a matching video device by comparing device names
1919 for (auto it = mUnattachedVideoDevices.begin(); it != mUnattachedVideoDevices.end();
1920 it++) {
1921 std::unique_ptr<TouchVideoDevice>& videoDevice = *it;
Chris Yed3fef462021-03-07 17:10:08 -08001922 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001923 // videoDevice was transferred to 'device'
1924 it = mUnattachedVideoDevices.erase(it);
1925 break;
1926 }
1927 }
1928
1929 auto [dev_it, inserted] = mDevices.insert_or_assign(device->id, std::move(device));
1930 if (!inserted) {
Chris Ye989bb932020-07-04 16:18:59 -07001931 ALOGW("Device id %d exists, replaced.", device->id);
1932 }
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001933 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001934 break;
1935 }
1936 }
1937
1938 // Grab the next input event.
1939 bool deviceChanged = false;
1940 while (mPendingEventIndex < mPendingEventCount) {
1941 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001942 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001943 if (eventItem.events & EPOLLIN) {
1944 mPendingINotify = true;
1945 } else {
1946 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
1947 }
1948 continue;
1949 }
1950
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001951 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001952 if (eventItem.events & EPOLLIN) {
1953 ALOGV("awoken after wake()");
1954 awoken = true;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001955 char wakeReadBuffer[16];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001956 ssize_t nRead;
1957 do {
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001958 nRead = read(mWakeReadPipeFd, wakeReadBuffer, sizeof(wakeReadBuffer));
1959 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(wakeReadBuffer));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001960 } else {
1961 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001962 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001963 }
1964 continue;
1965 }
1966
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001967 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Chris Ye989bb932020-07-04 16:18:59 -07001968 if (device == nullptr) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001969 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
1970 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001971 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001972 continue;
1973 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001974 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
1975 if (eventItem.events & EPOLLIN) {
1976 size_t numFrames = device->videoDevice->readAndQueueFrames();
1977 if (numFrames == 0) {
1978 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001979 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001980 }
1981 } else if (eventItem.events & EPOLLHUP) {
1982 // TODO(b/121395353) - consider adding EPOLLRDHUP
1983 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001984 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001985 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1986 device->videoDevice = nullptr;
1987 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001988 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1989 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001990 ALOG_ASSERT(!DEBUG);
1991 }
1992 continue;
1993 }
1994 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -08001995 if (eventItem.events & EPOLLIN) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001996 int32_t readSize =
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001997 read(device->fd, readBuffer.data(),
1998 sizeof(decltype(readBuffer)::value_type) * readBuffer.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001999 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
2000 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -07002001 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07002002 " capacity: %zu errno: %d)\n",
2003 device->fd, readSize, readBuffer.size(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002004 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07002005 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002006 } else if (readSize < 0) {
2007 if (errno != EAGAIN && errno != EINTR) {
2008 ALOGW("could not get event (errno=%d)", errno);
2009 }
2010 } else if ((readSize % sizeof(struct input_event)) != 0) {
2011 ALOGE("could not get event (wrong size: %d)", readSize);
2012 } else {
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002013 const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002014
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002015 const size_t count = size_t(readSize) / sizeof(struct input_event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002016 for (size_t i = 0; i < count; i++) {
2017 struct input_event& iev = readBuffer[i];
Prabir Pradhan9762ac92023-07-13 21:45:12 +00002018 device->trackInputEvent(iev);
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002019 events.push_back({
2020 .when = processEventTimestamp(iev),
2021 .readTime = systemTime(SYSTEM_TIME_MONOTONIC),
2022 .deviceId = deviceId,
2023 .type = iev.type,
2024 .code = iev.code,
2025 .value = iev.value,
2026 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08002027 }
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07002028 if (events.size() >= EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002029 // The result buffer is full. Reset the pending event index
2030 // so we will try to read the device again on the next iteration.
2031 mPendingEventIndex -= 1;
2032 break;
2033 }
2034 }
2035 } else if (eventItem.events & EPOLLHUP) {
2036 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002037 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002038 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07002039 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002040 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002041 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
2042 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002043 }
2044 }
2045
2046 // readNotify() will modify the list of devices so this must be done after
2047 // processing all other events to ensure that we read all remaining events
2048 // before closing the devices.
2049 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
2050 mPendingINotify = false;
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002051 const auto res = readNotifyLocked();
2052 if (!res.ok()) {
2053 ALOGW("Failed to read from inotify: %s", res.error().message().c_str());
2054 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002055 deviceChanged = true;
2056 }
2057
2058 // Report added or removed devices immediately.
2059 if (deviceChanged) {
2060 continue;
2061 }
2062
2063 // Return now if we have collected any events or if we were explicitly awoken.
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002064 if (!events.empty() || awoken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002065 break;
2066 }
2067
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01002068 // Poll for events.
2069 // When a device driver has pending (unread) events, it acquires
2070 // a kernel wake lock. Once the last pending event has been read, the device
2071 // driver will release the kernel wake lock, but the epoll will hold the wakelock,
2072 // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
2073 // is called again for the same fd that produced the event.
2074 // Thus the system can only sleep if there are no events pending or
2075 // currently being processed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002076 //
2077 // The timeout is advisory only. If the device is asleep, it will not wake just to
2078 // service the timeout.
2079 mPendingEventIndex = 0;
2080
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01002081 mLock.unlock(); // release lock before poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08002082
2083 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
2084
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01002085 mLock.lock(); // reacquire lock after poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08002086
2087 if (pollResult == 0) {
2088 // Timed out.
2089 mPendingEventCount = 0;
2090 break;
2091 }
2092
2093 if (pollResult < 0) {
2094 // An error occurred.
2095 mPendingEventCount = 0;
2096
2097 // Sleep after errors to avoid locking up the system.
2098 // Hopefully the error is transient.
2099 if (errno != EINTR) {
2100 ALOGW("poll failed (errno=%d)\n", errno);
2101 usleep(100000);
2102 }
2103 } else {
2104 // Some events occurred.
2105 mPendingEventCount = size_t(pollResult);
2106 }
2107 }
2108
2109 // All done, return the number of events we read.
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002110 return events;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002111}
2112
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08002113std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002114 std::scoped_lock _l(mLock);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08002115
2116 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07002117 if (device == nullptr || !device->videoDevice) {
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08002118 return {};
2119 }
2120 return device->videoDevice->consumeFrames();
2121}
2122
Michael Wrightd02c5b62014-02-10 15:10:22 -08002123void EventHub::wake() {
2124 ALOGV("wake() called");
2125
2126 ssize_t nWrite;
2127 do {
2128 nWrite = write(mWakeWritePipeFd, "W", 1);
2129 } while (nWrite == -1 && errno == EINTR);
2130
2131 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002132 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002133 }
2134}
2135
2136void EventHub::scanDevicesLocked() {
Usama Arifb27c8e62021-06-03 16:44:09 +01002137 status_t result;
2138 std::error_code errorCode;
2139
2140 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
2141 result = scanDirLocked(DEVICE_INPUT_PATH);
2142 if (result < 0) {
2143 ALOGE("scan dir failed for %s", DEVICE_INPUT_PATH);
2144 }
2145 } else {
2146 if (errorCode) {
2147 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
2148 errorCode.message().c_str());
2149 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002150 }
Philip Quinn39b81682019-01-09 22:20:39 -08002151 if (isV4lScanningEnabled()) {
Usama Arifb27c8e62021-06-03 16:44:09 +01002152 result = scanVideoDirLocked(DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08002153 if (result != OK) {
Usama Arifb27c8e62021-06-03 16:44:09 +01002154 ALOGE("scan video dir failed for %s", DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08002155 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002156 }
Chris Ye989bb932020-07-04 16:18:59 -07002157 if (mDevices.find(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) == mDevices.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002158 createVirtualKeyboardLocked();
2159 }
2160}
2161
2162// ----------------------------------------------------------------------------
2163
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002164status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002165 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002166 struct epoll_event eventItem = {};
2167 eventItem.events = EPOLLIN | EPOLLWAKEUP;
2168 eventItem.data.fd = fd;
2169 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
2170 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002171 return -errno;
2172 }
2173 return OK;
2174}
2175
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002176status_t EventHub::unregisterFdFromEpoll(int fd) {
2177 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
2178 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
2179 return -errno;
2180 }
2181 return OK;
2182}
2183
Chris Ye989bb932020-07-04 16:18:59 -07002184status_t EventHub::registerDeviceForEpollLocked(Device& device) {
2185 status_t result = registerFdForEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002186 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07002187 ALOGE("Could not add input device fd to epoll for device %" PRId32, device.id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002188 return result;
2189 }
Chris Ye989bb932020-07-04 16:18:59 -07002190 if (device.videoDevice) {
2191 registerVideoDeviceForEpollLocked(*device.videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002192 }
2193 return result;
2194}
2195
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002196void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
2197 status_t result = registerFdForEpoll(videoDevice.getFd());
2198 if (result != OK) {
2199 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
2200 }
2201}
2202
Chris Ye989bb932020-07-04 16:18:59 -07002203status_t EventHub::unregisterDeviceFromEpollLocked(Device& device) {
2204 if (device.hasValidFd()) {
2205 status_t result = unregisterFdFromEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002206 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07002207 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device.id);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002208 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002209 }
2210 }
Chris Ye989bb932020-07-04 16:18:59 -07002211 if (device.videoDevice) {
2212 unregisterVideoDeviceFromEpollLocked(*device.videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002213 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002214 return OK;
2215}
2216
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002217void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
2218 if (videoDevice.hasValidFd()) {
2219 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
2220 if (result != OK) {
2221 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002222 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002223 }
2224 }
2225}
2226
Chris Yed3fef462021-03-07 17:10:08 -08002227void EventHub::reportDeviceAddedForStatisticsLocked(const InputDeviceIdentifier& identifier,
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002228 ftl::Flags<InputDeviceClass> classes) {
Chris Ye657c2f02021-05-25 16:24:37 -07002229 SHA256_CTX ctx;
2230 SHA256_Init(&ctx);
2231 SHA256_Update(&ctx, reinterpret_cast<const uint8_t*>(identifier.uniqueId.c_str()),
2232 identifier.uniqueId.size());
2233 std::array<uint8_t, SHA256_DIGEST_LENGTH> digest;
2234 SHA256_Final(digest.data(), &ctx);
2235
2236 std::string obfuscatedId;
2237 for (size_t i = 0; i < OBFUSCATED_LENGTH; i++) {
2238 obfuscatedId += StringPrintf("%02x", digest[i]);
2239 }
2240
Chris Yed3fef462021-03-07 17:10:08 -08002241 android::util::stats_write(android::util::INPUTDEVICE_REGISTERED, identifier.name.c_str(),
2242 identifier.vendor, identifier.product, identifier.version,
Chris Ye657c2f02021-05-25 16:24:37 -07002243 identifier.bus, obfuscatedId.c_str(), classes.get());
Chris Yed3fef462021-03-07 17:10:08 -08002244}
2245
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002246void EventHub::openDeviceLocked(const std::string& devicePath) {
2247 // If an input device happens to register around the time when EventHub's constructor runs, it
2248 // is possible that the same input event node (for example, /dev/input/event3) will be noticed
2249 // in both 'inotify' callback and also in the 'scanDirLocked' pass. To prevent duplicate devices
2250 // from getting registered, ensure that this path is not already covered by an existing device.
2251 for (const auto& [deviceId, device] : mDevices) {
2252 if (device->path == devicePath) {
2253 return; // device was already registered
2254 }
2255 }
2256
Michael Wrightd02c5b62014-02-10 15:10:22 -08002257 char buffer[80];
2258
Chris Ye8594e192020-07-14 10:34:06 -07002259 ALOGV("Opening device: %s", devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002260
Chris Ye8594e192020-07-14 10:34:06 -07002261 int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002262 if (fd < 0) {
Chris Ye8594e192020-07-14 10:34:06 -07002263 ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002264 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002265 }
2266
2267 InputDeviceIdentifier identifier;
2268
2269 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002270 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Chris Ye8594e192020-07-14 10:34:06 -07002271 ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002272 } else {
2273 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002274 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002275 }
2276
2277 // Check to see if the device is on our excluded list
2278 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002279 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002280 if (identifier.name == item) {
Chris Ye8594e192020-07-14 10:34:06 -07002281 ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002282 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002283 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002284 }
2285 }
2286
2287 // Get device driver version.
2288 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002289 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Chris Ye8594e192020-07-14 10:34:06 -07002290 ALOGE("could not get driver version for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002291 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002292 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002293 }
2294
2295 // Get device identifier.
2296 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002297 if (ioctl(fd, EVIOCGID, &inputId)) {
Chris Ye8594e192020-07-14 10:34:06 -07002298 ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002299 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002300 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002301 }
2302 identifier.bus = inputId.bustype;
2303 identifier.product = inputId.product;
2304 identifier.vendor = inputId.vendor;
2305 identifier.version = inputId.version;
2306
2307 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002308 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
2309 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002310 } else {
2311 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002312 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002313 }
2314
2315 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002316 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
2317 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002318 } else {
2319 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002320 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002321 }
2322
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002323 // Attempt to get the bluetooth address of an input device from the uniqueId.
2324 if (identifier.bus == BUS_BLUETOOTH &&
2325 std::regex_match(identifier.uniqueId,
2326 std::regex("^[A-Fa-f0-9]{2}(?::[A-Fa-f0-9]{2}){5}$"))) {
2327 identifier.bluetoothAddress = identifier.uniqueId;
2328 // The Bluetooth stack requires alphabetic characters to be uppercase in a valid address.
2329 for (auto& c : *identifier.bluetoothAddress) {
2330 c = ::toupper(c);
2331 }
2332 }
2333
Michael Wrightd02c5b62014-02-10 15:10:22 -08002334 // Fill in the descriptor.
2335 assignDescriptorLocked(identifier);
2336
Michael Wrightd02c5b62014-02-10 15:10:22 -08002337 // Allocate device. (The device object takes ownership of the fd at this point.)
2338 int32_t deviceId = mNextDeviceId++;
Prabir Pradhancb42b472022-08-23 16:01:19 +00002339 std::unique_ptr<Device> device =
2340 std::make_unique<Device>(fd, deviceId, devicePath, identifier,
2341 obtainAssociatedDeviceLocked(devicePath));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002342
Chris Ye8594e192020-07-14 10:34:06 -07002343 ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002344 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002345 " vendor %04x\n"
2346 " product %04x\n"
2347 " version %04x\n",
2348 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002349 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
2350 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
2351 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
2352 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002353 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
2354 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002355
2356 // Load the configuration file for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002357 device->loadConfigurationLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002358
2359 // Figure out the kinds of events the device reports.
Chris Ye66fbac32020-07-06 20:36:43 -07002360 device->readDeviceBitMask(EVIOCGBIT(EV_KEY, 0), device->keyBitmask);
2361 device->readDeviceBitMask(EVIOCGBIT(EV_ABS, 0), device->absBitmask);
2362 device->readDeviceBitMask(EVIOCGBIT(EV_REL, 0), device->relBitmask);
2363 device->readDeviceBitMask(EVIOCGBIT(EV_SW, 0), device->swBitmask);
2364 device->readDeviceBitMask(EVIOCGBIT(EV_LED, 0), device->ledBitmask);
2365 device->readDeviceBitMask(EVIOCGBIT(EV_FF, 0), device->ffBitmask);
Chris Yef59a2f42020-10-16 12:55:26 -07002366 device->readDeviceBitMask(EVIOCGBIT(EV_MSC, 0), device->mscBitmask);
Chris Ye66fbac32020-07-06 20:36:43 -07002367 device->readDeviceBitMask(EVIOCGPROP(0), device->propBitmask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002368
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002369 // See if this is a device with keys. This could be full keyboard, or other devices like
2370 // gamepads, joysticks, and styluses with buttons that should generate key presses.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002371 bool haveKeyboardKeys =
Chris Ye66fbac32020-07-06 20:36:43 -07002372 device->keyBitmask.any(0, BTN_MISC) || device->keyBitmask.any(BTN_WHEEL, KEY_MAX + 1);
2373 bool haveGamepadButtons = device->keyBitmask.any(BTN_MISC, BTN_MOUSE) ||
2374 device->keyBitmask.any(BTN_JOYSTICK, BTN_DIGI);
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002375 bool haveStylusButtons = device->keyBitmask.test(BTN_STYLUS) ||
2376 device->keyBitmask.test(BTN_STYLUS2) || device->keyBitmask.test(BTN_STYLUS3);
2377 if (haveKeyboardKeys || haveGamepadButtons || haveStylusButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002378 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002379 }
2380
2381 // See if this is a cursor device such as a trackball or mouse.
Chris Ye66fbac32020-07-06 20:36:43 -07002382 if (device->keyBitmask.test(BTN_MOUSE) && device->relBitmask.test(REL_X) &&
2383 device->relBitmask.test(REL_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002384 device->classes |= InputDeviceClass::CURSOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002385 }
2386
Prabir Pradhana3621852022-10-14 18:57:23 +00002387 // See if the device is specially configured to be of a certain type.
Harry Cuttsf13161a2023-03-08 14:15:49 +00002388 if (device->configuration) {
2389 std::string deviceType = device->configuration->getString("device.type").value_or("");
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07002390 if (deviceType == "rotaryEncoder") {
Chris Ye1b0c7342020-07-28 21:57:03 -07002391 device->classes |= InputDeviceClass::ROTARY_ENCODER;
Prabir Pradhana3621852022-10-14 18:57:23 +00002392 } else if (deviceType == "externalStylus") {
2393 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002394 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002395 }
2396
Michael Wrightd02c5b62014-02-10 15:10:22 -08002397 // See if this is a touch pad.
2398 // Is this a new modern multi-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002399 if (device->absBitmask.test(ABS_MT_POSITION_X) && device->absBitmask.test(ABS_MT_POSITION_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002400 // Some joysticks such as the PS3 controller report axes that conflict
2401 // with the ABS_MT range. Try to confirm that the device really is
2402 // a touch screen.
Chris Ye66fbac32020-07-06 20:36:43 -07002403 if (device->keyBitmask.test(BTN_TOUCH) || !haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002404 device->classes |= (InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT);
Harry Cutts79cc9fa2022-10-28 15:32:39 +00002405 if (device->propBitmask.test(INPUT_PROP_POINTER) &&
2406 !device->keyBitmask.any(BTN_TOOL_PEN, BTN_TOOL_FINGER) && !haveStylusButtons) {
2407 device->classes |= InputDeviceClass::TOUCHPAD;
2408 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002409 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002410 // Is this an old style single-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002411 } else if (device->keyBitmask.test(BTN_TOUCH) && device->absBitmask.test(ABS_X) &&
2412 device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002413 device->classes |= InputDeviceClass::TOUCH;
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002414 // Is this a stylus that reports contact/pressure independently of touch coordinates?
Chris Ye66fbac32020-07-06 20:36:43 -07002415 } else if ((device->absBitmask.test(ABS_PRESSURE) || device->keyBitmask.test(BTN_TOUCH)) &&
2416 !device->absBitmask.test(ABS_X) && !device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002417 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002418 }
2419
2420 // See if this device is a joystick.
2421 // Assumes that joysticks always have gamepad buttons in order to distinguish them
2422 // from other devices such as accelerometers that also have absolute axes.
2423 if (haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002424 auto assumedClasses = device->classes | InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002425 for (int i = 0; i <= ABS_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002426 if (device->absBitmask.test(i) &&
Chris Ye1b0c7342020-07-28 21:57:03 -07002427 (getAbsAxisUsage(i, assumedClasses).test(InputDeviceClass::JOYSTICK))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002428 device->classes = assumedClasses;
2429 break;
2430 }
2431 }
2432 }
2433
Chris Yef59a2f42020-10-16 12:55:26 -07002434 // Check whether this device is an accelerometer.
2435 if (device->propBitmask.test(INPUT_PROP_ACCELEROMETER)) {
2436 device->classes |= InputDeviceClass::SENSOR;
2437 }
2438
Michael Wrightd02c5b62014-02-10 15:10:22 -08002439 // Check whether this device has switches.
2440 for (int i = 0; i <= SW_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002441 if (device->swBitmask.test(i)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002442 device->classes |= InputDeviceClass::SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002443 break;
2444 }
2445 }
2446
2447 // Check whether this device supports the vibrator.
Chris Ye66fbac32020-07-06 20:36:43 -07002448 if (device->ffBitmask.test(FF_RUMBLE)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002449 device->classes |= InputDeviceClass::VIBRATOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002450 }
2451
2452 // Configure virtual keys.
Chris Ye1b0c7342020-07-28 21:57:03 -07002453 if ((device->classes.test(InputDeviceClass::TOUCH))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002454 // Load the virtual keys for the touch screen, if any.
2455 // We do this now so that we can make sure to load the keymap if necessary.
Chris Ye989bb932020-07-04 16:18:59 -07002456 bool success = device->loadVirtualKeyMapLocked();
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06002457 if (success) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002458 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002459 }
2460 }
2461
2462 // Load the key map.
Chris Yef59a2f42020-10-16 12:55:26 -07002463 // We need to do this for joysticks too because the key layout may specify axes, and for
2464 // sensor as well because the key layout may specify the axes to sensor data mapping.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002465 status_t keyMapStatus = NAME_NOT_FOUND;
Chris Yef59a2f42020-10-16 12:55:26 -07002466 if (device->classes.any(InputDeviceClass::KEYBOARD | InputDeviceClass::JOYSTICK |
2467 InputDeviceClass::SENSOR)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002468 // Load the keymap for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002469 keyMapStatus = device->loadKeyMapLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002470 }
2471
2472 // Configure the keyboard, gamepad or virtual keyboard.
Chris Ye1b0c7342020-07-28 21:57:03 -07002473 if (device->classes.test(InputDeviceClass::KEYBOARD)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002474 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002475 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002476 isEligibleBuiltInKeyboard(device->identifier, device->configuration.get(),
2477 &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002478 mBuiltInKeyboardId = device->id;
2479 }
2480
2481 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
Chris Ye989bb932020-07-04 16:18:59 -07002482 if (device->hasKeycodeLocked(AKEYCODE_Q)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002483 device->classes |= InputDeviceClass::ALPHAKEY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002484 }
2485
Prabir Pradhanae10ee62023-05-12 19:44:18 +00002486 // See if this device has a D-pad.
2487 if (std::all_of(DPAD_REQUIRED_KEYCODES.begin(), DPAD_REQUIRED_KEYCODES.end(),
2488 [&](int32_t keycode) { return device->hasKeycodeLocked(keycode); })) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002489 device->classes |= InputDeviceClass::DPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002490 }
2491
2492 // See if this device has a gamepad.
Prabir Pradhanae10ee62023-05-12 19:44:18 +00002493 if (std::any_of(GAMEPAD_KEYCODES.begin(), GAMEPAD_KEYCODES.end(),
2494 [&](int32_t keycode) { return device->hasKeycodeLocked(keycode); })) {
2495 device->classes |= InputDeviceClass::GAMEPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002496 }
Prabir Pradhana3621852022-10-14 18:57:23 +00002497
2498 // See if this device has any stylus buttons that we would want to fuse with touch data.
Prabir Pradhanae10ee62023-05-12 19:44:18 +00002499 if (!device->classes.any(InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT) &&
Prabir Pradhan3c28b942023-08-18 20:02:01 +00002500 !device->classes.any(InputDeviceClass::ALPHAKEY) &&
Prabir Pradhanae10ee62023-05-12 19:44:18 +00002501 std::any_of(STYLUS_BUTTON_KEYCODES.begin(), STYLUS_BUTTON_KEYCODES.end(),
2502 [&](int32_t keycode) { return device->hasKeycodeLocked(keycode); })) {
2503 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Prabir Pradhana3621852022-10-14 18:57:23 +00002504 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002505 }
2506
Vladimir Komsiyskidd438e22024-02-13 11:47:54 +01002507 // See if the device is a rotary encoder with a single scroll axis and nothing else.
2508 if (vd_flags::virtual_rotary() && device->classes == ftl::Flags<InputDeviceClass>(0) &&
2509 device->relBitmask.test(REL_WHEEL) && !device->relBitmask.test(REL_HWHEEL)) {
2510 device->classes |= InputDeviceClass::ROTARY_ENCODER;
2511 }
2512
Michael Wrightd02c5b62014-02-10 15:10:22 -08002513 // If the device isn't recognized as something we handle, don't monitor it.
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002514 if (device->classes == ftl::Flags<InputDeviceClass>(0)) {
Chris Ye8594e192020-07-14 10:34:06 -07002515 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002516 device->identifier.name.c_str());
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002517 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002518 }
2519
Chris Ye3fdbfef2021-01-06 18:45:18 -08002520 // Classify InputDeviceClass::BATTERY.
Prabir Pradhan51894782022-08-23 16:29:10 +00002521 if (device->associatedDevice && !device->associatedDevice->batteryInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002522 device->classes |= InputDeviceClass::BATTERY;
2523 }
Kim Low03ea0352020-11-06 12:45:07 -08002524
Chris Ye3fdbfef2021-01-06 18:45:18 -08002525 // Classify InputDeviceClass::LIGHT.
Prabir Pradhan51894782022-08-23 16:29:10 +00002526 if (device->associatedDevice && !device->associatedDevice->lightInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002527 device->classes |= InputDeviceClass::LIGHT;
Kim Low03ea0352020-11-06 12:45:07 -08002528 }
2529
Tim Kilbourn063ff532015-04-08 10:26:18 -07002530 // Determine whether the device has a mic.
Chris Ye989bb932020-07-04 16:18:59 -07002531 if (device->deviceHasMicLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002532 device->classes |= InputDeviceClass::MIC;
Tim Kilbourn063ff532015-04-08 10:26:18 -07002533 }
2534
Michael Wrightd02c5b62014-02-10 15:10:22 -08002535 // Determine whether the device is external or internal.
Chris Ye989bb932020-07-04 16:18:59 -07002536 if (device->isExternalDeviceLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002537 device->classes |= InputDeviceClass::EXTERNAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002538 }
2539
Chris Ye1b0c7342020-07-28 21:57:03 -07002540 if (device->classes.any(InputDeviceClass::JOYSTICK | InputDeviceClass::DPAD) &&
2541 device->classes.test(InputDeviceClass::GAMEPAD)) {
Chris Ye989bb932020-07-04 16:18:59 -07002542 device->controllerNumber = getNextControllerNumberLocked(device->identifier.name);
2543 device->setLedForControllerLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002544 }
2545
Chris Ye989bb932020-07-04 16:18:59 -07002546 if (registerDeviceForEpollLocked(*device) != OK) {
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002547 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002548 }
2549
Chris Ye989bb932020-07-04 16:18:59 -07002550 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002551
Chris Ye1b0c7342020-07-28 21:57:03 -07002552 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=%s, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002553 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Chris Ye1b0c7342020-07-28 21:57:03 -07002554 deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(),
2555 device->classes.string().c_str(), device->configurationFile.c_str(),
2556 device->keyMap.keyLayoutFile.c_str(), device->keyMap.keyCharacterMapFile.c_str(),
2557 toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002558
Chris Ye989bb932020-07-04 16:18:59 -07002559 addDeviceLocked(std::move(device));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002560}
2561
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002562void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
2563 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
2564 if (!videoDevice) {
2565 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
2566 return;
2567 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002568 // Transfer ownership of this video device to a matching input device
Chris Ye989bb932020-07-04 16:18:59 -07002569 for (const auto& [id, device] : mDevices) {
Chris Yed3fef462021-03-07 17:10:08 -08002570 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002571 return; // 'device' now owns 'videoDevice'
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002572 }
2573 }
2574
2575 // Couldn't find a matching input device, so just add it to a temporary holding queue.
2576 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002577 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002578 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002579 mUnattachedVideoDevices.push_back(std::move(videoDevice));
2580}
2581
Chris Yed3fef462021-03-07 17:10:08 -08002582bool EventHub::tryAddVideoDeviceLocked(EventHub::Device& device,
2583 std::unique_ptr<TouchVideoDevice>& videoDevice) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002584 if (videoDevice->getName() != device.identifier.name) {
2585 return false;
2586 }
2587 device.videoDevice = std::move(videoDevice);
2588 if (device.enabled) {
2589 registerVideoDeviceForEpollLocked(*device.videoDevice);
2590 }
2591 return true;
2592}
2593
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002594bool EventHub::isDeviceEnabled(int32_t deviceId) const {
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 false;
2600 }
2601 return device->enabled;
2602}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002603
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002604status_t EventHub::enableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002605 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002606 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002607 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002608 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2609 return BAD_VALUE;
2610 }
2611 if (device->enabled) {
2612 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
2613 return OK;
2614 }
2615 status_t result = device->enable();
2616 if (result != OK) {
2617 ALOGE("Failed to enable device %" PRId32, deviceId);
2618 return result;
2619 }
2620
Chris Ye989bb932020-07-04 16:18:59 -07002621 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002622
Chris Ye989bb932020-07-04 16:18:59 -07002623 return registerDeviceForEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002624}
2625
2626status_t EventHub::disableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002627 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002628 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002629 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002630 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2631 return BAD_VALUE;
2632 }
2633 if (!device->enabled) {
2634 ALOGW("Duplicate call to %s, input device already disabled", __func__);
2635 return OK;
2636 }
Chris Ye989bb932020-07-04 16:18:59 -07002637 unregisterDeviceFromEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002638 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002639}
2640
Vaibhav Devmurari5fc7d852023-03-17 18:43:33 +00002641// TODO(b/274755573): Shift to uevent handling on native side and remove this method
2642// Currently using Java UEventObserver to trigger this which uses UEvent infrastructure that uses a
2643// NETLINK socket to observe UEvents. We can create similar infrastructure on Eventhub side to
2644// directly observe UEvents instead of triggering from Java side.
2645void EventHub::sysfsNodeChanged(const std::string& sysfsNodePath) {
2646 std::scoped_lock _l(mLock);
2647
2648 // Check in opening devices
2649 for (auto it = mOpeningDevices.begin(); it != mOpeningDevices.end(); it++) {
2650 std::unique_ptr<Device>& device = *it;
2651 if (device->associatedDevice &&
2652 sysfsNodePath.find(device->associatedDevice->sysfsRootPath.string()) !=
2653 std::string::npos &&
2654 device->associatedDevice->isChanged()) {
2655 it = mOpeningDevices.erase(it);
2656 openDeviceLocked(device->path);
2657 }
2658 }
2659
2660 // Check in already added device
2661 std::vector<Device*> devicesToReopen;
2662 for (const auto& [id, device] : mDevices) {
2663 if (device->associatedDevice &&
2664 sysfsNodePath.find(device->associatedDevice->sysfsRootPath.string()) !=
2665 std::string::npos &&
2666 device->associatedDevice->isChanged()) {
2667 devicesToReopen.push_back(device.get());
2668 }
2669 }
2670 for (const auto& device : devicesToReopen) {
2671 closeDeviceLocked(*device);
2672 openDeviceLocked(device->path);
2673 }
2674 devicesToReopen.clear();
2675}
2676
Michael Wrightd02c5b62014-02-10 15:10:22 -08002677void EventHub::createVirtualKeyboardLocked() {
2678 InputDeviceIdentifier identifier;
2679 identifier.name = "Virtual";
2680 identifier.uniqueId = "<virtual>";
2681 assignDescriptorLocked(identifier);
2682
Chris Ye989bb932020-07-04 16:18:59 -07002683 std::unique_ptr<Device> device =
2684 std::make_unique<Device>(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
Harry Cutts33476232023-01-30 19:57:29 +00002685 identifier, /*associatedDevice=*/nullptr);
Chris Ye1b0c7342020-07-28 21:57:03 -07002686 device->classes = InputDeviceClass::KEYBOARD | InputDeviceClass::ALPHAKEY |
2687 InputDeviceClass::DPAD | InputDeviceClass::VIRTUAL;
Chris Ye989bb932020-07-04 16:18:59 -07002688 device->loadKeyMapLocked();
2689 addDeviceLocked(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002690}
2691
Chris Ye989bb932020-07-04 16:18:59 -07002692void EventHub::addDeviceLocked(std::unique_ptr<Device> device) {
Chris Yed3fef462021-03-07 17:10:08 -08002693 reportDeviceAddedForStatisticsLocked(device->identifier, device->classes);
Chris Ye989bb932020-07-04 16:18:59 -07002694 mOpeningDevices.push_back(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002695}
2696
Chris Ye989bb932020-07-04 16:18:59 -07002697int32_t EventHub::getNextControllerNumberLocked(const std::string& name) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002698 if (mControllerNumbers.isFull()) {
2699 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Chris Ye989bb932020-07-04 16:18:59 -07002700 name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002701 return 0;
2702 }
2703 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
2704 // one
2705 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
2706}
2707
Chris Ye989bb932020-07-04 16:18:59 -07002708void EventHub::releaseControllerNumberLocked(int32_t num) {
2709 if (num > 0) {
2710 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002711 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002712}
2713
Chris Ye8594e192020-07-14 10:34:06 -07002714void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002715 Device* device = getDeviceByPathLocked(devicePath);
Chris Ye989bb932020-07-04 16:18:59 -07002716 if (device != nullptr) {
2717 closeDeviceLocked(*device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002718 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002719 }
Chris Ye8594e192020-07-14 10:34:06 -07002720 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002721}
2722
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002723/**
2724 * Find the video device by filename, and close it.
2725 * The video device is closed by path during an inotify event, where we don't have the
2726 * additional context about the video device fd, or the associated input device.
2727 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002728void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002729 // A video device may be owned by an existing input device, or it may be stored in
2730 // the mUnattachedVideoDevices queue. Check both locations.
Chris Ye989bb932020-07-04 16:18:59 -07002731 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002732 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002733 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002734 device->videoDevice = nullptr;
2735 return;
2736 }
2737 }
Siarhei Vishniakouf47c339e2021-12-30 11:22:26 -08002738 std::erase_if(mUnattachedVideoDevices,
2739 [&devicePath](const std::unique_ptr<TouchVideoDevice>& videoDevice) {
2740 return videoDevice->getPath() == devicePath;
2741 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08002742}
2743
2744void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002745 mUnattachedVideoDevices.clear();
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002746 while (!mDevices.empty()) {
2747 closeDeviceLocked(*(mDevices.begin()->second));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002748 }
2749}
2750
Chris Ye989bb932020-07-04 16:18:59 -07002751void EventHub::closeDeviceLocked(Device& device) {
2752 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=%s", device.path.c_str(),
2753 device.identifier.name.c_str(), device.id, device.fd, device.classes.string().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002754
Chris Ye989bb932020-07-04 16:18:59 -07002755 if (device.id == mBuiltInKeyboardId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002756 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Chris Ye989bb932020-07-04 16:18:59 -07002757 device.path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002758 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
2759 }
2760
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002761 unregisterDeviceFromEpollLocked(device);
Chris Ye989bb932020-07-04 16:18:59 -07002762 if (device.videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002763 // This must be done after the video device is removed from epoll
Chris Ye989bb932020-07-04 16:18:59 -07002764 mUnattachedVideoDevices.push_back(std::move(device.videoDevice));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002765 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002766
Chris Ye989bb932020-07-04 16:18:59 -07002767 releaseControllerNumberLocked(device.controllerNumber);
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002768 device.controllerNumber = 0;
Chris Ye989bb932020-07-04 16:18:59 -07002769 device.close();
Chris Ye989bb932020-07-04 16:18:59 -07002770 mClosingDevices.push_back(std::move(mDevices[device.id]));
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002771
Chris Ye989bb932020-07-04 16:18:59 -07002772 mDevices.erase(device.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002773}
2774
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002775base::Result<void> EventHub::readNotifyLocked() {
2776 static constexpr auto EVENT_SIZE = static_cast<ssize_t>(sizeof(inotify_event));
2777 uint8_t eventBuffer[512];
2778 ssize_t sizeRead;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002779
2780 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002781 do {
2782 sizeRead = read(mINotifyFd, eventBuffer, sizeof(eventBuffer));
2783 } while (sizeRead < 0 && errno == EINTR);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002784
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002785 if (sizeRead < EVENT_SIZE) return Errorf("could not get event, %s", strerror(errno));
2786
2787 for (ssize_t eventPos = 0; sizeRead >= EVENT_SIZE;) {
2788 const inotify_event* event;
2789 event = (const inotify_event*)(eventBuffer + eventPos);
2790 if (event->len == 0) continue;
2791
2792 handleNotifyEventLocked(*event);
2793
2794 const ssize_t eventSize = EVENT_SIZE + event->len;
2795 sizeRead -= eventSize;
2796 eventPos += eventSize;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002797 }
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002798 return {};
2799}
2800
2801void EventHub::handleNotifyEventLocked(const inotify_event& event) {
2802 if (event.wd == mDeviceInputWd) {
2803 std::string filename = std::string(DEVICE_INPUT_PATH) + "/" + event.name;
2804 if (event.mask & IN_CREATE) {
2805 openDeviceLocked(filename);
2806 } else {
2807 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
2808 closeDeviceByPathLocked(filename);
2809 }
2810 } else if (event.wd == mDeviceWd) {
2811 if (isV4lTouchNode(event.name)) {
2812 std::string filename = std::string(DEVICE_PATH) + "/" + event.name;
2813 if (event.mask & IN_CREATE) {
2814 openVideoDeviceLocked(filename);
2815 } else {
2816 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
2817 closeVideoDeviceByPathLocked(filename);
2818 }
2819 } else if (strcmp(event.name, "input") == 0 && event.mask & IN_CREATE) {
2820 addDeviceInputInotify();
2821 }
2822 } else {
2823 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event.wd);
2824 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002825}
2826
Chris Ye8594e192020-07-14 10:34:06 -07002827status_t EventHub::scanDirLocked(const std::string& dirname) {
2828 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2829 openDeviceLocked(entry.path());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002830 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002831 return 0;
2832}
2833
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002834/**
2835 * Look for all dirname/v4l-touch* devices, and open them.
2836 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002837status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Chris Ye8594e192020-07-14 10:34:06 -07002838 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2839 if (isV4lTouchNode(entry.path())) {
2840 ALOGI("Found touch video device %s", entry.path().c_str());
2841 openVideoDeviceLocked(entry.path());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002842 }
2843 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002844 return OK;
2845}
2846
Michael Wrightd02c5b62014-02-10 15:10:22 -08002847void EventHub::requestReopenDevices() {
2848 ALOGV("requestReopenDevices() called");
2849
Chris Ye87143712020-11-10 05:05:58 +00002850 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002851 mNeedToReopenDevices = true;
2852}
2853
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002854void EventHub::dump(std::string& dump) const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002855 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002856
2857 { // acquire lock
Chris Ye87143712020-11-10 05:05:58 +00002858 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002859
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002860 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002861
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002862 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002863
Chris Ye989bb932020-07-04 16:18:59 -07002864 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002865 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002866 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002867 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002868 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002869 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002870 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002871 }
Chris Ye1b0c7342020-07-28 21:57:03 -07002872 dump += StringPrintf(INDENT3 "Classes: %s\n", device->classes.string().c_str());
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002873 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002874 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002875 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
2876 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002877 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002878 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002879 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002880 "product=0x%04x, version=0x%04x, bluetoothAddress=%s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002881 device->identifier.bus, device->identifier.vendor,
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002882 device->identifier.product, device->identifier.version,
2883 toString(device->identifier.bluetoothAddress).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002884 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002885 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002886 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002887 device->keyMap.keyCharacterMapFile.c_str());
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00002888 if (device->associatedDevice && device->associatedDevice->layoutInfo) {
2889 dump += StringPrintf(INDENT3 "LanguageTag: %s\n",
2890 device->associatedDevice->layoutInfo->languageTag.c_str());
2891 dump += StringPrintf(INDENT3 "LayoutType: %s\n",
2892 device->associatedDevice->layoutInfo->layoutType.c_str());
2893 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002894 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002895 device->configurationFile.c_str());
Prabir Pradhan51894782022-08-23 16:29:10 +00002896 dump += StringPrintf(INDENT3 "VideoDevice: %s\n",
2897 device->videoDevice ? device->videoDevice->dump().c_str()
2898 : "<none>");
2899 dump += StringPrintf(INDENT3 "SysfsDevicePath: %s\n",
2900 device->associatedDevice
2901 ? device->associatedDevice->sysfsRootPath.c_str()
2902 : "<none>");
Prabir Pradhan955b6132023-07-14 19:44:34 +00002903 if (device->keyBitmask.any(0, KEY_MAX + 1)) {
2904 const auto pressedKeys = device->keyState.dumpSetIndices(", ", [](int i) {
2905 return InputEventLookup::getLinuxEvdevLabel(EV_KEY, i, 1).code;
2906 });
2907 dump += StringPrintf(INDENT3 "KeyState (pressed): %s\n", pressedKeys.c_str());
2908 }
2909 if (device->swBitmask.any(0, SW_MAX + 1)) {
2910 const auto pressedSwitches = device->swState.dumpSetIndices(", ", [](int i) {
2911 return InputEventLookup::getLinuxEvdevLabel(EV_SW, i, 1).code;
2912 });
2913 dump += StringPrintf(INDENT3 "SwState (pressed): %s\n", pressedSwitches.c_str());
2914 }
2915 if (!device->absState.empty()) {
2916 std::string axisValues;
2917 for (const auto& [axis, state] : device->absState) {
2918 if (!axisValues.empty()) {
2919 axisValues += ", ";
2920 }
2921 axisValues += StringPrintf("%s=%d",
2922 InputEventLookup::getLinuxEvdevLabel(EV_ABS, axis, 0)
2923 .code.c_str(),
2924 state.value);
2925 }
2926 dump += INDENT3 "AbsState: " + axisValues + "\n";
2927 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002928 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002929
2930 dump += INDENT "Unattached video devices:\n";
2931 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
2932 dump += INDENT2 + videoDevice->dump() + "\n";
2933 }
2934 if (mUnattachedVideoDevices.empty()) {
2935 dump += INDENT2 "<none>\n";
2936 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002937 } // release lock
2938}
2939
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002940void EventHub::monitor() const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002941 // Acquire and release the lock to ensure that the event hub has not deadlocked.
Chris Ye1c2e0892020-11-30 21:41:44 -08002942 std::unique_lock<std::mutex> lock(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002943}
2944
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00002945std::string EventHub::AssociatedDevice::dump() const {
2946 return StringPrintf("path=%s, numBatteries=%zu, numLight=%zu", sysfsRootPath.c_str(),
2947 batteryInfos.size(), lightInfos.size());
2948}
2949
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002950} // namespace android