blob: 117b38473552fb7486661f1687df51c9be657b17 [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>
Chris Ye8594e192020-07-14 10:34:06 -070046#include <input/KeyCharacterMap.h>
47#include <input/KeyLayoutMap.h>
Prabir Pradhan07525ef2022-10-03 21:51:26 +000048#include <input/PrintTools.h>
Chris Ye8594e192020-07-14 10:34:06 -070049#include <input/VirtualKeyMap.h>
Dan Albert677d87e2014-06-16 17:31:28 -070050#include <openssl/sha.h>
Chris Yed3fef462021-03-07 17:10:08 -080051#include <statslog.h>
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070052#include <utils/Errors.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080053#include <utils/Log.h>
54#include <utils/Timers.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080055
Chris Ye8594e192020-07-14 10:34:06 -070056#include <filesystem>
Harry Cuttsf13161a2023-03-08 14:15:49 +000057#include <optional>
Chris Ye3fdbfef2021-01-06 18:45:18 -080058#include <regex>
Prabir Pradhancb42b472022-08-23 16:01:19 +000059#include <utility>
Chris Ye8594e192020-07-14 10:34:06 -070060
61#include "EventHub.h"
Michael Wrightd02c5b62014-02-10 15:10:22 -080062
Prabir Pradhanae10ee62023-05-12 19:44:18 +000063#include "KeyCodeClassifications.h"
64
Michael Wrightd02c5b62014-02-10 15:10:22 -080065#define INDENT " "
66#define INDENT2 " "
67#define INDENT3 " "
68
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080069using android::base::StringPrintf;
70
Michael Wrightd02c5b62014-02-10 15:10:22 -080071namespace android {
72
Vladimir Komsiyskidd438e22024-02-13 11:47:54 +010073namespace vd_flags = android::companion::virtualdevice::flags;
74
Dominik Laskowski2f01d772022-03-23 16:01:29 -070075using namespace ftl::flag_operators;
76
Usama Arifb27c8e62021-06-03 16:44:09 +010077static const char* DEVICE_INPUT_PATH = "/dev/input";
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080078// v4l2 devices go directly into /dev
Usama Arifb27c8e62021-06-03 16:44:09 +010079static const char* DEVICE_PATH = "/dev";
Michael Wrightd02c5b62014-02-10 15:10:22 -080080
Chris Ye657c2f02021-05-25 16:24:37 -070081static constexpr size_t OBFUSCATED_LENGTH = 8;
82
Chris Ye87143712020-11-10 05:05:58 +000083static constexpr int32_t FF_STRONG_MAGNITUDE_CHANNEL_IDX = 0;
84static constexpr int32_t FF_WEAK_MAGNITUDE_CHANNEL_IDX = 1;
Chris Ye6393a262020-08-04 19:41:36 -070085
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -070086static constexpr size_t EVENT_BUFFER_SIZE = 256;
87
Chris Yee2b1e5c2021-03-10 22:45:12 -080088// Mapping for input battery class node IDs lookup.
89// https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
90static const std::unordered_map<std::string, InputBatteryClass> BATTERY_CLASSES =
91 {{"capacity", InputBatteryClass::CAPACITY},
92 {"capacity_level", InputBatteryClass::CAPACITY_LEVEL},
93 {"status", InputBatteryClass::STATUS}};
94
95// Mapping for input battery class node names lookup.
96// https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
97static const std::unordered_map<InputBatteryClass, std::string> BATTERY_NODES =
98 {{InputBatteryClass::CAPACITY, "capacity"},
99 {InputBatteryClass::CAPACITY_LEVEL, "capacity_level"},
100 {InputBatteryClass::STATUS, "status"}};
101
Kim Low03ea0352020-11-06 12:45:07 -0800102// must be kept in sync with definitions in kernel /drivers/power/supply/power_supply_sysfs.c
103static const std::unordered_map<std::string, int32_t> BATTERY_STATUS =
104 {{"Unknown", BATTERY_STATUS_UNKNOWN},
105 {"Charging", BATTERY_STATUS_CHARGING},
106 {"Discharging", BATTERY_STATUS_DISCHARGING},
107 {"Not charging", BATTERY_STATUS_NOT_CHARGING},
108 {"Full", BATTERY_STATUS_FULL}};
109
110// Mapping taken from
111// https://gitlab.freedesktop.org/upower/upower/-/blob/master/src/linux/up-device-supply.c#L484
112static const std::unordered_map<std::string, int32_t> BATTERY_LEVEL = {{"Critical", 5},
113 {"Low", 10},
114 {"Normal", 55},
115 {"High", 70},
116 {"Full", 100},
117 {"Unknown", 50}};
118
Chris Ye3fdbfef2021-01-06 18:45:18 -0800119// Mapping for input led class node names lookup.
120// https://www.kernel.org/doc/html/latest/leds/leds-class.html
121static const std::unordered_map<std::string, InputLightClass> LIGHT_CLASSES =
122 {{"red", InputLightClass::RED},
123 {"green", InputLightClass::GREEN},
124 {"blue", InputLightClass::BLUE},
125 {"global", InputLightClass::GLOBAL},
126 {"brightness", InputLightClass::BRIGHTNESS},
127 {"multi_index", InputLightClass::MULTI_INDEX},
128 {"multi_intensity", InputLightClass::MULTI_INTENSITY},
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000129 {"max_brightness", InputLightClass::MAX_BRIGHTNESS},
DingYong99f2c3c2023-12-20 15:46:06 +0800130 {"kbd_backlight", InputLightClass::KEYBOARD_BACKLIGHT},
131 {"mic_mute", InputLightClass::KEYBOARD_MIC_MUTE}};
Chris Ye3fdbfef2021-01-06 18:45:18 -0800132
133// Mapping for input multicolor led class node names.
134// https://www.kernel.org/doc/html/latest/leds/leds-class-multicolor.html
135static const std::unordered_map<InputLightClass, std::string> LIGHT_NODES =
136 {{InputLightClass::BRIGHTNESS, "brightness"},
137 {InputLightClass::MULTI_INDEX, "multi_index"},
138 {InputLightClass::MULTI_INTENSITY, "multi_intensity"}};
139
140// Mapping for light color name and the light color
141const std::unordered_map<std::string, LightColor> LIGHT_COLORS = {{"red", LightColor::RED},
142 {"green", LightColor::GREEN},
143 {"blue", LightColor::BLUE}};
144
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000145// Mapping for country code to Layout info.
146// See bCountryCode in 6.2.1 of https://usb.org/sites/default/files/hid1_11.pdf.
147const std::unordered_map<std::int32_t, RawLayoutInfo> LAYOUT_INFOS =
148 {{0, RawLayoutInfo{.languageTag = "", .layoutType = ""}}, // NOT_SUPPORTED
149 {1, RawLayoutInfo{.languageTag = "ar-Arab", .layoutType = ""}}, // ARABIC
150 {2, RawLayoutInfo{.languageTag = "fr-BE", .layoutType = ""}}, // BELGIAN
151 {3, RawLayoutInfo{.languageTag = "fr-CA", .layoutType = ""}}, // CANADIAN_BILINGUAL
152 {4, RawLayoutInfo{.languageTag = "fr-CA", .layoutType = ""}}, // CANADIAN_FRENCH
153 {5, RawLayoutInfo{.languageTag = "cs", .layoutType = ""}}, // CZECH_REPUBLIC
154 {6, RawLayoutInfo{.languageTag = "da", .layoutType = ""}}, // DANISH
155 {7, RawLayoutInfo{.languageTag = "fi", .layoutType = ""}}, // FINNISH
156 {8, RawLayoutInfo{.languageTag = "fr-FR", .layoutType = ""}}, // FRENCH
157 {9, RawLayoutInfo{.languageTag = "de", .layoutType = ""}}, // GERMAN
158 {10, RawLayoutInfo{.languageTag = "el", .layoutType = ""}}, // GREEK
159 {11, RawLayoutInfo{.languageTag = "iw", .layoutType = ""}}, // HEBREW
160 {12, RawLayoutInfo{.languageTag = "hu", .layoutType = ""}}, // HUNGARY
161 {13, RawLayoutInfo{.languageTag = "en", .layoutType = "extended"}}, // INTERNATIONAL (ISO)
162 {14, RawLayoutInfo{.languageTag = "it", .layoutType = ""}}, // ITALIAN
163 {15, RawLayoutInfo{.languageTag = "ja", .layoutType = ""}}, // JAPAN
164 {16, RawLayoutInfo{.languageTag = "ko", .layoutType = ""}}, // KOREAN
165 {17, RawLayoutInfo{.languageTag = "es-419", .layoutType = ""}}, // LATIN_AMERICA
166 {18, RawLayoutInfo{.languageTag = "nl", .layoutType = ""}}, // DUTCH
167 {19, RawLayoutInfo{.languageTag = "nb", .layoutType = ""}}, // NORWEGIAN
168 {20, RawLayoutInfo{.languageTag = "fa", .layoutType = ""}}, // PERSIAN
169 {21, RawLayoutInfo{.languageTag = "pl", .layoutType = ""}}, // POLAND
170 {22, RawLayoutInfo{.languageTag = "pt", .layoutType = ""}}, // PORTUGUESE
171 {23, RawLayoutInfo{.languageTag = "ru", .layoutType = ""}}, // RUSSIA
172 {24, RawLayoutInfo{.languageTag = "sk", .layoutType = ""}}, // SLOVAKIA
173 {25, RawLayoutInfo{.languageTag = "es-ES", .layoutType = ""}}, // SPANISH
174 {26, RawLayoutInfo{.languageTag = "sv", .layoutType = ""}}, // SWEDISH
175 {27, RawLayoutInfo{.languageTag = "fr-CH", .layoutType = ""}}, // SWISS_FRENCH
176 {28, RawLayoutInfo{.languageTag = "de-CH", .layoutType = ""}}, // SWISS_GERMAN
177 {29, RawLayoutInfo{.languageTag = "de-CH", .layoutType = ""}}, // SWITZERLAND
178 {30, RawLayoutInfo{.languageTag = "zh-TW", .layoutType = ""}}, // TAIWAN
179 {31, RawLayoutInfo{.languageTag = "tr", .layoutType = "turkish_q"}}, // TURKISH_Q
180 {32, RawLayoutInfo{.languageTag = "en-GB", .layoutType = ""}}, // UK
181 {33, RawLayoutInfo{.languageTag = "en-US", .layoutType = ""}}, // US
182 {34, RawLayoutInfo{.languageTag = "", .layoutType = ""}}, // YUGOSLAVIA
183 {35, RawLayoutInfo{.languageTag = "tr", .layoutType = "turkish_f"}}}; // TURKISH_F
184
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100185static std::string sha1(const std::string& in) {
Dan Albert677d87e2014-06-16 17:31:28 -0700186 SHA_CTX ctx;
187 SHA1_Init(&ctx);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100188 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
Dan Albert677d87e2014-06-16 17:31:28 -0700189 u_char digest[SHA_DIGEST_LENGTH];
190 SHA1_Final(digest, &ctx);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800191
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100192 std::string out;
Dan Albert677d87e2014-06-16 17:31:28 -0700193 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100194 out += StringPrintf("%02x", digest[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800195 }
196 return out;
197}
198
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800199/**
200 * Return true if name matches "v4l-touch*"
201 */
Chris Ye8594e192020-07-14 10:34:06 -0700202static bool isV4lTouchNode(std::string name) {
203 return name.find("v4l-touch") != std::string::npos;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800204}
205
Philip Quinn39b81682019-01-09 22:20:39 -0800206/**
207 * Returns true if V4L devices should be scanned.
208 *
209 * The system property ro.input.video_enabled can be used to control whether
210 * EventHub scans and opens V4L devices. As V4L does not support multiple
211 * clients, EventHub effectively blocks access to these devices when it opens
Siarhei Vishniakou29f88492019-04-05 14:11:43 -0700212 * them.
213 *
214 * Setting this to "false" would prevent any video devices from being discovered and
215 * associated with input devices.
216 *
217 * This property can be used as follows:
218 * 1. To turn off features that are dependent on video device presence.
219 * 2. During testing and development, to allow other clients to read video devices
220 * directly from /dev.
Philip Quinn39b81682019-01-09 22:20:39 -0800221 */
222static bool isV4lScanningEnabled() {
Harry Cutts33476232023-01-30 19:57:29 +0000223 return property_get_bool("ro.input.video_enabled", /*default_value=*/true);
Philip Quinn39b81682019-01-09 22:20:39 -0800224}
225
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800226static nsecs_t processEventTimestamp(const struct input_event& event) {
227 // Use the time specified in the event instead of the current time
228 // so that downstream code can get more accurate estimates of
229 // event dispatch latency from the time the event is enqueued onto
230 // the evdev client buffer.
231 //
232 // The event's timestamp fortuitously uses the same monotonic clock
233 // time base as the rest of Android. The kernel event device driver
234 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
235 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
236 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
237 // system call that also queries ktime_get_ts().
238
Colin Cross5b799302022-10-18 21:52:41 -0700239 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.input_event_sec) +
240 microseconds_to_nanoseconds(event.input_event_usec);
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800241 return inputEventTime;
242}
243
Kim Low03ea0352020-11-06 12:45:07 -0800244/**
Prabir Pradhancb42b472022-08-23 16:01:19 +0000245 * Returns the sysfs root path of the input device.
Kim Low03ea0352020-11-06 12:45:07 -0800246 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800247static std::optional<std::filesystem::path> getSysfsRootPath(const char* devicePath) {
Kim Low03ea0352020-11-06 12:45:07 -0800248 std::error_code errorCode;
249
250 // Stat the device path to get the major and minor number of the character file
251 struct stat statbuf;
252 if (stat(devicePath, &statbuf) == -1) {
253 ALOGE("Could not stat device %s due to error: %s.", devicePath, std::strerror(errno));
Chris Ye3fdbfef2021-01-06 18:45:18 -0800254 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800255 }
256
257 unsigned int major_num = major(statbuf.st_rdev);
258 unsigned int minor_num = minor(statbuf.st_rdev);
259
260 // Realpath "/sys/dev/char/{major}:{minor}" to get the sysfs path to the input event
261 auto sysfsPath = std::filesystem::path("/sys/dev/char/");
262 sysfsPath /= std::to_string(major_num) + ":" + std::to_string(minor_num);
263 sysfsPath = std::filesystem::canonical(sysfsPath, errorCode);
264
265 // Make sure nothing went wrong in call to canonical()
266 if (errorCode) {
267 ALOGW("Could not run filesystem::canonical() due to error %d : %s.", errorCode.value(),
268 errorCode.message().c_str());
Chris Ye3fdbfef2021-01-06 18:45:18 -0800269 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800270 }
271
272 // Continue to go up a directory until we reach a directory named "input"
273 while (sysfsPath != "/" && sysfsPath.filename() != "input") {
274 sysfsPath = sysfsPath.parent_path();
275 }
276
277 // Then go up one more and you will be at the sysfs root of the device
278 sysfsPath = sysfsPath.parent_path();
279
280 // Make sure we didn't reach root path and that directory actually exists
281 if (sysfsPath == "/" || !std::filesystem::exists(sysfsPath, errorCode)) {
282 if (errorCode) {
283 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
284 errorCode.message().c_str());
285 }
286
287 // Not found
Chris Ye3fdbfef2021-01-06 18:45:18 -0800288 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800289 }
290
291 return sysfsPath;
292}
293
294/**
Chris Ye3fdbfef2021-01-06 18:45:18 -0800295 * Returns the list of files under a specified path.
Kim Low03ea0352020-11-06 12:45:07 -0800296 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800297static std::vector<std::filesystem::path> allFilesInPath(const std::filesystem::path& path) {
298 std::vector<std::filesystem::path> nodes;
299 std::error_code errorCode;
300 auto iter = std::filesystem::directory_iterator(path, errorCode);
301 while (!errorCode && iter != std::filesystem::directory_iterator()) {
302 nodes.push_back(iter->path());
303 iter++;
304 }
305 return nodes;
306}
307
308/**
309 * Returns the list of files under a specified directory in a sysfs path.
310 * Example:
311 * findSysfsNodes(sysfsRootPath, SysfsClass::LEDS) will return all led nodes under "leds" directory
312 * in the sysfs path.
313 */
314static std::vector<std::filesystem::path> findSysfsNodes(const std::filesystem::path& sysfsRoot,
315 SysfsClass clazz) {
Dominik Laskowski75788452021-02-09 18:51:25 -0800316 std::string nodeStr = ftl::enum_string(clazz);
Chris Ye3fdbfef2021-01-06 18:45:18 -0800317 std::for_each(nodeStr.begin(), nodeStr.end(),
318 [](char& c) { c = std::tolower(static_cast<unsigned char>(c)); });
319 std::vector<std::filesystem::path> nodes;
320 for (auto path = sysfsRoot; path != "/" && nodes.empty(); path = path.parent_path()) {
321 nodes = allFilesInPath(path / nodeStr);
322 }
323 return nodes;
324}
325
326static std::optional<std::array<LightColor, COLOR_NUM>> getColorIndexArray(
327 std::filesystem::path path) {
328 std::string indexStr;
329 if (!base::ReadFileToString(path, &indexStr)) {
330 return std::nullopt;
331 }
332
333 // Parse the multi color LED index file, refer to kernel docs
334 // leds/leds-class-multicolor.html
335 std::regex indexPattern("(red|green|blue)\\s(red|green|blue)\\s(red|green|blue)[\\n]");
336 std::smatch results;
337 std::array<LightColor, COLOR_NUM> colors;
338 if (!std::regex_match(indexStr, results, indexPattern)) {
339 return std::nullopt;
340 }
341
342 for (size_t i = 1; i < results.size(); i++) {
343 const auto it = LIGHT_COLORS.find(results[i].str());
344 if (it != LIGHT_COLORS.end()) {
345 // intensities.emplace(it->second, 0);
346 colors[i - 1] = it->second;
Kim Low03ea0352020-11-06 12:45:07 -0800347 }
348 }
Chris Ye3fdbfef2021-01-06 18:45:18 -0800349 return colors;
Kim Low03ea0352020-11-06 12:45:07 -0800350}
351
Prabir Pradhancb42b472022-08-23 16:01:19 +0000352/**
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000353 * Read country code information exposed through the sysfs path and convert it to Layout info.
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000354 */
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000355static std::optional<RawLayoutInfo> readLayoutConfiguration(
356 const std::filesystem::path& sysfsRootPath) {
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000357 // Check the sysfs root path
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000358 int32_t hidCountryCode = -1;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000359 std::string str;
360 if (base::ReadFileToString(sysfsRootPath / "country", &str)) {
361 hidCountryCode = std::stoi(str, nullptr, 16);
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000362 // Update this condition if new supported country codes are added to HID spec.
Vaibhav Devmurari990ff7b2022-12-22 18:23:21 +0000363 if (hidCountryCode > 35 || hidCountryCode < 0) {
364 ALOGE("HID country code should be in range [0, 35], but for sysfs path %s it was %d",
365 sysfsRootPath.c_str(), hidCountryCode);
Vaibhav Devmurari990ff7b2022-12-22 18:23:21 +0000366 }
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000367 }
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000368 const auto it = LAYOUT_INFOS.find(hidCountryCode);
369 if (it != LAYOUT_INFOS.end()) {
370 return it->second;
371 }
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000372
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000373 return std::nullopt;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000374}
375
376/**
Prabir Pradhancb42b472022-08-23 16:01:19 +0000377 * Read information about batteries exposed through the sysfs path.
378 */
379static std::unordered_map<int32_t /*batteryId*/, RawBatteryInfo> readBatteryConfiguration(
380 const std::filesystem::path& sysfsRootPath) {
381 std::unordered_map<int32_t, RawBatteryInfo> batteryInfos;
382 int32_t nextBatteryId = 0;
383 // Check if device has any battery.
384 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::POWER_SUPPLY);
385 for (const auto& nodePath : paths) {
386 RawBatteryInfo info;
387 info.id = ++nextBatteryId;
388 info.path = nodePath;
389 info.name = nodePath.filename();
390
391 // Scan the path for all the files
392 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
393 const auto& files = allFilesInPath(nodePath);
394 for (const auto& file : files) {
395 const auto it = BATTERY_CLASSES.find(file.filename().string());
396 if (it != BATTERY_CLASSES.end()) {
397 info.flags |= it->second;
398 }
399 }
400 batteryInfos.insert_or_assign(info.id, info);
401 ALOGD("configureBatteryLocked rawBatteryId %d name %s", info.id, info.name.c_str());
402 }
403 return batteryInfos;
404}
405
406/**
407 * Read information about lights exposed through the sysfs path.
408 */
409static std::unordered_map<int32_t /*lightId*/, RawLightInfo> readLightsConfiguration(
410 const std::filesystem::path& sysfsRootPath) {
411 std::unordered_map<int32_t, RawLightInfo> lightInfos;
412 int32_t nextLightId = 0;
413 // Check if device has any lights.
414 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::LEDS);
415 for (const auto& nodePath : paths) {
416 RawLightInfo info;
417 info.id = ++nextLightId;
418 info.path = nodePath;
419 info.name = nodePath.filename();
420 info.maxBrightness = std::nullopt;
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000421
422 // Light name should follow the naming pattern <name>:<color>:<function>
423 // Refer kernel docs /leds/leds-class.html for valid supported LED names.
424 std::regex indexPattern("([a-zA-Z0-9_.:]*:)?([a-zA-Z0-9_.]*):([a-zA-Z0-9_.]*)");
425 std::smatch results;
426
427 if (std::regex_match(info.name, results, indexPattern)) {
428 // regex_match will return full match at index 0 and <name> at index 1. For RawLightInfo
429 // we only care about sections <color> and <function> which will be at index 2 and 3.
430 for (int i = 2; i <= 3; i++) {
431 const auto it = LIGHT_CLASSES.find(results.str(i));
432 if (it != LIGHT_CLASSES.end()) {
433 info.flags |= it->second;
434 }
Prabir Pradhancb42b472022-08-23 16:01:19 +0000435 }
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000436
437 // Set name of the raw light to <function> which represents playerIDs for LEDs that
438 // turn on/off based on the current player ID (Refer to PeripheralController.cpp for
439 // player ID logic)
440 info.name = results.str(3);
Prabir Pradhancb42b472022-08-23 16:01:19 +0000441 }
442 // Scan the path for all the files
443 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
444 const auto& files = allFilesInPath(nodePath);
445 for (const auto& file : files) {
446 const auto it = LIGHT_CLASSES.find(file.filename().string());
447 if (it != LIGHT_CLASSES.end()) {
448 info.flags |= it->second;
449 // If the node has maximum brightness, read it
450 if (it->second == InputLightClass::MAX_BRIGHTNESS) {
451 std::string str;
452 if (base::ReadFileToString(file, &str)) {
453 info.maxBrightness = std::stoi(str);
454 }
455 }
456 }
457 }
458 lightInfos.insert_or_assign(info.id, info);
459 ALOGD("configureLightsLocked rawLightId %d name %s", info.id, info.name.c_str());
460 }
461 return lightInfos;
462}
463
Michael Wrightd02c5b62014-02-10 15:10:22 -0800464// --- Global Functions ---
465
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700466ftl::Flags<InputDeviceClass> getAbsAxisUsage(int32_t axis,
467 ftl::Flags<InputDeviceClass> deviceClasses) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800468 // Touch devices get dibs on touch-related axes.
Chris Ye1b0c7342020-07-28 21:57:03 -0700469 if (deviceClasses.test(InputDeviceClass::TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800470 switch (axis) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700471 case ABS_X:
472 case ABS_Y:
473 case ABS_PRESSURE:
474 case ABS_TOOL_WIDTH:
475 case ABS_DISTANCE:
476 case ABS_TILT_X:
477 case ABS_TILT_Y:
478 case ABS_MT_SLOT:
479 case ABS_MT_TOUCH_MAJOR:
480 case ABS_MT_TOUCH_MINOR:
481 case ABS_MT_WIDTH_MAJOR:
482 case ABS_MT_WIDTH_MINOR:
483 case ABS_MT_ORIENTATION:
484 case ABS_MT_POSITION_X:
485 case ABS_MT_POSITION_Y:
486 case ABS_MT_TOOL_TYPE:
487 case ABS_MT_BLOB_ID:
488 case ABS_MT_TRACKING_ID:
489 case ABS_MT_PRESSURE:
490 case ABS_MT_DISTANCE:
Chris Ye1b0c7342020-07-28 21:57:03 -0700491 return InputDeviceClass::TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800492 }
493 }
494
Chris Yef59a2f42020-10-16 12:55:26 -0700495 if (deviceClasses.test(InputDeviceClass::SENSOR)) {
496 switch (axis) {
497 case ABS_X:
498 case ABS_Y:
499 case ABS_Z:
500 case ABS_RX:
501 case ABS_RY:
502 case ABS_RZ:
503 return InputDeviceClass::SENSOR;
504 }
505 }
506
Michael Wright842500e2015-03-13 17:32:02 -0700507 // External stylus gets the pressure axis
Chris Ye1b0c7342020-07-28 21:57:03 -0700508 if (deviceClasses.test(InputDeviceClass::EXTERNAL_STYLUS)) {
Michael Wright842500e2015-03-13 17:32:02 -0700509 if (axis == ABS_PRESSURE) {
Chris Ye1b0c7342020-07-28 21:57:03 -0700510 return InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -0700511 }
512 }
513
Michael Wrightd02c5b62014-02-10 15:10:22 -0800514 // Joystick devices get the rest.
Chris Ye1b0c7342020-07-28 21:57:03 -0700515 return deviceClasses & InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800516}
517
Harry Cuttsea73eaa2023-01-16 17:55:46 +0000518// --- RawAbsoluteAxisInfo ---
519
Prabir Pradhan132f21c2024-07-25 16:48:30 +0000520std::ostream& operator<<(std::ostream& out, const std::optional<RawAbsoluteAxisInfo>& info) {
521 if (info) {
522 out << "min=" << info->minValue << ", max=" << info->maxValue << ", flat=" << info->flat
523 << ", fuzz=" << info->fuzz << ", resolution=" << info->resolution;
Harry Cuttsea73eaa2023-01-16 17:55:46 +0000524 } else {
525 out << "unknown range";
526 }
527 return out;
528}
529
Michael Wrightd02c5b62014-02-10 15:10:22 -0800530// --- EventHub::Device ---
531
Prabir Pradhancb42b472022-08-23 16:01:19 +0000532EventHub::Device::Device(int fd, int32_t id, std::string path, InputDeviceIdentifier identifier,
533 std::shared_ptr<const AssociatedDevice> assocDev)
Chris Ye989bb932020-07-04 16:18:59 -0700534 : fd(fd),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700535 id(id),
Prabir Pradhancb42b472022-08-23 16:01:19 +0000536 path(std::move(path)),
537 identifier(std::move(identifier)),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700538 classes(0),
539 configuration(nullptr),
540 virtualKeyMap(nullptr),
541 ffEffectPlaying(false),
542 ffEffectId(-1),
Prabir Pradhancb42b472022-08-23 16:01:19 +0000543 associatedDevice(std::move(assocDev)),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700544 controllerNumber(0),
545 enabled(true),
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000546 isVirtual(fd < 0),
547 currentFrameDropped(false) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800548
549EventHub::Device::~Device() {
550 close();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800551}
552
553void EventHub::Device::close() {
554 if (fd >= 0) {
555 ::close(fd);
556 fd = -1;
557 }
558}
559
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700560status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100561 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700562 if (fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100563 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700564 return -errno;
565 }
566 enabled = true;
567 return OK;
568}
569
570status_t EventHub::Device::disable() {
571 close();
572 enabled = false;
573 return OK;
574}
575
Chris Ye989bb932020-07-04 16:18:59 -0700576bool EventHub::Device::hasValidFd() const {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700577 return !isVirtual && enabled;
578}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800579
Chris Ye3a1e4462020-08-12 10:13:15 -0700580const std::shared_ptr<KeyCharacterMap> EventHub::Device::getKeyCharacterMap() const {
Chris Ye989bb932020-07-04 16:18:59 -0700581 return keyMap.keyCharacterMap;
582}
583
584template <std::size_t N>
585status_t EventHub::Device::readDeviceBitMask(unsigned long ioctlCode, BitArray<N>& bitArray) {
586 if (!hasValidFd()) {
587 return BAD_VALUE;
588 }
589 if ((_IOC_SIZE(ioctlCode) == 0)) {
590 ioctlCode |= _IOC(0, 0, 0, bitArray.bytes());
591 }
592
593 typename BitArray<N>::Buffer buffer;
594 status_t ret = ioctl(fd, ioctlCode, buffer.data());
595 bitArray.loadFromBuffer(buffer);
596 return ret;
597}
598
599void EventHub::Device::configureFd() {
600 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
601 if (classes.test(InputDeviceClass::KEYBOARD)) {
602 // Disable kernel key repeat since we handle it ourselves
603 unsigned int repeatRate[] = {0, 0};
604 if (ioctl(fd, EVIOCSREP, repeatRate)) {
605 ALOGW("Unable to disable kernel key repeat for %s: %s", path.c_str(), strerror(errno));
606 }
607 }
608
609 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
610 // associated with input events. This is important because the input system
611 // uses the timestamps extensively and assumes they were recorded using the monotonic
612 // clock.
613 int clockId = CLOCK_MONOTONIC;
Chris Yef59a2f42020-10-16 12:55:26 -0700614 if (classes.test(InputDeviceClass::SENSOR)) {
615 // Each new sensor event should use the same time base as
616 // SystemClock.elapsedRealtimeNanos().
617 clockId = CLOCK_BOOTTIME;
618 }
Chris Ye989bb932020-07-04 16:18:59 -0700619 bool usingClockIoctl = !ioctl(fd, EVIOCSCLOCKID, &clockId);
620 ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000621
622 // Query the initial state of keys and switches, which is tracked by EventHub.
623 readDeviceState();
624}
625
626void EventHub::Device::readDeviceState() {
627 if (readDeviceBitMask(EVIOCGKEY(0), keyState) < 0) {
628 ALOGD("Unable to query the global key state for %s: %s", path.c_str(), strerror(errno));
629 }
630 if (readDeviceBitMask(EVIOCGSW(0), swState) < 0) {
631 ALOGD("Unable to query the global switch state for %s: %s", path.c_str(), strerror(errno));
632 }
Prabir Pradhan341d0782023-07-14 19:04:10 +0000633
634 // Read absolute axis info and values for all available axes for the device.
635 populateAbsoluteAxisStates();
636}
637
638void EventHub::Device::populateAbsoluteAxisStates() {
639 absState.clear();
640
641 for (int axis = 0; axis <= ABS_MAX; axis++) {
642 if (!absBitmask.test(axis)) {
643 continue;
644 }
645 struct input_absinfo info {};
646 if (ioctl(fd, EVIOCGABS(axis), &info)) {
647 ALOGE("Error reading absolute controller %d for device %s fd %d: %s", axis,
648 identifier.name.c_str(), fd, strerror(errno));
649 continue;
650 }
Prabir Pradhan341d0782023-07-14 19:04:10 +0000651 auto& [axisInfo, value] = absState[axis];
Prabir Pradhan341d0782023-07-14 19:04:10 +0000652 axisInfo.minValue = info.minimum;
653 axisInfo.maxValue = info.maximum;
654 axisInfo.flat = info.flat;
655 axisInfo.fuzz = info.fuzz;
656 axisInfo.resolution = info.resolution;
657 value = info.value;
658 }
Chris Ye989bb932020-07-04 16:18:59 -0700659}
660
661bool EventHub::Device::hasKeycodeLocked(int keycode) const {
Vaibhav Devmurari5a71e882024-09-30 15:54:41 +0000662 if (hasKeycodeInternalLocked(keycode)) {
663 return true;
664 }
Rishi Sikka8cb62fe2024-10-10 11:31:18 +0000665 // Check the key character map first. Not all input devices will have one.
666 const std::shared_ptr<KeyCharacterMap> kcm = getKeyCharacterMap();
667 if (kcm == nullptr) {
668 return false;
669 }
670 for (auto& fromKey : kcm->findKeyCodesMappedToKeyCode(keycode)) {
Vaibhav Devmurari5a71e882024-09-30 15:54:41 +0000671 if (hasKeycodeInternalLocked(fromKey)) {
672 return true;
673 }
674 }
675 return false;
676}
677
678bool EventHub::Device::hasKeycodeInternalLocked(int keycode) const {
Chris Ye989bb932020-07-04 16:18:59 -0700679 if (!keyMap.haveKeyLayout()) {
680 return false;
681 }
682
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700683 std::vector<int32_t> scanCodes = keyMap.keyLayoutMap->findScanCodesForKey(keycode);
Chris Ye989bb932020-07-04 16:18:59 -0700684 const size_t N = scanCodes.size();
685 for (size_t i = 0; i < N && i <= KEY_MAX; i++) {
686 int32_t sc = scanCodes[i];
687 if (sc >= 0 && sc <= KEY_MAX && keyBitmask.test(sc)) {
688 return true;
689 }
690 }
691
Charles Linaadf8d52023-03-30 13:34:54 +0800692 std::vector<int32_t> usageCodes = keyMap.keyLayoutMap->findUsageCodesForKey(keycode);
693 if (usageCodes.size() > 0 && mscBitmask.test(MSC_SCAN)) {
694 return true;
695 }
Chris Ye989bb932020-07-04 16:18:59 -0700696 return false;
697}
698
699void EventHub::Device::loadConfigurationLocked() {
700 configurationFile =
701 getInputDeviceConfigurationFilePathByDeviceIdentifier(identifier,
702 InputDeviceConfigurationFileType::
703 CONFIGURATION);
704 if (configurationFile.empty()) {
705 ALOGD("No input device configuration file found for device '%s'.", identifier.name.c_str());
706 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500707 android::base::Result<std::unique_ptr<PropertyMap>> propertyMap =
708 PropertyMap::load(configurationFile.c_str());
709 if (!propertyMap.ok()) {
Chris Ye989bb932020-07-04 16:18:59 -0700710 ALOGE("Error loading input device configuration file for device '%s'. "
711 "Using default configuration.",
712 identifier.name.c_str());
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500713 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500714 configuration = std::move(*propertyMap);
Chris Ye989bb932020-07-04 16:18:59 -0700715 }
716 }
717}
718
719bool EventHub::Device::loadVirtualKeyMapLocked() {
720 // The virtual key map is supplied by the kernel as a system board property file.
721 std::string propPath = "/sys/board_properties/virtualkeys.";
722 propPath += identifier.getCanonicalName();
723 if (access(propPath.c_str(), R_OK)) {
724 return false;
725 }
726 virtualKeyMap = VirtualKeyMap::load(propPath);
727 return virtualKeyMap != nullptr;
728}
729
730status_t EventHub::Device::loadKeyMapLocked() {
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500731 return keyMap.load(identifier, configuration.get());
Chris Ye989bb932020-07-04 16:18:59 -0700732}
733
734bool EventHub::Device::isExternalDeviceLocked() {
735 if (configuration) {
Harry Cuttsf13161a2023-03-08 14:15:49 +0000736 std::optional<bool> isInternal = configuration->getBool("device.internal");
737 if (isInternal.has_value()) {
738 return !isInternal.value();
Chris Ye989bb932020-07-04 16:18:59 -0700739 }
740 }
741 return identifier.bus == BUS_USB || identifier.bus == BUS_BLUETOOTH;
742}
743
744bool EventHub::Device::deviceHasMicLocked() {
745 if (configuration) {
Harry Cuttsf13161a2023-03-08 14:15:49 +0000746 std::optional<bool> hasMic = configuration->getBool("audio.mic");
747 if (hasMic.has_value()) {
748 return hasMic.value();
Chris Ye989bb932020-07-04 16:18:59 -0700749 }
750 }
751 return false;
752}
753
754void EventHub::Device::setLedStateLocked(int32_t led, bool on) {
755 int32_t sc;
756 if (hasValidFd() && mapLed(led, &sc) != NAME_NOT_FOUND) {
757 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -0700758 ev.input_event_sec = 0;
759 ev.input_event_usec = 0;
Chris Ye989bb932020-07-04 16:18:59 -0700760 ev.type = EV_LED;
761 ev.code = sc;
762 ev.value = on ? 1 : 0;
763
764 ssize_t nWrite;
765 do {
766 nWrite = write(fd, &ev, sizeof(struct input_event));
767 } while (nWrite == -1 && errno == EINTR);
768 }
769}
770
771void EventHub::Device::setLedForControllerLocked() {
772 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
773 setLedStateLocked(ALED_CONTROLLER_1 + i, controllerNumber == i + 1);
774 }
775}
776
777status_t EventHub::Device::mapLed(int32_t led, int32_t* outScanCode) const {
778 if (!keyMap.haveKeyLayout()) {
779 return NAME_NOT_FOUND;
780 }
781
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700782 std::optional<int32_t> scanCode = keyMap.keyLayoutMap->findScanCodeForLed(led);
783 if (scanCode.has_value()) {
784 if (*scanCode >= 0 && *scanCode <= LED_MAX && ledBitmask.test(*scanCode)) {
785 *outScanCode = *scanCode;
Chris Ye989bb932020-07-04 16:18:59 -0700786 return NO_ERROR;
787 }
788 }
789 return NAME_NOT_FOUND;
790}
791
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000792void EventHub::Device::trackInputEvent(const struct input_event& event) {
793 switch (event.type) {
794 case EV_KEY: {
795 LOG_ALWAYS_FATAL_IF(!currentFrameDropped &&
796 !keyState.set(static_cast<size_t>(event.code),
797 event.value != 0),
Prabir Pradhan10301422023-07-26 21:48:30 +0000798 "%s: device '%s' received invalid EV_KEY event code: %s value: %d",
799 __func__, identifier.name.c_str(),
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000800 InputEventLookup::getLinuxEvdevLabel(EV_KEY, event.code, 1)
Prabir Pradhan10301422023-07-26 21:48:30 +0000801 .code.c_str(),
802 event.value);
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000803 break;
804 }
805 case EV_SW: {
806 LOG_ALWAYS_FATAL_IF(!currentFrameDropped &&
807 !swState.set(static_cast<size_t>(event.code),
808 event.value != 0),
Prabir Pradhan10301422023-07-26 21:48:30 +0000809 "%s: device '%s' received invalid EV_SW event code: %s value: %d",
810 __func__, identifier.name.c_str(),
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000811 InputEventLookup::getLinuxEvdevLabel(EV_SW, event.code, 1)
Prabir Pradhan10301422023-07-26 21:48:30 +0000812 .code.c_str(),
813 event.value);
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000814 break;
815 }
Prabir Pradhan341d0782023-07-14 19:04:10 +0000816 case EV_ABS: {
Prabir Pradhan10301422023-07-26 21:48:30 +0000817 if (currentFrameDropped) {
818 break;
819 }
Prabir Pradhan341d0782023-07-14 19:04:10 +0000820 auto it = absState.find(event.code);
Prabir Pradhan10301422023-07-26 21:48:30 +0000821 LOG_ALWAYS_FATAL_IF(it == absState.end(),
822 "%s: device '%s' received invalid EV_ABS event code: %s value: %d",
823 __func__, identifier.name.c_str(),
Prabir Pradhan341d0782023-07-14 19:04:10 +0000824 InputEventLookup::getLinuxEvdevLabel(EV_ABS, event.code, 0)
Prabir Pradhan10301422023-07-26 21:48:30 +0000825 .code.c_str(),
826 event.value);
Prabir Pradhan341d0782023-07-14 19:04:10 +0000827 it->second.value = event.value;
828 break;
829 }
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000830 case EV_SYN: {
831 switch (event.code) {
832 case SYN_REPORT:
Arpit Singh1c3d8552024-01-08 14:16:28 +0000833 if (currentFrameDropped) {
834 // To recover after a SYN_DROPPED, we need to query the state of the device
835 // to synchronize our device state with the kernel's to account for the
836 // dropped events on receiving the next SYN_REPORT.
837 // Note we don't drop the SYN_REPORT at this point but it is used by the
838 // InputDevice to reset and repopulate mapper state
839 readDeviceState();
840 currentFrameDropped = false;
841 }
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000842 break;
843 case SYN_DROPPED:
844 // When we receive SYN_DROPPED, all events in the current frame should be
Arpit Singh1c3d8552024-01-08 14:16:28 +0000845 // dropped up to and including next SYN_REPORT
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000846 currentFrameDropped = true;
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000847 break;
848 default:
849 break;
850 }
851 break;
852 }
853 default:
854 break;
855 }
856}
857
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100858/**
859 * Get the capabilities for the current process.
860 * Crashes the system if unable to create / check / destroy the capabilities object.
861 */
862class Capabilities final {
863public:
864 explicit Capabilities() {
865 mCaps = cap_get_proc();
866 LOG_ALWAYS_FATAL_IF(mCaps == nullptr, "Could not get capabilities of the current process");
867 }
868
869 /**
870 * Check whether the current process has a specific capability
871 * in the set of effective capabilities.
872 * Return CAP_SET if the process has the requested capability
873 * Return CAP_CLEAR otherwise.
874 */
875 cap_flag_value_t checkEffectiveCapability(cap_value_t capability) {
876 cap_flag_value_t value;
877 const int result = cap_get_flag(mCaps, capability, CAP_EFFECTIVE, &value);
878 LOG_ALWAYS_FATAL_IF(result == -1, "Could not obtain the requested capability");
879 return value;
880 }
881
882 ~Capabilities() {
883 const int result = cap_free(mCaps);
884 LOG_ALWAYS_FATAL_IF(result == -1, "Could not release the capabilities structure");
885 }
886
887private:
888 cap_t mCaps;
889};
890
891static void ensureProcessCanBlockSuspend() {
892 Capabilities capabilities;
893 const bool canBlockSuspend =
894 capabilities.checkEffectiveCapability(CAP_BLOCK_SUSPEND) == CAP_SET;
895 LOG_ALWAYS_FATAL_IF(!canBlockSuspend,
896 "Input must be able to block suspend to properly process events");
897}
898
Michael Wrightd02c5b62014-02-10 15:10:22 -0800899// --- EventHub ---
900
Michael Wrightd02c5b62014-02-10 15:10:22 -0800901const int EventHub::EPOLL_MAX_EVENTS;
902
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700903EventHub::EventHub(void)
904 : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
905 mNextDeviceId(1),
906 mControllerNumbers(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700907 mNeedToReopenDevices(false),
908 mNeedToScanDevices(true),
909 mPendingEventCount(0),
910 mPendingEventIndex(0),
911 mPendingINotify(false) {
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100912 ensureProcessCanBlockSuspend();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800913
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800914 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800915 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800916
Michael Wright8e9a8562022-02-09 13:44:29 +0000917 mINotifyFd = inotify_init1(IN_CLOEXEC);
Prabir Pradhan952e65b2022-06-23 17:49:55 +0000918 LOG_ALWAYS_FATAL_IF(mINotifyFd < 0, "Could not create inotify instance: %s", strerror(errno));
Usama Arifb27c8e62021-06-03 16:44:09 +0100919
920 std::error_code errorCode;
921 bool isDeviceInotifyAdded = false;
922 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
923 addDeviceInputInotify();
Philip Quinn39b81682019-01-09 22:20:39 -0800924 } else {
Usama Arifb27c8e62021-06-03 16:44:09 +0100925 addDeviceInotify();
926 isDeviceInotifyAdded = true;
927 if (errorCode) {
928 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
929 errorCode.message().c_str());
930 }
931 }
932
933 if (isV4lScanningEnabled() && !isDeviceInotifyAdded) {
934 addDeviceInotify();
935 } else {
Philip Quinn39b81682019-01-09 22:20:39 -0800936 ALOGI("Video device scanning disabled");
937 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800938
Siarhei Vishniakou2d0e9482019-09-24 12:52:47 +0100939 struct epoll_event eventItem = {};
940 eventItem.events = EPOLLIN | EPOLLWAKEUP;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700941 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800942 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800943 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
944
945 int wakeFds[2];
Michael Wright8e9a8562022-02-09 13:44:29 +0000946 result = pipe2(wakeFds, O_CLOEXEC);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800947 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
948
949 mWakeReadPipeFd = wakeFds[0];
950 mWakeWritePipeFd = wakeFds[1];
951
952 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
953 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700954 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800955
956 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
957 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700958 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800959
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700960 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800961 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
962 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700963 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800964}
965
966EventHub::~EventHub(void) {
967 closeAllDevicesLocked();
968
Michael Wrightd02c5b62014-02-10 15:10:22 -0800969 ::close(mEpollFd);
970 ::close(mINotifyFd);
971 ::close(mWakeReadPipeFd);
972 ::close(mWakeWritePipeFd);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800973}
974
Usama Arifb27c8e62021-06-03 16:44:09 +0100975/**
976 * On devices that don't have any input devices (like some development boards), the /dev/input
977 * directory will be absent. However, the user may still plug in an input device at a later time.
978 * Add watch for contents of /dev/input only when /dev/input appears.
979 */
980void EventHub::addDeviceInputInotify() {
981 mDeviceInputWd = inotify_add_watch(mINotifyFd, DEVICE_INPUT_PATH, IN_DELETE | IN_CREATE);
982 LOG_ALWAYS_FATAL_IF(mDeviceInputWd < 0, "Could not register INotify for %s: %s",
983 DEVICE_INPUT_PATH, strerror(errno));
984}
985
986void EventHub::addDeviceInotify() {
987 mDeviceWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
988 LOG_ALWAYS_FATAL_IF(mDeviceWd < 0, "Could not register INotify for %s: %s", DEVICE_PATH,
989 strerror(errno));
990}
991
Michael Wrightd02c5b62014-02-10 15:10:22 -0800992InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000993 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800994 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700995 return device != nullptr ? device->identifier : InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800996}
997
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700998ftl::Flags<InputDeviceClass> EventHub::getDeviceClasses(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000999 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001000 Device* device = getDeviceLocked(deviceId);
Dominik Laskowski2f01d772022-03-23 16:01:29 -07001001 return device != nullptr ? device->classes : ftl::Flags<InputDeviceClass>(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001002}
1003
1004int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001005 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001006 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -07001007 return device != nullptr ? device->controllerNumber : 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001008}
1009
Harry Cuttsc34f7582023-03-07 16:23:30 +00001010std::optional<PropertyMap> EventHub::getConfiguration(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001011 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001012 Device* device = getDeviceLocked(deviceId);
Harry Cuttsc34f7582023-03-07 16:23:30 +00001013 if (device == nullptr || device->configuration == nullptr) {
1014 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001015 }
Harry Cuttsc34f7582023-03-07 16:23:30 +00001016 return *device->configuration;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001017}
1018
Harry Cutts207674d2024-06-06 18:53:41 +00001019std::optional<RawAbsoluteAxisInfo> EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis) const {
Arpit Singh77140f42023-06-13 11:35:27 +00001020 if (axis < 0 || axis > ABS_MAX) {
Harry Cutts207674d2024-06-06 18:53:41 +00001021 return std::nullopt;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001022 }
Arpit Singh77140f42023-06-13 11:35:27 +00001023 std::scoped_lock _l(mLock);
Prabir Pradhan341d0782023-07-14 19:04:10 +00001024 const Device* device = getDeviceLocked(deviceId);
Arpit Singh77140f42023-06-13 11:35:27 +00001025 if (device == nullptr) {
Harry Cutts207674d2024-06-06 18:53:41 +00001026 return std::nullopt;
Arpit Singh77140f42023-06-13 11:35:27 +00001027 }
Prabir Pradhan341d0782023-07-14 19:04:10 +00001028 // We can read the RawAbsoluteAxisInfo even if the device is disabled and doesn't have a valid
1029 // fd, because the info is populated once when the device is first opened, and it doesn't change
1030 // throughout the device lifecycle.
1031 auto it = device->absState.find(axis);
1032 if (it == device->absState.end()) {
Harry Cutts207674d2024-06-06 18:53:41 +00001033 return std::nullopt;
Arpit Singh77140f42023-06-13 11:35:27 +00001034 }
Harry Cutts207674d2024-06-06 18:53:41 +00001035 return it->second.info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001036}
1037
1038bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
1039 if (axis >= 0 && axis <= REL_MAX) {
Chris Ye87143712020-11-10 05:05:58 +00001040 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001041 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001042 return device != nullptr ? device->relBitmask.test(axis) : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001043 }
1044 return false;
1045}
1046
1047bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
Chris Ye87143712020-11-10 05:05:58 +00001048 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001049
Chris Ye989bb932020-07-04 16:18:59 -07001050 Device* device = getDeviceLocked(deviceId);
1051 return property >= 0 && property <= INPUT_PROP_MAX && device != nullptr
1052 ? device->propBitmask.test(property)
1053 : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001054}
1055
Chris Yef59a2f42020-10-16 12:55:26 -07001056bool EventHub::hasMscEvent(int32_t deviceId, int mscEvent) const {
1057 std::scoped_lock _l(mLock);
1058
1059 Device* device = getDeviceLocked(deviceId);
1060 return mscEvent >= 0 && mscEvent <= MSC_MAX && device != nullptr
1061 ? device->mscBitmask.test(mscEvent)
1062 : false;
1063}
1064
Michael Wrightd02c5b62014-02-10 15:10:22 -08001065int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001066 if (scanCode < 0 || scanCode > KEY_MAX) {
1067 return AKEY_STATE_UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001068 }
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001069 std::scoped_lock _l(mLock);
1070 const Device* device = getDeviceLocked(deviceId);
1071 if (device == nullptr || !device->hasValidFd() || !device->keyBitmask.test(scanCode)) {
1072 return AKEY_STATE_UNKNOWN;
1073 }
1074 return device->keyState.test(scanCode) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001075}
1076
1077int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
Chris Ye87143712020-11-10 05:05:58 +00001078 std::scoped_lock _l(mLock);
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001079 const Device* device = getDeviceLocked(deviceId);
1080 if (device == nullptr || !device->hasValidFd() || !device->keyMap.haveKeyLayout()) {
1081 return AKEY_STATE_UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001082 }
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001083 const std::vector<int32_t> scanCodes =
1084 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode);
1085 if (scanCodes.empty()) {
1086 return AKEY_STATE_UNKNOWN;
1087 }
1088 return std::any_of(scanCodes.begin(), scanCodes.end(),
1089 [&device](const int32_t sc) {
1090 return sc >= 0 && sc <= KEY_MAX && device->keyState.test(sc);
1091 })
1092 ? AKEY_STATE_DOWN
1093 : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001094}
1095
Philip Junker4af3b3d2021-12-14 10:36:55 +01001096int32_t EventHub::getKeyCodeForKeyLocation(int32_t deviceId, int32_t locationKeyCode) const {
1097 std::scoped_lock _l(mLock);
1098
1099 Device* device = getDeviceLocked(deviceId);
1100 if (device == nullptr || !device->hasValidFd() || device->keyMap.keyCharacterMap == nullptr ||
1101 device->keyMap.keyLayoutMap == nullptr) {
1102 return AKEYCODE_UNKNOWN;
1103 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001104 std::vector<int32_t> scanCodes =
1105 device->keyMap.keyLayoutMap->findScanCodesForKey(locationKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +01001106 if (scanCodes.empty()) {
1107 ALOGW("Failed to get key code for key location: no scan code maps to key code %d for input"
1108 "device %d",
1109 locationKeyCode, deviceId);
1110 return AKEYCODE_UNKNOWN;
1111 }
1112 if (scanCodes.size() > 1) {
1113 ALOGW("Multiple scan codes map to the same key code %d, returning only the first match",
1114 locationKeyCode);
1115 }
1116 int32_t outKeyCode;
1117 status_t mapKeyRes =
Harry Cutts33476232023-01-30 19:57:29 +00001118 device->getKeyCharacterMap()->mapKey(scanCodes[0], /*usageCode=*/0, &outKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +01001119 switch (mapKeyRes) {
1120 case OK:
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001121 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +01001122 case NAME_NOT_FOUND:
1123 // key character map doesn't re-map this scanCode, hence the keyCode remains the same
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001124 outKeyCode = locationKeyCode;
1125 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +01001126 default:
1127 ALOGW("Failed to get key code for key location: Key character map returned error %s",
1128 statusToString(mapKeyRes).c_str());
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001129 outKeyCode = AKEYCODE_UNKNOWN;
1130 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +01001131 }
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001132 // Remap if there is a Key remapping added to the KCM and return the remapped key
1133 return device->getKeyCharacterMap()->applyKeyRemapping(outKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +01001134}
1135
Michael Wrightd02c5b62014-02-10 15:10:22 -08001136int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001137 if (sw < 0 || sw > SW_MAX) {
1138 return AKEY_STATE_UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001139 }
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001140 std::scoped_lock _l(mLock);
1141 const Device* device = getDeviceLocked(deviceId);
1142 if (device == nullptr || !device->hasValidFd() || !device->swBitmask.test(sw)) {
1143 return AKEY_STATE_UNKNOWN;
1144 }
1145 return device->swState.test(sw) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001146}
1147
Harry Cuttse2c5e202024-06-21 17:08:48 +00001148std::optional<int32_t> EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis) const {
Prabir Pradhan341d0782023-07-14 19:04:10 +00001149 if (axis < 0 || axis > ABS_MAX) {
Harry Cuttse2c5e202024-06-21 17:08:48 +00001150 return std::nullopt;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001151 }
Prabir Pradhan341d0782023-07-14 19:04:10 +00001152 std::scoped_lock _l(mLock);
1153 const Device* device = getDeviceLocked(deviceId);
1154 if (device == nullptr || !device->hasValidFd()) {
Harry Cuttse2c5e202024-06-21 17:08:48 +00001155 return std::nullopt;
Prabir Pradhan341d0782023-07-14 19:04:10 +00001156 }
1157 const auto it = device->absState.find(axis);
1158 if (it == device->absState.end()) {
Harry Cuttse2c5e202024-06-21 17:08:48 +00001159 return std::nullopt;
Prabir Pradhan341d0782023-07-14 19:04:10 +00001160 }
Harry Cuttse2c5e202024-06-21 17:08:48 +00001161 return it->second.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001162}
1163
Arpit Singh4b4a4572023-11-24 18:19:56 +00001164base::Result<std::vector<int32_t>> EventHub::getMtSlotValues(int32_t deviceId, int32_t axis,
1165 size_t slotCount) const {
1166 std::scoped_lock _l(mLock);
1167 const Device* device = getDeviceLocked(deviceId);
1168 if (device == nullptr || !device->hasValidFd() || !device->absBitmask.test(axis)) {
1169 return base::ResultError("device problem or axis not supported", NAME_NOT_FOUND);
1170 }
1171 std::vector<int32_t> outValues(slotCount + 1);
1172 outValues[0] = axis;
1173 const size_t bufferSize = outValues.size() * sizeof(int32_t);
1174 if (ioctl(device->fd, EVIOCGMTSLOTS(bufferSize), outValues.data()) != OK) {
1175 return base::ErrnoError();
1176 }
1177 return std::move(outValues);
1178}
1179
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001180bool EventHub::markSupportedKeyCodes(int32_t deviceId, const std::vector<int32_t>& keyCodes,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001181 uint8_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +00001182 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001183
1184 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001185 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001186 for (size_t codeIndex = 0; codeIndex < keyCodes.size(); codeIndex++) {
Sergej Salnikove5420e72023-05-11 11:52:54 +00001187 if (device->hasKeycodeLocked(keyCodes[codeIndex])) {
1188 outFlags[codeIndex] = 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001189 }
1190 }
1191 return true;
1192 }
1193 return false;
1194}
1195
Linnan Lie5657f22024-09-13 21:54:37 +08001196void EventHub::setKeyRemapping(int32_t deviceId,
1197 const std::map<int32_t, int32_t>& keyRemapping) const {
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001198 std::scoped_lock _l(mLock);
1199 Device* device = getDeviceLocked(deviceId);
1200 if (device == nullptr) {
1201 return;
1202 }
1203 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
1204 if (kcm) {
Linnan Lie5657f22024-09-13 21:54:37 +08001205 kcm->setKeyRemapping(keyRemapping);
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001206 }
1207}
1208
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001209status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
1210 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +00001211 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001212 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001213 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001214
Chris Ye66fbac32020-07-06 20:36:43 -07001215 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001216 // Check the key character map first.
Chris Ye3a1e4462020-08-12 10:13:15 -07001217 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
1218 if (kcm) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001219 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
1220 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001221 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001222 }
1223 }
1224
1225 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001226 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -08001227 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001228 status = NO_ERROR;
1229 }
1230 }
1231
1232 if (status == NO_ERROR) {
Chris Ye3a1e4462020-08-12 10:13:15 -07001233 if (kcm) {
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001234 // Remap keys based on user-defined key remappings and key behavior defined in the
1235 // corresponding kcm file
1236 *outKeycode = kcm->applyKeyRemapping(*outKeycode);
1237
1238 // Remap keys based on Key behavior defined in KCM file
1239 std::tie(*outKeycode, *outMetaState) =
1240 kcm->applyKeyBehavior(*outKeycode, metaState);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001241 } else {
1242 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243 }
1244 }
1245 }
1246
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001247 if (status != NO_ERROR) {
1248 *outKeycode = 0;
1249 *outFlags = 0;
1250 *outMetaState = metaState;
1251 }
1252
1253 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001254}
1255
1256status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
Chris Ye87143712020-11-10 05:05:58 +00001257 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001258 Device* device = getDeviceLocked(deviceId);
1259
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001260 if (device == nullptr || !device->keyMap.haveKeyLayout()) {
1261 return NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001262 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001263 std::optional<AxisInfo> info = device->keyMap.keyLayoutMap->mapAxis(scanCode);
1264 if (!info.has_value()) {
1265 return NAME_NOT_FOUND;
1266 }
1267 *outAxisInfo = *info;
1268 return NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001269}
1270
Chris Yef59a2f42020-10-16 12:55:26 -07001271base::Result<std::pair<InputDeviceSensorType, int32_t>> EventHub::mapSensor(int32_t deviceId,
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001272 int32_t absCode) const {
Chris Yef59a2f42020-10-16 12:55:26 -07001273 std::scoped_lock _l(mLock);
1274 Device* device = getDeviceLocked(deviceId);
1275
1276 if (device != nullptr && device->keyMap.haveKeyLayout()) {
1277 return device->keyMap.keyLayoutMap->mapSensor(absCode);
1278 }
1279 return Errorf("Device not found or device has no key layout.");
1280}
1281
Chris Yee2b1e5c2021-03-10 22:45:12 -08001282// Gets the battery info map from battery ID to RawBatteryInfo of the miscellaneous device
1283// associated with the device ID. Returns an empty map if no miscellaneous device found.
1284const std::unordered_map<int32_t, RawBatteryInfo>& EventHub::getBatteryInfoLocked(
1285 int32_t deviceId) const {
1286 static const std::unordered_map<int32_t, RawBatteryInfo> EMPTY_BATTERY_INFO = {};
1287 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001288 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001289 return EMPTY_BATTERY_INFO;
1290 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001291 return device->associatedDevice->batteryInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001292}
1293
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001294std::vector<int32_t> EventHub::getRawBatteryIds(int32_t deviceId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001295 std::scoped_lock _l(mLock);
1296 std::vector<int32_t> batteryIds;
1297
Prabir Pradhan51894782022-08-23 16:29:10 +00001298 for (const auto& [id, info] : getBatteryInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001299 batteryIds.push_back(id);
1300 }
1301
1302 return batteryIds;
1303}
1304
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001305std::optional<RawBatteryInfo> EventHub::getRawBatteryInfo(int32_t deviceId,
1306 int32_t batteryId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001307 std::scoped_lock _l(mLock);
1308
1309 const auto infos = getBatteryInfoLocked(deviceId);
1310
1311 auto it = infos.find(batteryId);
1312 if (it != infos.end()) {
1313 return it->second;
1314 }
1315
1316 return std::nullopt;
1317}
1318
1319// Gets the light info map from light ID to RawLightInfo of the miscellaneous device associated
Prabir Pradhan51894782022-08-23 16:29:10 +00001320// with the device ID. Returns an empty map if no miscellaneous device found.
Chris Yee2b1e5c2021-03-10 22:45:12 -08001321const std::unordered_map<int32_t, RawLightInfo>& EventHub::getLightInfoLocked(
1322 int32_t deviceId) const {
1323 static const std::unordered_map<int32_t, RawLightInfo> EMPTY_LIGHT_INFO = {};
1324 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001325 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001326 return EMPTY_LIGHT_INFO;
1327 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001328 return device->associatedDevice->lightInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001329}
1330
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001331std::vector<int32_t> EventHub::getRawLightIds(int32_t deviceId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001332 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001333 std::vector<int32_t> lightIds;
1334
Prabir Pradhan51894782022-08-23 16:29:10 +00001335 for (const auto& [id, info] : getLightInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001336 lightIds.push_back(id);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001337 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001338
Chris Ye3fdbfef2021-01-06 18:45:18 -08001339 return lightIds;
1340}
1341
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001342std::optional<RawLightInfo> EventHub::getRawLightInfo(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001343 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001344
Chris Yee2b1e5c2021-03-10 22:45:12 -08001345 const auto infos = getLightInfoLocked(deviceId);
1346
1347 auto it = infos.find(lightId);
1348 if (it != infos.end()) {
1349 return it->second;
Chris Ye3fdbfef2021-01-06 18:45:18 -08001350 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001351
Chris Ye3fdbfef2021-01-06 18:45:18 -08001352 return std::nullopt;
1353}
1354
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001355std::optional<int32_t> EventHub::getLightBrightness(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001356 std::scoped_lock _l(mLock);
1357
Chris Yee2b1e5c2021-03-10 22:45:12 -08001358 const auto infos = getLightInfoLocked(deviceId);
1359 auto it = infos.find(lightId);
1360 if (it == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001361 return std::nullopt;
1362 }
1363 std::string buffer;
1364 if (!base::ReadFileToString(it->second.path / LIGHT_NODES.at(InputLightClass::BRIGHTNESS),
1365 &buffer)) {
1366 return std::nullopt;
1367 }
1368 return std::stoi(buffer);
1369}
1370
1371std::optional<std::unordered_map<LightColor, int32_t>> EventHub::getLightIntensities(
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001372 int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001373 std::scoped_lock _l(mLock);
1374
Chris Yee2b1e5c2021-03-10 22:45:12 -08001375 const auto infos = getLightInfoLocked(deviceId);
1376 auto lightIt = infos.find(lightId);
1377 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001378 return std::nullopt;
1379 }
1380
1381 auto ret =
1382 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1383
1384 if (!ret.has_value()) {
1385 return std::nullopt;
1386 }
1387 std::array<LightColor, COLOR_NUM> colors = ret.value();
1388
1389 std::string intensityStr;
1390 if (!base::ReadFileToString(lightIt->second.path /
1391 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY),
1392 &intensityStr)) {
1393 return std::nullopt;
1394 }
1395
1396 // Intensity node outputs 3 color values
1397 std::regex intensityPattern("([0-9]+)\\s([0-9]+)\\s([0-9]+)[\\n]");
1398 std::smatch results;
1399
1400 if (!std::regex_match(intensityStr, results, intensityPattern)) {
1401 return std::nullopt;
1402 }
1403 std::unordered_map<LightColor, int32_t> intensities;
1404 for (size_t i = 1; i < results.size(); i++) {
1405 int value = std::stoi(results[i].str());
1406 intensities.emplace(colors[i - 1], value);
1407 }
1408 return intensities;
1409}
1410
1411void EventHub::setLightBrightness(int32_t deviceId, int32_t lightId, int32_t brightness) {
1412 std::scoped_lock _l(mLock);
1413
Chris Yee2b1e5c2021-03-10 22:45:12 -08001414 const auto infos = getLightInfoLocked(deviceId);
1415 auto lightIt = infos.find(lightId);
1416 if (lightIt == infos.end()) {
1417 ALOGE("%s lightId %d not found ", __func__, lightId);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001418 return;
1419 }
1420
1421 if (!base::WriteStringToFile(std::to_string(brightness),
1422 lightIt->second.path /
1423 LIGHT_NODES.at(InputLightClass::BRIGHTNESS))) {
1424 ALOGE("Can not write to file, error: %s", strerror(errno));
1425 }
1426}
1427
1428void EventHub::setLightIntensities(int32_t deviceId, int32_t lightId,
1429 std::unordered_map<LightColor, int32_t> intensities) {
1430 std::scoped_lock _l(mLock);
1431
Chris Yee2b1e5c2021-03-10 22:45:12 -08001432 const auto infos = getLightInfoLocked(deviceId);
1433 auto lightIt = infos.find(lightId);
1434 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001435 ALOGE("Light Id %d does not exist.", lightId);
1436 return;
1437 }
1438
1439 auto ret =
1440 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1441
1442 if (!ret.has_value()) {
1443 return;
1444 }
1445 std::array<LightColor, COLOR_NUM> colors = ret.value();
1446
1447 std::string rgbStr;
1448 for (size_t i = 0; i < COLOR_NUM; i++) {
1449 auto it = intensities.find(colors[i]);
1450 if (it != intensities.end()) {
1451 rgbStr += std::to_string(it->second);
1452 // Insert space between colors
1453 if (i < COLOR_NUM - 1) {
1454 rgbStr += " ";
1455 }
1456 }
1457 }
1458 // Append new line
1459 rgbStr += "\n";
1460
1461 if (!base::WriteStringToFile(rgbStr,
1462 lightIt->second.path /
1463 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY))) {
1464 ALOGE("Can not write to file, error: %s", strerror(errno));
1465 }
1466}
1467
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001468std::optional<RawLayoutInfo> EventHub::getRawLayoutInfo(int32_t deviceId) const {
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001469 std::scoped_lock _l(mLock);
1470 Device* device = getDeviceLocked(deviceId);
1471 if (device == nullptr || !device->associatedDevice) {
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001472 return std::nullopt;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001473 }
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001474 return device->associatedDevice->layoutInfo;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001475}
1476
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001477void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Chris Ye87143712020-11-10 05:05:58 +00001478 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001479
1480 mExcludedDevices = devices;
1481}
1482
1483bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
Chris Ye87143712020-11-10 05:05:58 +00001484 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001485 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001486 if (device != nullptr && scanCode >= 0 && scanCode <= KEY_MAX) {
1487 return device->keyBitmask.test(scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001488 }
1489 return false;
1490}
1491
Arthur Hungcb40a002021-08-03 14:31:01 +00001492bool EventHub::hasKeyCode(int32_t deviceId, int32_t keyCode) const {
1493 std::scoped_lock _l(mLock);
1494 Device* device = getDeviceLocked(deviceId);
1495 if (device != nullptr) {
1496 return device->hasKeycodeLocked(keyCode);
1497 }
1498 return false;
1499}
1500
Michael Wrightd02c5b62014-02-10 15:10:22 -08001501bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
Chris Ye87143712020-11-10 05:05:58 +00001502 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001503 Device* device = getDeviceLocked(deviceId);
1504 int32_t sc;
Chris Ye989bb932020-07-04 16:18:59 -07001505 if (device != nullptr && device->mapLed(led, &sc) == NO_ERROR) {
Chris Ye66fbac32020-07-06 20:36:43 -07001506 return device->ledBitmask.test(sc);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001507 }
1508 return false;
1509}
1510
1511void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
Chris Ye87143712020-11-10 05:05:58 +00001512 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001513 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -07001514 if (device != nullptr && device->hasValidFd()) {
1515 device->setLedStateLocked(led, on);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001516 }
1517}
1518
1519void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001520 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001521 outVirtualKeys.clear();
1522
Chris Ye87143712020-11-10 05:05:58 +00001523 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001524 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001525 if (device != nullptr && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001526 const std::vector<VirtualKeyDefinition> virtualKeys =
1527 device->virtualKeyMap->getVirtualKeys();
1528 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001529 }
1530}
1531
Chris Ye3a1e4462020-08-12 10:13:15 -07001532const std::shared_ptr<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001533 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001534 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001535 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001536 return device->getKeyCharacterMap();
1537 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001538 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001539}
1540
Vaibhav Devmurari23e8ae92022-12-29 12:07:56 +00001541// If provided map is null, it will reset key character map to default KCM.
Chris Ye3a1e4462020-08-12 10:13:15 -07001542bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, std::shared_ptr<KeyCharacterMap> map) {
Chris Ye87143712020-11-10 05:05:58 +00001543 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001544 Device* device = getDeviceLocked(deviceId);
Vaibhav Devmurari23e8ae92022-12-29 12:07:56 +00001545 if (device == nullptr || device->keyMap.keyCharacterMap == nullptr) {
Philip Junker90bc9492021-12-10 18:39:42 +01001546 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001547 }
Vaibhav Devmurari23e8ae92022-12-29 12:07:56 +00001548 if (map == nullptr) {
1549 device->keyMap.keyCharacterMap->clearLayoutOverlay();
1550 return true;
1551 }
Philip Junker90bc9492021-12-10 18:39:42 +01001552 device->keyMap.keyCharacterMap->combine(*map);
1553 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001554}
1555
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001556static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
1557 std::string rawDescriptor;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001558 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001559 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001560 if (!identifier.uniqueId.empty()) {
1561 rawDescriptor += "uniqueId:";
1562 rawDescriptor += identifier.uniqueId;
Josh Bartel938632f2022-07-19 15:34:22 -05001563 }
1564 if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001565 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001566 }
1567
1568 if (identifier.vendor == 0 && identifier.product == 0) {
1569 // If we don't know the vendor and product id, then the device is probably
1570 // built-in so we need to rely on other information to uniquely identify
1571 // the input device. Usually we try to avoid relying on the device name or
1572 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001573 if (!identifier.name.empty()) {
1574 rawDescriptor += "name:";
1575 rawDescriptor += identifier.name;
1576 } else if (!identifier.location.empty()) {
1577 rawDescriptor += "location:";
1578 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001579 }
1580 }
1581 identifier.descriptor = sha1(rawDescriptor);
1582 return rawDescriptor;
1583}
1584
1585void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
1586 // Compute a device descriptor that uniquely identifies the device.
1587 // The descriptor is assumed to be a stable identifier. Its value should not
1588 // change between reboots, reconnections, firmware updates or new releases
1589 // of Android. In practice we sometimes get devices that cannot be uniquely
1590 // identified. In this case we enforce uniqueness between connected devices.
1591 // Ideally, we also want the descriptor to be short and relatively opaque.
Josh Bartel938632f2022-07-19 15:34:22 -05001592 // Note that we explicitly do not use the path or location for external devices
1593 // as their path or location will change as they are plugged/unplugged or moved
1594 // to different ports. We do fallback to using name and location in the case of
1595 // internal devices which are detected by the vendor and product being 0 in
1596 // generateDescriptor. If two identical descriptors are detected we will fallback
1597 // to using a 'nonce' and incrementing it until the new descriptor no longer has
1598 // a match with any existing descriptors.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001599
1600 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001601 std::string rawDescriptor = generateDescriptor(identifier);
Josh Bartel938632f2022-07-19 15:34:22 -05001602 // Enforce that the generated descriptor is unique.
1603 while (hasDeviceWithDescriptorLocked(identifier.descriptor)) {
1604 identifier.nonce++;
1605 rawDescriptor = generateDescriptor(identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001606 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001607 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001608 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001609}
1610
Prabir Pradhancb42b472022-08-23 16:01:19 +00001611std::shared_ptr<const EventHub::AssociatedDevice> EventHub::obtainAssociatedDeviceLocked(
1612 const std::filesystem::path& devicePath) const {
1613 const std::optional<std::filesystem::path> sysfsRootPathOpt =
1614 getSysfsRootPath(devicePath.c_str());
1615 if (!sysfsRootPathOpt) {
1616 return nullptr;
1617 }
1618
1619 const auto& path = *sysfsRootPathOpt;
Prabir Pradhancb42b472022-08-23 16:01:19 +00001620
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00001621 std::shared_ptr<const AssociatedDevice> associatedDevice = std::make_shared<AssociatedDevice>(
Prabir Pradhancb42b472022-08-23 16:01:19 +00001622 AssociatedDevice{.sysfsRootPath = path,
1623 .batteryInfos = readBatteryConfiguration(path),
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001624 .lightInfos = readLightsConfiguration(path),
1625 .layoutInfo = readLayoutConfiguration(path)});
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00001626
1627 bool associatedDeviceChanged = false;
1628 for (const auto& [id, dev] : mDevices) {
1629 if (dev->associatedDevice && dev->associatedDevice->sysfsRootPath == path) {
1630 if (*associatedDevice != *dev->associatedDevice) {
1631 associatedDeviceChanged = true;
1632 dev->associatedDevice = associatedDevice;
1633 }
1634 associatedDevice = dev->associatedDevice;
1635 }
1636 }
1637 ALOGI_IF(associatedDeviceChanged,
1638 "The AssociatedDevice changed for path '%s'. Using new AssociatedDevice: %s",
1639 path.c_str(), associatedDevice->dump().c_str());
1640
1641 return associatedDevice;
Prabir Pradhancb42b472022-08-23 16:01:19 +00001642}
1643
Vaibhav Devmurari5fc7d852023-03-17 18:43:33 +00001644bool EventHub::AssociatedDevice::isChanged() const {
1645 std::unordered_map<int32_t, RawBatteryInfo> newBatteryInfos =
1646 readBatteryConfiguration(sysfsRootPath);
1647 std::unordered_map<int32_t, RawLightInfo> newLightInfos =
1648 readLightsConfiguration(sysfsRootPath);
1649 std::optional<RawLayoutInfo> newLayoutInfo = readLayoutConfiguration(sysfsRootPath);
1650
1651 if (newBatteryInfos == batteryInfos && newLightInfos == lightInfos &&
1652 newLayoutInfo == layoutInfo) {
1653 return false;
1654 }
1655 return true;
1656}
1657
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001658void EventHub::vibrate(int32_t deviceId, const VibrationElement& element) {
Chris Ye87143712020-11-10 05:05:58 +00001659 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001660 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001661 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001662 ff_effect effect;
1663 memset(&effect, 0, sizeof(effect));
1664 effect.type = FF_RUMBLE;
1665 effect.id = device->ffEffectId;
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001666 // evdev FF_RUMBLE effect only supports two channels of vibration.
Chris Ye6393a262020-08-04 19:41:36 -07001667 effect.u.rumble.strong_magnitude = element.getMagnitude(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1668 effect.u.rumble.weak_magnitude = element.getMagnitude(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001669 effect.replay.length = element.duration.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001670 effect.replay.delay = 0;
1671 if (ioctl(device->fd, EVIOCSFF, &effect)) {
1672 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001673 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001674 return;
1675 }
1676 device->ffEffectId = effect.id;
1677
1678 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -07001679 ev.input_event_sec = 0;
1680 ev.input_event_usec = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001681 ev.type = EV_FF;
1682 ev.code = device->ffEffectId;
1683 ev.value = 1;
1684 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1685 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001686 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001687 return;
1688 }
1689 device->ffEffectPlaying = true;
1690 }
1691}
1692
1693void EventHub::cancelVibrate(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001694 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001695 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001696 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001697 if (device->ffEffectPlaying) {
1698 device->ffEffectPlaying = false;
1699
1700 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -07001701 ev.input_event_sec = 0;
1702 ev.input_event_usec = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001703 ev.type = EV_FF;
1704 ev.code = device->ffEffectId;
1705 ev.value = 0;
1706 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1707 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001708 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001709 return;
1710 }
1711 }
1712 }
1713}
1714
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001715std::vector<int32_t> EventHub::getVibratorIds(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001716 std::scoped_lock _l(mLock);
1717 std::vector<int32_t> vibrators;
1718 Device* device = getDeviceLocked(deviceId);
1719 if (device != nullptr && device->hasValidFd() &&
1720 device->classes.test(InputDeviceClass::VIBRATOR)) {
1721 vibrators.push_back(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1722 vibrators.push_back(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
1723 }
1724 return vibrators;
1725}
1726
Josh Bartel938632f2022-07-19 15:34:22 -05001727/**
1728 * Checks both mDevices and mOpeningDevices for a device with the descriptor passed.
1729 */
1730bool EventHub::hasDeviceWithDescriptorLocked(const std::string& descriptor) const {
1731 for (const auto& device : mOpeningDevices) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001732 if (descriptor == device->identifier.descriptor) {
Josh Bartel938632f2022-07-19 15:34:22 -05001733 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001734 }
1735 }
Josh Bartel938632f2022-07-19 15:34:22 -05001736
1737 for (const auto& [id, device] : mDevices) {
1738 if (descriptor == device->identifier.descriptor) {
1739 return true;
1740 }
1741 }
1742 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001743}
1744
1745EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001746 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001747 deviceId = mBuiltInKeyboardId;
1748 }
Chris Ye989bb932020-07-04 16:18:59 -07001749 const auto& it = mDevices.find(deviceId);
1750 return it != mDevices.end() ? it->second.get() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001751}
1752
Chris Ye8594e192020-07-14 10:34:06 -07001753EventHub::Device* EventHub::getDeviceByPathLocked(const std::string& devicePath) const {
Chris Ye989bb932020-07-04 16:18:59 -07001754 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001755 if (device->path == devicePath) {
Chris Ye989bb932020-07-04 16:18:59 -07001756 return device.get();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001757 }
1758 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001759 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001760}
1761
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001762/**
1763 * The file descriptor could be either input device, or a video device (associated with a
1764 * specific input device). Check both cases here, and return the device that this event
1765 * belongs to. Caller can compare the fd's once more to determine event type.
1766 * Looks through all input devices, and only attached video devices. Unattached video
1767 * devices are ignored.
1768 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001769EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
Chris Ye989bb932020-07-04 16:18:59 -07001770 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001771 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001772 // This is an input device event
Chris Ye989bb932020-07-04 16:18:59 -07001773 return device.get();
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001774 }
1775 if (device->videoDevice && device->videoDevice->getFd() == fd) {
1776 // This is a video device event
Chris Ye989bb932020-07-04 16:18:59 -07001777 return device.get();
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001778 }
1779 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001780 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
1781 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001782 return nullptr;
1783}
1784
Chris Yee2b1e5c2021-03-10 22:45:12 -08001785std::optional<int32_t> EventHub::getBatteryCapacity(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001786 std::filesystem::path batteryPath;
1787 {
1788 // Do not read the sysfs node to get the battery state while holding
1789 // the EventHub lock. For some peripheral devices, reading battery state
1790 // can be broken and take 5+ seconds. Holding the lock in this case would
1791 // block all other event processing during this time. For now, we assume this
1792 // call never happens on the InputReader thread and read the sysfs node outside
1793 // the lock to prevent event processing from being blocked by this call.
1794 std::scoped_lock _l(mLock);
Kim Low03ea0352020-11-06 12:45:07 -08001795
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001796 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001797 auto it = infos.find(batteryId);
1798 if (it == infos.end()) {
1799 return std::nullopt;
1800 }
1801 batteryPath = it->second.path;
1802 } // release lock
1803
Chris Yee2b1e5c2021-03-10 22:45:12 -08001804 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001805
1806 // Some devices report battery capacity as an integer through the "capacity" file
Andy Chenf9f1a022022-08-29 20:07:10 -04001807 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001808 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001809 return std::stoi(base::Trim(buffer));
Kim Low03ea0352020-11-06 12:45:07 -08001810 }
1811
1812 // Other devices report capacity as an enum value POWER_SUPPLY_CAPACITY_LEVEL_XXX
1813 // These values are taken from kernel source code include/linux/power_supply.h
Andy Chenf9f1a022022-08-29 20:07:10 -04001814 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY_LEVEL),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001815 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001816 // Remove any white space such as trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001817 const auto levelIt = BATTERY_LEVEL.find(base::Trim(buffer));
1818 if (levelIt != BATTERY_LEVEL.end()) {
1819 return levelIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001820 }
1821 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001822
Kim Low03ea0352020-11-06 12:45:07 -08001823 return std::nullopt;
1824}
1825
Chris Yee2b1e5c2021-03-10 22:45:12 -08001826std::optional<int32_t> EventHub::getBatteryStatus(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001827 std::filesystem::path batteryPath;
1828 {
1829 // Do not read the sysfs node to get the battery state while holding
1830 // the EventHub lock. For some peripheral devices, reading battery state
1831 // can be broken and take 5+ seconds. Holding the lock in this case would
1832 // block all other event processing during this time. For now, we assume this
1833 // call never happens on the InputReader thread and read the sysfs node outside
1834 // the lock to prevent event processing from being blocked by this call.
1835 std::scoped_lock _l(mLock);
1836
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001837 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001838 auto it = infos.find(batteryId);
1839 if (it == infos.end()) {
1840 return std::nullopt;
1841 }
1842 batteryPath = it->second.path;
1843 } // release lock
1844
Chris Yee2b1e5c2021-03-10 22:45:12 -08001845 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001846
Andy Chenf9f1a022022-08-29 20:07:10 -04001847 if (!base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::STATUS),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001848 &buffer)) {
Kim Low03ea0352020-11-06 12:45:07 -08001849 ALOGE("Failed to read sysfs battery info: %s", strerror(errno));
1850 return std::nullopt;
1851 }
1852
Chris Yed1936772021-02-22 10:30:40 -08001853 // Remove white space like trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001854 const auto statusIt = BATTERY_STATUS.find(base::Trim(buffer));
1855 if (statusIt != BATTERY_STATUS.end()) {
1856 return statusIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001857 }
1858
1859 return std::nullopt;
1860}
1861
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001862std::vector<RawEvent> EventHub::getEvents(int timeoutMillis) {
Chris Ye87143712020-11-10 05:05:58 +00001863 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001864
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001865 std::array<input_event, EVENT_BUFFER_SIZE> readBuffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001866
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001867 std::vector<RawEvent> events;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001868 bool awoken = false;
1869 for (;;) {
1870 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
1871
1872 // Reopen input devices if needed.
1873 if (mNeedToReopenDevices) {
1874 mNeedToReopenDevices = false;
1875
1876 ALOGI("Reopening all input devices due to a configuration change.");
1877
1878 closeAllDevicesLocked();
1879 mNeedToScanDevices = true;
1880 break; // return to the caller before we actually rescan
1881 }
1882
1883 // Report any devices that had last been added/removed.
Chris Ye989bb932020-07-04 16:18:59 -07001884 for (auto it = mClosingDevices.begin(); it != mClosingDevices.end();) {
1885 std::unique_ptr<Device> device = std::move(*it);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001886 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001887 const int32_t deviceId = (device->id == mBuiltInKeyboardId)
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001888 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
1889 : device->id;
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001890 events.push_back({
1891 .when = now,
1892 .deviceId = deviceId,
1893 .type = DEVICE_REMOVED,
1894 });
Chris Ye989bb932020-07-04 16:18:59 -07001895 it = mClosingDevices.erase(it);
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001896 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001897 break;
1898 }
1899 }
1900
1901 if (mNeedToScanDevices) {
1902 mNeedToScanDevices = false;
1903 scanDevicesLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001904 }
1905
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001906 while (!mOpeningDevices.empty()) {
1907 std::unique_ptr<Device> device = std::move(*mOpeningDevices.rbegin());
1908 mOpeningDevices.pop_back();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001909 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001910 const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1911 events.push_back({
1912 .when = now,
1913 .deviceId = deviceId,
1914 .type = DEVICE_ADDED,
1915 });
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001916
1917 // Try to find a matching video device by comparing device names
1918 for (auto it = mUnattachedVideoDevices.begin(); it != mUnattachedVideoDevices.end();
1919 it++) {
1920 std::unique_ptr<TouchVideoDevice>& videoDevice = *it;
Chris Yed3fef462021-03-07 17:10:08 -08001921 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001922 // videoDevice was transferred to 'device'
1923 it = mUnattachedVideoDevices.erase(it);
1924 break;
1925 }
1926 }
1927
1928 auto [dev_it, inserted] = mDevices.insert_or_assign(device->id, std::move(device));
1929 if (!inserted) {
Chris Ye989bb932020-07-04 16:18:59 -07001930 ALOGW("Device id %d exists, replaced.", device->id);
1931 }
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001932 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001933 break;
1934 }
1935 }
1936
1937 // Grab the next input event.
1938 bool deviceChanged = false;
1939 while (mPendingEventIndex < mPendingEventCount) {
1940 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001941 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001942 if (eventItem.events & EPOLLIN) {
1943 mPendingINotify = true;
1944 } else {
1945 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
1946 }
1947 continue;
1948 }
1949
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001950 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001951 if (eventItem.events & EPOLLIN) {
1952 ALOGV("awoken after wake()");
1953 awoken = true;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001954 char wakeReadBuffer[16];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001955 ssize_t nRead;
1956 do {
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001957 nRead = read(mWakeReadPipeFd, wakeReadBuffer, sizeof(wakeReadBuffer));
1958 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(wakeReadBuffer));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001959 } else {
1960 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001961 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001962 }
1963 continue;
1964 }
1965
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001966 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Chris Ye989bb932020-07-04 16:18:59 -07001967 if (device == nullptr) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001968 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
1969 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001970 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001971 continue;
1972 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001973 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
1974 if (eventItem.events & EPOLLIN) {
1975 size_t numFrames = device->videoDevice->readAndQueueFrames();
1976 if (numFrames == 0) {
1977 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001978 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001979 }
1980 } else if (eventItem.events & EPOLLHUP) {
1981 // TODO(b/121395353) - consider adding EPOLLRDHUP
1982 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001983 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001984 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1985 device->videoDevice = nullptr;
1986 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001987 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1988 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001989 ALOG_ASSERT(!DEBUG);
1990 }
1991 continue;
1992 }
1993 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -08001994 if (eventItem.events & EPOLLIN) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001995 int32_t readSize =
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001996 read(device->fd, readBuffer.data(),
1997 sizeof(decltype(readBuffer)::value_type) * readBuffer.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001998 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
1999 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -07002000 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07002001 " capacity: %zu errno: %d)\n",
2002 device->fd, readSize, readBuffer.size(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002003 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07002004 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002005 } else if (readSize < 0) {
2006 if (errno != EAGAIN && errno != EINTR) {
2007 ALOGW("could not get event (errno=%d)", errno);
2008 }
2009 } else if ((readSize % sizeof(struct input_event)) != 0) {
2010 ALOGE("could not get event (wrong size: %d)", readSize);
2011 } else {
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002012 const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002013
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002014 const size_t count = size_t(readSize) / sizeof(struct input_event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002015 for (size_t i = 0; i < count; i++) {
2016 struct input_event& iev = readBuffer[i];
Prabir Pradhan9762ac92023-07-13 21:45:12 +00002017 device->trackInputEvent(iev);
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002018 events.push_back({
2019 .when = processEventTimestamp(iev),
2020 .readTime = systemTime(SYSTEM_TIME_MONOTONIC),
2021 .deviceId = deviceId,
2022 .type = iev.type,
2023 .code = iev.code,
2024 .value = iev.value,
2025 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08002026 }
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07002027 if (events.size() >= EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002028 // The result buffer is full. Reset the pending event index
2029 // so we will try to read the device again on the next iteration.
2030 mPendingEventIndex -= 1;
2031 break;
2032 }
2033 }
2034 } else if (eventItem.events & EPOLLHUP) {
2035 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002036 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002037 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07002038 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002039 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002040 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
2041 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002042 }
2043 }
2044
2045 // readNotify() will modify the list of devices so this must be done after
2046 // processing all other events to ensure that we read all remaining events
2047 // before closing the devices.
2048 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
2049 mPendingINotify = false;
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002050 const auto res = readNotifyLocked();
2051 if (!res.ok()) {
2052 ALOGW("Failed to read from inotify: %s", res.error().message().c_str());
2053 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002054 deviceChanged = true;
2055 }
2056
2057 // Report added or removed devices immediately.
2058 if (deviceChanged) {
2059 continue;
2060 }
2061
2062 // Return now if we have collected any events or if we were explicitly awoken.
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002063 if (!events.empty() || awoken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002064 break;
2065 }
2066
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01002067 // Poll for events.
2068 // When a device driver has pending (unread) events, it acquires
2069 // a kernel wake lock. Once the last pending event has been read, the device
2070 // driver will release the kernel wake lock, but the epoll will hold the wakelock,
2071 // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
2072 // is called again for the same fd that produced the event.
2073 // Thus the system can only sleep if there are no events pending or
2074 // currently being processed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002075 //
2076 // The timeout is advisory only. If the device is asleep, it will not wake just to
2077 // service the timeout.
2078 mPendingEventIndex = 0;
2079
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01002080 mLock.unlock(); // release lock before poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08002081
2082 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
2083
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01002084 mLock.lock(); // reacquire lock after poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08002085
2086 if (pollResult == 0) {
2087 // Timed out.
2088 mPendingEventCount = 0;
2089 break;
2090 }
2091
2092 if (pollResult < 0) {
2093 // An error occurred.
2094 mPendingEventCount = 0;
2095
2096 // Sleep after errors to avoid locking up the system.
2097 // Hopefully the error is transient.
2098 if (errno != EINTR) {
2099 ALOGW("poll failed (errno=%d)\n", errno);
2100 usleep(100000);
2101 }
2102 } else {
2103 // Some events occurred.
2104 mPendingEventCount = size_t(pollResult);
2105 }
2106 }
2107
2108 // All done, return the number of events we read.
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002109 return events;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002110}
2111
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08002112std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002113 std::scoped_lock _l(mLock);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08002114
2115 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07002116 if (device == nullptr || !device->videoDevice) {
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08002117 return {};
2118 }
2119 return device->videoDevice->consumeFrames();
2120}
2121
Michael Wrightd02c5b62014-02-10 15:10:22 -08002122void EventHub::wake() {
2123 ALOGV("wake() called");
2124
2125 ssize_t nWrite;
2126 do {
2127 nWrite = write(mWakeWritePipeFd, "W", 1);
2128 } while (nWrite == -1 && errno == EINTR);
2129
2130 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002131 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002132 }
2133}
2134
2135void EventHub::scanDevicesLocked() {
Usama Arifb27c8e62021-06-03 16:44:09 +01002136 status_t result;
2137 std::error_code errorCode;
2138
2139 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
2140 result = scanDirLocked(DEVICE_INPUT_PATH);
2141 if (result < 0) {
2142 ALOGE("scan dir failed for %s", DEVICE_INPUT_PATH);
2143 }
2144 } else {
2145 if (errorCode) {
2146 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
2147 errorCode.message().c_str());
2148 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002149 }
Philip Quinn39b81682019-01-09 22:20:39 -08002150 if (isV4lScanningEnabled()) {
Usama Arifb27c8e62021-06-03 16:44:09 +01002151 result = scanVideoDirLocked(DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08002152 if (result != OK) {
Usama Arifb27c8e62021-06-03 16:44:09 +01002153 ALOGE("scan video dir failed for %s", DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08002154 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002155 }
Chris Ye989bb932020-07-04 16:18:59 -07002156 if (mDevices.find(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) == mDevices.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002157 createVirtualKeyboardLocked();
2158 }
2159}
2160
2161// ----------------------------------------------------------------------------
2162
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002163status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002164 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002165 struct epoll_event eventItem = {};
2166 eventItem.events = EPOLLIN | EPOLLWAKEUP;
2167 eventItem.data.fd = fd;
2168 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
2169 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002170 return -errno;
2171 }
2172 return OK;
2173}
2174
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002175status_t EventHub::unregisterFdFromEpoll(int fd) {
2176 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
2177 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
2178 return -errno;
2179 }
2180 return OK;
2181}
2182
Chris Ye989bb932020-07-04 16:18:59 -07002183status_t EventHub::registerDeviceForEpollLocked(Device& device) {
2184 status_t result = registerFdForEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002185 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07002186 ALOGE("Could not add input device fd to epoll for device %" PRId32, device.id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002187 return result;
2188 }
Chris Ye989bb932020-07-04 16:18:59 -07002189 if (device.videoDevice) {
2190 registerVideoDeviceForEpollLocked(*device.videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002191 }
2192 return result;
2193}
2194
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002195void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
2196 status_t result = registerFdForEpoll(videoDevice.getFd());
2197 if (result != OK) {
2198 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
2199 }
2200}
2201
Chris Ye989bb932020-07-04 16:18:59 -07002202status_t EventHub::unregisterDeviceFromEpollLocked(Device& device) {
2203 if (device.hasValidFd()) {
2204 status_t result = unregisterFdFromEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002205 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07002206 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device.id);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002207 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002208 }
2209 }
Chris Ye989bb932020-07-04 16:18:59 -07002210 if (device.videoDevice) {
2211 unregisterVideoDeviceFromEpollLocked(*device.videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002212 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002213 return OK;
2214}
2215
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002216void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
2217 if (videoDevice.hasValidFd()) {
2218 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
2219 if (result != OK) {
2220 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002221 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002222 }
2223 }
2224}
2225
Chris Yed3fef462021-03-07 17:10:08 -08002226void EventHub::reportDeviceAddedForStatisticsLocked(const InputDeviceIdentifier& identifier,
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002227 ftl::Flags<InputDeviceClass> classes) {
Chris Ye657c2f02021-05-25 16:24:37 -07002228 SHA256_CTX ctx;
2229 SHA256_Init(&ctx);
2230 SHA256_Update(&ctx, reinterpret_cast<const uint8_t*>(identifier.uniqueId.c_str()),
2231 identifier.uniqueId.size());
2232 std::array<uint8_t, SHA256_DIGEST_LENGTH> digest;
2233 SHA256_Final(digest.data(), &ctx);
2234
2235 std::string obfuscatedId;
2236 for (size_t i = 0; i < OBFUSCATED_LENGTH; i++) {
2237 obfuscatedId += StringPrintf("%02x", digest[i]);
2238 }
2239
Chris Yed3fef462021-03-07 17:10:08 -08002240 android::util::stats_write(android::util::INPUTDEVICE_REGISTERED, identifier.name.c_str(),
2241 identifier.vendor, identifier.product, identifier.version,
Chris Ye657c2f02021-05-25 16:24:37 -07002242 identifier.bus, obfuscatedId.c_str(), classes.get());
Chris Yed3fef462021-03-07 17:10:08 -08002243}
2244
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002245void EventHub::openDeviceLocked(const std::string& devicePath) {
2246 // If an input device happens to register around the time when EventHub's constructor runs, it
2247 // is possible that the same input event node (for example, /dev/input/event3) will be noticed
2248 // in both 'inotify' callback and also in the 'scanDirLocked' pass. To prevent duplicate devices
2249 // from getting registered, ensure that this path is not already covered by an existing device.
2250 for (const auto& [deviceId, device] : mDevices) {
2251 if (device->path == devicePath) {
2252 return; // device was already registered
2253 }
2254 }
2255
Michael Wrightd02c5b62014-02-10 15:10:22 -08002256 char buffer[80];
2257
Chris Ye8594e192020-07-14 10:34:06 -07002258 ALOGV("Opening device: %s", devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002259
Chris Ye8594e192020-07-14 10:34:06 -07002260 int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002261 if (fd < 0) {
Chris Ye8594e192020-07-14 10:34:06 -07002262 ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002263 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002264 }
2265
2266 InputDeviceIdentifier identifier;
2267
2268 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002269 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Chris Ye8594e192020-07-14 10:34:06 -07002270 ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002271 } else {
2272 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002273 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002274 }
2275
2276 // Check to see if the device is on our excluded list
2277 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002278 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002279 if (identifier.name == item) {
Chris Ye8594e192020-07-14 10:34:06 -07002280 ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002281 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002282 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002283 }
2284 }
2285
2286 // Get device driver version.
2287 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002288 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Chris Ye8594e192020-07-14 10:34:06 -07002289 ALOGE("could not get driver version for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002290 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002291 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002292 }
2293
2294 // Get device identifier.
2295 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002296 if (ioctl(fd, EVIOCGID, &inputId)) {
Chris Ye8594e192020-07-14 10:34:06 -07002297 ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002298 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002299 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002300 }
2301 identifier.bus = inputId.bustype;
2302 identifier.product = inputId.product;
2303 identifier.vendor = inputId.vendor;
2304 identifier.version = inputId.version;
2305
2306 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002307 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
2308 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002309 } else {
2310 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002311 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002312 }
2313
2314 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002315 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
2316 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002317 } else {
2318 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002319 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002320 }
2321
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002322 // Attempt to get the bluetooth address of an input device from the uniqueId.
2323 if (identifier.bus == BUS_BLUETOOTH &&
2324 std::regex_match(identifier.uniqueId,
2325 std::regex("^[A-Fa-f0-9]{2}(?::[A-Fa-f0-9]{2}){5}$"))) {
2326 identifier.bluetoothAddress = identifier.uniqueId;
2327 // The Bluetooth stack requires alphabetic characters to be uppercase in a valid address.
2328 for (auto& c : *identifier.bluetoothAddress) {
2329 c = ::toupper(c);
2330 }
2331 }
2332
Michael Wrightd02c5b62014-02-10 15:10:22 -08002333 // Fill in the descriptor.
2334 assignDescriptorLocked(identifier);
2335
Michael Wrightd02c5b62014-02-10 15:10:22 -08002336 // Allocate device. (The device object takes ownership of the fd at this point.)
2337 int32_t deviceId = mNextDeviceId++;
Prabir Pradhancb42b472022-08-23 16:01:19 +00002338 std::unique_ptr<Device> device =
2339 std::make_unique<Device>(fd, deviceId, devicePath, identifier,
2340 obtainAssociatedDeviceLocked(devicePath));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002341
Chris Ye8594e192020-07-14 10:34:06 -07002342 ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002343 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002344 " vendor %04x\n"
2345 " product %04x\n"
2346 " version %04x\n",
2347 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002348 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
2349 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
2350 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
2351 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002352 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
2353 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002354
2355 // Load the configuration file for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002356 device->loadConfigurationLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002357
2358 // Figure out the kinds of events the device reports.
Chris Ye66fbac32020-07-06 20:36:43 -07002359 device->readDeviceBitMask(EVIOCGBIT(EV_KEY, 0), device->keyBitmask);
2360 device->readDeviceBitMask(EVIOCGBIT(EV_ABS, 0), device->absBitmask);
2361 device->readDeviceBitMask(EVIOCGBIT(EV_REL, 0), device->relBitmask);
2362 device->readDeviceBitMask(EVIOCGBIT(EV_SW, 0), device->swBitmask);
2363 device->readDeviceBitMask(EVIOCGBIT(EV_LED, 0), device->ledBitmask);
2364 device->readDeviceBitMask(EVIOCGBIT(EV_FF, 0), device->ffBitmask);
Chris Yef59a2f42020-10-16 12:55:26 -07002365 device->readDeviceBitMask(EVIOCGBIT(EV_MSC, 0), device->mscBitmask);
Chris Ye66fbac32020-07-06 20:36:43 -07002366 device->readDeviceBitMask(EVIOCGPROP(0), device->propBitmask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002367
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002368 // See if this is a device with keys. This could be full keyboard, or other devices like
2369 // gamepads, joysticks, and styluses with buttons that should generate key presses.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002370 bool haveKeyboardKeys =
Chris Ye66fbac32020-07-06 20:36:43 -07002371 device->keyBitmask.any(0, BTN_MISC) || device->keyBitmask.any(BTN_WHEEL, KEY_MAX + 1);
2372 bool haveGamepadButtons = device->keyBitmask.any(BTN_MISC, BTN_MOUSE) ||
2373 device->keyBitmask.any(BTN_JOYSTICK, BTN_DIGI);
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002374 bool haveStylusButtons = device->keyBitmask.test(BTN_STYLUS) ||
2375 device->keyBitmask.test(BTN_STYLUS2) || device->keyBitmask.test(BTN_STYLUS3);
2376 if (haveKeyboardKeys || haveGamepadButtons || haveStylusButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002377 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002378 }
2379
2380 // See if this is a cursor device such as a trackball or mouse.
Chris Ye66fbac32020-07-06 20:36:43 -07002381 if (device->keyBitmask.test(BTN_MOUSE) && device->relBitmask.test(REL_X) &&
2382 device->relBitmask.test(REL_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002383 device->classes |= InputDeviceClass::CURSOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002384 }
2385
Prabir Pradhana3621852022-10-14 18:57:23 +00002386 // See if the device is specially configured to be of a certain type.
Harry Cuttsf13161a2023-03-08 14:15:49 +00002387 if (device->configuration) {
2388 std::string deviceType = device->configuration->getString("device.type").value_or("");
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07002389 if (deviceType == "rotaryEncoder") {
Chris Ye1b0c7342020-07-28 21:57:03 -07002390 device->classes |= InputDeviceClass::ROTARY_ENCODER;
Prabir Pradhana3621852022-10-14 18:57:23 +00002391 } else if (deviceType == "externalStylus") {
2392 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002393 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002394 }
2395
Michael Wrightd02c5b62014-02-10 15:10:22 -08002396 // See if this is a touch pad.
2397 // Is this a new modern multi-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002398 if (device->absBitmask.test(ABS_MT_POSITION_X) && device->absBitmask.test(ABS_MT_POSITION_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002399 // Some joysticks such as the PS3 controller report axes that conflict
2400 // with the ABS_MT range. Try to confirm that the device really is
2401 // a touch screen.
Chris Ye66fbac32020-07-06 20:36:43 -07002402 if (device->keyBitmask.test(BTN_TOUCH) || !haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002403 device->classes |= (InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT);
Harry Cutts79cc9fa2022-10-28 15:32:39 +00002404 if (device->propBitmask.test(INPUT_PROP_POINTER) &&
2405 !device->keyBitmask.any(BTN_TOOL_PEN, BTN_TOOL_FINGER) && !haveStylusButtons) {
2406 device->classes |= InputDeviceClass::TOUCHPAD;
2407 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002408 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002409 // Is this an old style single-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002410 } else if (device->keyBitmask.test(BTN_TOUCH) && device->absBitmask.test(ABS_X) &&
2411 device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002412 device->classes |= InputDeviceClass::TOUCH;
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002413 // Is this a stylus that reports contact/pressure independently of touch coordinates?
Chris Ye66fbac32020-07-06 20:36:43 -07002414 } else if ((device->absBitmask.test(ABS_PRESSURE) || device->keyBitmask.test(BTN_TOUCH)) &&
2415 !device->absBitmask.test(ABS_X) && !device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002416 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002417 }
2418
2419 // See if this device is a joystick.
2420 // Assumes that joysticks always have gamepad buttons in order to distinguish them
2421 // from other devices such as accelerometers that also have absolute axes.
2422 if (haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002423 auto assumedClasses = device->classes | InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002424 for (int i = 0; i <= ABS_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002425 if (device->absBitmask.test(i) &&
Chris Ye1b0c7342020-07-28 21:57:03 -07002426 (getAbsAxisUsage(i, assumedClasses).test(InputDeviceClass::JOYSTICK))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002427 device->classes = assumedClasses;
2428 break;
2429 }
2430 }
2431 }
2432
Chris Yef59a2f42020-10-16 12:55:26 -07002433 // Check whether this device is an accelerometer.
2434 if (device->propBitmask.test(INPUT_PROP_ACCELEROMETER)) {
2435 device->classes |= InputDeviceClass::SENSOR;
2436 }
2437
Michael Wrightd02c5b62014-02-10 15:10:22 -08002438 // Check whether this device has switches.
2439 for (int i = 0; i <= SW_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002440 if (device->swBitmask.test(i)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002441 device->classes |= InputDeviceClass::SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002442 break;
2443 }
2444 }
2445
2446 // Check whether this device supports the vibrator.
Chris Ye66fbac32020-07-06 20:36:43 -07002447 if (device->ffBitmask.test(FF_RUMBLE)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002448 device->classes |= InputDeviceClass::VIBRATOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002449 }
2450
2451 // Configure virtual keys.
Chris Ye1b0c7342020-07-28 21:57:03 -07002452 if ((device->classes.test(InputDeviceClass::TOUCH))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002453 // Load the virtual keys for the touch screen, if any.
2454 // We do this now so that we can make sure to load the keymap if necessary.
Chris Ye989bb932020-07-04 16:18:59 -07002455 bool success = device->loadVirtualKeyMapLocked();
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06002456 if (success) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002457 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002458 }
2459 }
2460
2461 // Load the key map.
Chris Yef59a2f42020-10-16 12:55:26 -07002462 // We need to do this for joysticks too because the key layout may specify axes, and for
2463 // sensor as well because the key layout may specify the axes to sensor data mapping.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002464 status_t keyMapStatus = NAME_NOT_FOUND;
Chris Yef59a2f42020-10-16 12:55:26 -07002465 if (device->classes.any(InputDeviceClass::KEYBOARD | InputDeviceClass::JOYSTICK |
2466 InputDeviceClass::SENSOR)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002467 // Load the keymap for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002468 keyMapStatus = device->loadKeyMapLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002469 }
2470
2471 // Configure the keyboard, gamepad or virtual keyboard.
Chris Ye1b0c7342020-07-28 21:57:03 -07002472 if (device->classes.test(InputDeviceClass::KEYBOARD)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002473 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002474 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002475 isEligibleBuiltInKeyboard(device->identifier, device->configuration.get(),
2476 &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002477 mBuiltInKeyboardId = device->id;
2478 }
2479
2480 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
Chris Ye989bb932020-07-04 16:18:59 -07002481 if (device->hasKeycodeLocked(AKEYCODE_Q)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002482 device->classes |= InputDeviceClass::ALPHAKEY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002483 }
2484
Prabir Pradhanae10ee62023-05-12 19:44:18 +00002485 // See if this device has a D-pad.
2486 if (std::all_of(DPAD_REQUIRED_KEYCODES.begin(), DPAD_REQUIRED_KEYCODES.end(),
2487 [&](int32_t keycode) { return device->hasKeycodeLocked(keycode); })) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002488 device->classes |= InputDeviceClass::DPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002489 }
2490
2491 // See if this device has a gamepad.
Prabir Pradhanae10ee62023-05-12 19:44:18 +00002492 if (std::any_of(GAMEPAD_KEYCODES.begin(), GAMEPAD_KEYCODES.end(),
2493 [&](int32_t keycode) { return device->hasKeycodeLocked(keycode); })) {
2494 device->classes |= InputDeviceClass::GAMEPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002495 }
Prabir Pradhana3621852022-10-14 18:57:23 +00002496
2497 // See if this device has any stylus buttons that we would want to fuse with touch data.
Prabir Pradhanae10ee62023-05-12 19:44:18 +00002498 if (!device->classes.any(InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT) &&
Prabir Pradhan3c28b942023-08-18 20:02:01 +00002499 !device->classes.any(InputDeviceClass::ALPHAKEY) &&
Prabir Pradhanae10ee62023-05-12 19:44:18 +00002500 std::any_of(STYLUS_BUTTON_KEYCODES.begin(), STYLUS_BUTTON_KEYCODES.end(),
2501 [&](int32_t keycode) { return device->hasKeycodeLocked(keycode); })) {
2502 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Prabir Pradhana3621852022-10-14 18:57:23 +00002503 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002504 }
2505
Vladimir Komsiyskidd438e22024-02-13 11:47:54 +01002506 // See if the device is a rotary encoder with a single scroll axis and nothing else.
2507 if (vd_flags::virtual_rotary() && device->classes == ftl::Flags<InputDeviceClass>(0) &&
2508 device->relBitmask.test(REL_WHEEL) && !device->relBitmask.test(REL_HWHEEL)) {
2509 device->classes |= InputDeviceClass::ROTARY_ENCODER;
2510 }
2511
Michael Wrightd02c5b62014-02-10 15:10:22 -08002512 // If the device isn't recognized as something we handle, don't monitor it.
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002513 if (device->classes == ftl::Flags<InputDeviceClass>(0)) {
Chris Ye8594e192020-07-14 10:34:06 -07002514 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002515 device->identifier.name.c_str());
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002516 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002517 }
2518
Chris Ye3fdbfef2021-01-06 18:45:18 -08002519 // Classify InputDeviceClass::BATTERY.
Prabir Pradhan51894782022-08-23 16:29:10 +00002520 if (device->associatedDevice && !device->associatedDevice->batteryInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002521 device->classes |= InputDeviceClass::BATTERY;
2522 }
Kim Low03ea0352020-11-06 12:45:07 -08002523
Chris Ye3fdbfef2021-01-06 18:45:18 -08002524 // Classify InputDeviceClass::LIGHT.
Prabir Pradhan51894782022-08-23 16:29:10 +00002525 if (device->associatedDevice && !device->associatedDevice->lightInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002526 device->classes |= InputDeviceClass::LIGHT;
Kim Low03ea0352020-11-06 12:45:07 -08002527 }
2528
Tim Kilbourn063ff532015-04-08 10:26:18 -07002529 // Determine whether the device has a mic.
Chris Ye989bb932020-07-04 16:18:59 -07002530 if (device->deviceHasMicLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002531 device->classes |= InputDeviceClass::MIC;
Tim Kilbourn063ff532015-04-08 10:26:18 -07002532 }
2533
Michael Wrightd02c5b62014-02-10 15:10:22 -08002534 // Determine whether the device is external or internal.
Chris Ye989bb932020-07-04 16:18:59 -07002535 if (device->isExternalDeviceLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002536 device->classes |= InputDeviceClass::EXTERNAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002537 }
2538
Chris Ye1b0c7342020-07-28 21:57:03 -07002539 if (device->classes.any(InputDeviceClass::JOYSTICK | InputDeviceClass::DPAD) &&
2540 device->classes.test(InputDeviceClass::GAMEPAD)) {
Chris Ye989bb932020-07-04 16:18:59 -07002541 device->controllerNumber = getNextControllerNumberLocked(device->identifier.name);
2542 device->setLedForControllerLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002543 }
2544
Chris Ye989bb932020-07-04 16:18:59 -07002545 if (registerDeviceForEpollLocked(*device) != OK) {
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002546 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002547 }
2548
Chris Ye989bb932020-07-04 16:18:59 -07002549 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002550
Chris Ye1b0c7342020-07-28 21:57:03 -07002551 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=%s, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002552 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Chris Ye1b0c7342020-07-28 21:57:03 -07002553 deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(),
2554 device->classes.string().c_str(), device->configurationFile.c_str(),
2555 device->keyMap.keyLayoutFile.c_str(), device->keyMap.keyCharacterMapFile.c_str(),
2556 toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002557
Chris Ye989bb932020-07-04 16:18:59 -07002558 addDeviceLocked(std::move(device));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002559}
2560
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002561void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
2562 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
2563 if (!videoDevice) {
2564 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
2565 return;
2566 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002567 // Transfer ownership of this video device to a matching input device
Chris Ye989bb932020-07-04 16:18:59 -07002568 for (const auto& [id, device] : mDevices) {
Chris Yed3fef462021-03-07 17:10:08 -08002569 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002570 return; // 'device' now owns 'videoDevice'
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002571 }
2572 }
2573
2574 // Couldn't find a matching input device, so just add it to a temporary holding queue.
2575 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002576 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002577 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002578 mUnattachedVideoDevices.push_back(std::move(videoDevice));
2579}
2580
Chris Yed3fef462021-03-07 17:10:08 -08002581bool EventHub::tryAddVideoDeviceLocked(EventHub::Device& device,
2582 std::unique_ptr<TouchVideoDevice>& videoDevice) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002583 if (videoDevice->getName() != device.identifier.name) {
2584 return false;
2585 }
2586 device.videoDevice = std::move(videoDevice);
2587 if (device.enabled) {
2588 registerVideoDeviceForEpollLocked(*device.videoDevice);
2589 }
2590 return true;
2591}
2592
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002593bool EventHub::isDeviceEnabled(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00002594 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002595 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002596 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002597 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2598 return false;
2599 }
2600 return device->enabled;
2601}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002602
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002603status_t EventHub::enableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002604 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002605 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002606 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002607 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2608 return BAD_VALUE;
2609 }
2610 if (device->enabled) {
2611 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
2612 return OK;
2613 }
2614 status_t result = device->enable();
2615 if (result != OK) {
2616 ALOGE("Failed to enable device %" PRId32, deviceId);
2617 return result;
2618 }
2619
Chris Ye989bb932020-07-04 16:18:59 -07002620 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002621
Chris Ye989bb932020-07-04 16:18:59 -07002622 return registerDeviceForEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002623}
2624
2625status_t EventHub::disableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002626 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002627 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002628 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002629 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2630 return BAD_VALUE;
2631 }
2632 if (!device->enabled) {
2633 ALOGW("Duplicate call to %s, input device already disabled", __func__);
2634 return OK;
2635 }
Chris Ye989bb932020-07-04 16:18:59 -07002636 unregisterDeviceFromEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002637 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002638}
2639
Vaibhav Devmurari5fc7d852023-03-17 18:43:33 +00002640// TODO(b/274755573): Shift to uevent handling on native side and remove this method
2641// Currently using Java UEventObserver to trigger this which uses UEvent infrastructure that uses a
2642// NETLINK socket to observe UEvents. We can create similar infrastructure on Eventhub side to
2643// directly observe UEvents instead of triggering from Java side.
2644void EventHub::sysfsNodeChanged(const std::string& sysfsNodePath) {
2645 std::scoped_lock _l(mLock);
2646
2647 // Check in opening devices
2648 for (auto it = mOpeningDevices.begin(); it != mOpeningDevices.end(); it++) {
2649 std::unique_ptr<Device>& device = *it;
2650 if (device->associatedDevice &&
2651 sysfsNodePath.find(device->associatedDevice->sysfsRootPath.string()) !=
2652 std::string::npos &&
2653 device->associatedDevice->isChanged()) {
2654 it = mOpeningDevices.erase(it);
2655 openDeviceLocked(device->path);
2656 }
2657 }
2658
2659 // Check in already added device
2660 std::vector<Device*> devicesToReopen;
2661 for (const auto& [id, device] : mDevices) {
2662 if (device->associatedDevice &&
2663 sysfsNodePath.find(device->associatedDevice->sysfsRootPath.string()) !=
2664 std::string::npos &&
2665 device->associatedDevice->isChanged()) {
2666 devicesToReopen.push_back(device.get());
2667 }
2668 }
2669 for (const auto& device : devicesToReopen) {
2670 closeDeviceLocked(*device);
2671 openDeviceLocked(device->path);
2672 }
2673 devicesToReopen.clear();
2674}
2675
Michael Wrightd02c5b62014-02-10 15:10:22 -08002676void EventHub::createVirtualKeyboardLocked() {
2677 InputDeviceIdentifier identifier;
2678 identifier.name = "Virtual";
2679 identifier.uniqueId = "<virtual>";
2680 assignDescriptorLocked(identifier);
2681
Chris Ye989bb932020-07-04 16:18:59 -07002682 std::unique_ptr<Device> device =
2683 std::make_unique<Device>(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
Harry Cutts33476232023-01-30 19:57:29 +00002684 identifier, /*associatedDevice=*/nullptr);
Chris Ye1b0c7342020-07-28 21:57:03 -07002685 device->classes = InputDeviceClass::KEYBOARD | InputDeviceClass::ALPHAKEY |
2686 InputDeviceClass::DPAD | InputDeviceClass::VIRTUAL;
Chris Ye989bb932020-07-04 16:18:59 -07002687 device->loadKeyMapLocked();
2688 addDeviceLocked(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002689}
2690
Chris Ye989bb932020-07-04 16:18:59 -07002691void EventHub::addDeviceLocked(std::unique_ptr<Device> device) {
Chris Yed3fef462021-03-07 17:10:08 -08002692 reportDeviceAddedForStatisticsLocked(device->identifier, device->classes);
Chris Ye989bb932020-07-04 16:18:59 -07002693 mOpeningDevices.push_back(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002694}
2695
Chris Ye989bb932020-07-04 16:18:59 -07002696int32_t EventHub::getNextControllerNumberLocked(const std::string& name) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002697 if (mControllerNumbers.isFull()) {
2698 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Chris Ye989bb932020-07-04 16:18:59 -07002699 name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002700 return 0;
2701 }
2702 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
2703 // one
2704 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
2705}
2706
Chris Ye989bb932020-07-04 16:18:59 -07002707void EventHub::releaseControllerNumberLocked(int32_t num) {
2708 if (num > 0) {
2709 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002710 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002711}
2712
Chris Ye8594e192020-07-14 10:34:06 -07002713void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002714 Device* device = getDeviceByPathLocked(devicePath);
Chris Ye989bb932020-07-04 16:18:59 -07002715 if (device != nullptr) {
2716 closeDeviceLocked(*device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002717 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002718 }
Chris Ye8594e192020-07-14 10:34:06 -07002719 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002720}
2721
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002722/**
2723 * Find the video device by filename, and close it.
2724 * The video device is closed by path during an inotify event, where we don't have the
2725 * additional context about the video device fd, or the associated input device.
2726 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002727void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002728 // A video device may be owned by an existing input device, or it may be stored in
2729 // the mUnattachedVideoDevices queue. Check both locations.
Chris Ye989bb932020-07-04 16:18:59 -07002730 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002731 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002732 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002733 device->videoDevice = nullptr;
2734 return;
2735 }
2736 }
Siarhei Vishniakouf47c339e2021-12-30 11:22:26 -08002737 std::erase_if(mUnattachedVideoDevices,
2738 [&devicePath](const std::unique_ptr<TouchVideoDevice>& videoDevice) {
2739 return videoDevice->getPath() == devicePath;
2740 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08002741}
2742
2743void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002744 mUnattachedVideoDevices.clear();
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002745 while (!mDevices.empty()) {
2746 closeDeviceLocked(*(mDevices.begin()->second));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002747 }
2748}
2749
Chris Ye989bb932020-07-04 16:18:59 -07002750void EventHub::closeDeviceLocked(Device& device) {
2751 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=%s", device.path.c_str(),
2752 device.identifier.name.c_str(), device.id, device.fd, device.classes.string().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002753
Chris Ye989bb932020-07-04 16:18:59 -07002754 if (device.id == mBuiltInKeyboardId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002755 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Chris Ye989bb932020-07-04 16:18:59 -07002756 device.path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002757 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
2758 }
2759
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002760 unregisterDeviceFromEpollLocked(device);
Chris Ye989bb932020-07-04 16:18:59 -07002761 if (device.videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002762 // This must be done after the video device is removed from epoll
Chris Ye989bb932020-07-04 16:18:59 -07002763 mUnattachedVideoDevices.push_back(std::move(device.videoDevice));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002764 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002765
Chris Ye989bb932020-07-04 16:18:59 -07002766 releaseControllerNumberLocked(device.controllerNumber);
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002767 device.controllerNumber = 0;
Chris Ye989bb932020-07-04 16:18:59 -07002768 device.close();
Chris Ye989bb932020-07-04 16:18:59 -07002769 mClosingDevices.push_back(std::move(mDevices[device.id]));
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002770
Chris Ye989bb932020-07-04 16:18:59 -07002771 mDevices.erase(device.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002772}
2773
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002774base::Result<void> EventHub::readNotifyLocked() {
2775 static constexpr auto EVENT_SIZE = static_cast<ssize_t>(sizeof(inotify_event));
2776 uint8_t eventBuffer[512];
2777 ssize_t sizeRead;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002778
2779 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002780 do {
2781 sizeRead = read(mINotifyFd, eventBuffer, sizeof(eventBuffer));
2782 } while (sizeRead < 0 && errno == EINTR);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002783
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002784 if (sizeRead < EVENT_SIZE) return Errorf("could not get event, %s", strerror(errno));
2785
2786 for (ssize_t eventPos = 0; sizeRead >= EVENT_SIZE;) {
2787 const inotify_event* event;
2788 event = (const inotify_event*)(eventBuffer + eventPos);
2789 if (event->len == 0) continue;
2790
2791 handleNotifyEventLocked(*event);
2792
2793 const ssize_t eventSize = EVENT_SIZE + event->len;
2794 sizeRead -= eventSize;
2795 eventPos += eventSize;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002796 }
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002797 return {};
2798}
2799
2800void EventHub::handleNotifyEventLocked(const inotify_event& event) {
2801 if (event.wd == mDeviceInputWd) {
2802 std::string filename = std::string(DEVICE_INPUT_PATH) + "/" + event.name;
2803 if (event.mask & IN_CREATE) {
2804 openDeviceLocked(filename);
2805 } else {
2806 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
2807 closeDeviceByPathLocked(filename);
2808 }
2809 } else if (event.wd == mDeviceWd) {
2810 if (isV4lTouchNode(event.name)) {
2811 std::string filename = std::string(DEVICE_PATH) + "/" + event.name;
2812 if (event.mask & IN_CREATE) {
2813 openVideoDeviceLocked(filename);
2814 } else {
2815 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
2816 closeVideoDeviceByPathLocked(filename);
2817 }
2818 } else if (strcmp(event.name, "input") == 0 && event.mask & IN_CREATE) {
2819 addDeviceInputInotify();
2820 }
2821 } else {
2822 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event.wd);
2823 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002824}
2825
Chris Ye8594e192020-07-14 10:34:06 -07002826status_t EventHub::scanDirLocked(const std::string& dirname) {
2827 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2828 openDeviceLocked(entry.path());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002829 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002830 return 0;
2831}
2832
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002833/**
2834 * Look for all dirname/v4l-touch* devices, and open them.
2835 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002836status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Chris Ye8594e192020-07-14 10:34:06 -07002837 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2838 if (isV4lTouchNode(entry.path())) {
2839 ALOGI("Found touch video device %s", entry.path().c_str());
2840 openVideoDeviceLocked(entry.path());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002841 }
2842 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002843 return OK;
2844}
2845
Michael Wrightd02c5b62014-02-10 15:10:22 -08002846void EventHub::requestReopenDevices() {
2847 ALOGV("requestReopenDevices() called");
2848
Chris Ye87143712020-11-10 05:05:58 +00002849 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002850 mNeedToReopenDevices = true;
2851}
2852
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002853void EventHub::dump(std::string& dump) const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002854 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002855
2856 { // acquire lock
Chris Ye87143712020-11-10 05:05:58 +00002857 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002858
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002859 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002860
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002861 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002862
Chris Ye989bb932020-07-04 16:18:59 -07002863 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002864 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002865 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002866 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002867 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002868 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002869 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002870 }
Chris Ye1b0c7342020-07-28 21:57:03 -07002871 dump += StringPrintf(INDENT3 "Classes: %s\n", device->classes.string().c_str());
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002872 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002873 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002874 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
2875 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002876 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002877 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002878 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002879 "product=0x%04x, version=0x%04x, bluetoothAddress=%s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002880 device->identifier.bus, device->identifier.vendor,
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002881 device->identifier.product, device->identifier.version,
2882 toString(device->identifier.bluetoothAddress).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002883 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002884 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002885 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002886 device->keyMap.keyCharacterMapFile.c_str());
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00002887 if (device->associatedDevice && device->associatedDevice->layoutInfo) {
2888 dump += StringPrintf(INDENT3 "LanguageTag: %s\n",
2889 device->associatedDevice->layoutInfo->languageTag.c_str());
2890 dump += StringPrintf(INDENT3 "LayoutType: %s\n",
2891 device->associatedDevice->layoutInfo->layoutType.c_str());
2892 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002893 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002894 device->configurationFile.c_str());
Prabir Pradhan51894782022-08-23 16:29:10 +00002895 dump += StringPrintf(INDENT3 "VideoDevice: %s\n",
2896 device->videoDevice ? device->videoDevice->dump().c_str()
2897 : "<none>");
2898 dump += StringPrintf(INDENT3 "SysfsDevicePath: %s\n",
2899 device->associatedDevice
2900 ? device->associatedDevice->sysfsRootPath.c_str()
2901 : "<none>");
Prabir Pradhan955b6132023-07-14 19:44:34 +00002902 if (device->keyBitmask.any(0, KEY_MAX + 1)) {
2903 const auto pressedKeys = device->keyState.dumpSetIndices(", ", [](int i) {
2904 return InputEventLookup::getLinuxEvdevLabel(EV_KEY, i, 1).code;
2905 });
2906 dump += StringPrintf(INDENT3 "KeyState (pressed): %s\n", pressedKeys.c_str());
2907 }
2908 if (device->swBitmask.any(0, SW_MAX + 1)) {
2909 const auto pressedSwitches = device->swState.dumpSetIndices(", ", [](int i) {
2910 return InputEventLookup::getLinuxEvdevLabel(EV_SW, i, 1).code;
2911 });
2912 dump += StringPrintf(INDENT3 "SwState (pressed): %s\n", pressedSwitches.c_str());
2913 }
2914 if (!device->absState.empty()) {
2915 std::string axisValues;
2916 for (const auto& [axis, state] : device->absState) {
2917 if (!axisValues.empty()) {
2918 axisValues += ", ";
2919 }
2920 axisValues += StringPrintf("%s=%d",
2921 InputEventLookup::getLinuxEvdevLabel(EV_ABS, axis, 0)
2922 .code.c_str(),
2923 state.value);
2924 }
2925 dump += INDENT3 "AbsState: " + axisValues + "\n";
2926 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002927 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002928
2929 dump += INDENT "Unattached video devices:\n";
2930 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
2931 dump += INDENT2 + videoDevice->dump() + "\n";
2932 }
2933 if (mUnattachedVideoDevices.empty()) {
2934 dump += INDENT2 "<none>\n";
2935 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002936 } // release lock
2937}
2938
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002939void EventHub::monitor() const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002940 // Acquire and release the lock to ensure that the event hub has not deadlocked.
Chris Ye1c2e0892020-11-30 21:41:44 -08002941 std::unique_lock<std::mutex> lock(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002942}
2943
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00002944std::string EventHub::AssociatedDevice::dump() const {
2945 return StringPrintf("path=%s, numBatteries=%zu, numLight=%zu", sysfsRootPath.c_str(),
2946 batteryInfos.size(), lightInfos.size());
2947}
2948
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002949} // namespace android