blob: 013ef862ad3c180989e5c51443e3d820bdc2b3d1 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2005 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070017#include <assert.h>
18#include <dirent.h>
19#include <errno.h>
20#include <fcntl.h>
21#include <inttypes.h>
Colin Cross5b799302022-10-18 21:52:41 -070022#include <linux/ioctl.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070023#include <memory.h>
24#include <stdint.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +010028#include <sys/capability.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070029#include <sys/epoll.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070030#include <sys/inotify.h>
31#include <sys/ioctl.h>
Kim Low03ea0352020-11-06 12:45:07 -080032#include <sys/stat.h>
33#include <sys/sysmacros.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070034#include <unistd.h>
35
Vladimir Komsiyskidd438e22024-02-13 11:47:54 +010036#include <android_companion_virtualdevice_flags.h>
37
Michael Wrightd02c5b62014-02-10 15:10:22 -080038#define LOG_TAG "EventHub"
39
40// #define LOG_NDEBUG 0
Kim Low03ea0352020-11-06 12:45:07 -080041#include <android-base/file.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080042#include <android-base/stringprintf.h>
Chris Yed3fef462021-03-07 17:10:08 -080043#include <android-base/strings.h>
Philip Quinn39b81682019-01-09 22:20:39 -080044#include <cutils/properties.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080045#include <ftl/enum.h>
Harry Cuttsd6a3fb52024-10-23 09:48:55 +000046#include <input/InputEventLabels.h>
Chris Ye8594e192020-07-14 10:34:06 -070047#include <input/KeyCharacterMap.h>
48#include <input/KeyLayoutMap.h>
Prabir Pradhan07525ef2022-10-03 21:51:26 +000049#include <input/PrintTools.h>
Chris Ye8594e192020-07-14 10:34:06 -070050#include <input/VirtualKeyMap.h>
Dan Albert677d87e2014-06-16 17:31:28 -070051#include <openssl/sha.h>
Chris Yed3fef462021-03-07 17:10:08 -080052#include <statslog.h>
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070053#include <utils/Errors.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080054#include <utils/Log.h>
55#include <utils/Timers.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080056
Chris Ye8594e192020-07-14 10:34:06 -070057#include <filesystem>
Harry Cuttsf13161a2023-03-08 14:15:49 +000058#include <optional>
Chris Ye3fdbfef2021-01-06 18:45:18 -080059#include <regex>
Prabir Pradhancb42b472022-08-23 16:01:19 +000060#include <utility>
Chris Ye8594e192020-07-14 10:34:06 -070061
62#include "EventHub.h"
Michael Wrightd02c5b62014-02-10 15:10:22 -080063
Prabir Pradhanae10ee62023-05-12 19:44:18 +000064#include "KeyCodeClassifications.h"
65
Michael Wrightd02c5b62014-02-10 15:10:22 -080066#define INDENT " "
67#define INDENT2 " "
68#define INDENT3 " "
69
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080070using android::base::StringPrintf;
71
Michael Wrightd02c5b62014-02-10 15:10:22 -080072namespace android {
73
Vladimir Komsiyskidd438e22024-02-13 11:47:54 +010074namespace vd_flags = android::companion::virtualdevice::flags;
75
Dominik Laskowski2f01d772022-03-23 16:01:29 -070076using namespace ftl::flag_operators;
77
Usama Arifb27c8e62021-06-03 16:44:09 +010078static const char* DEVICE_INPUT_PATH = "/dev/input";
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080079// v4l2 devices go directly into /dev
Usama Arifb27c8e62021-06-03 16:44:09 +010080static const char* DEVICE_PATH = "/dev";
Michael Wrightd02c5b62014-02-10 15:10:22 -080081
Chris Ye657c2f02021-05-25 16:24:37 -070082static constexpr size_t OBFUSCATED_LENGTH = 8;
83
Chris Ye87143712020-11-10 05:05:58 +000084static constexpr int32_t FF_STRONG_MAGNITUDE_CHANNEL_IDX = 0;
85static constexpr int32_t FF_WEAK_MAGNITUDE_CHANNEL_IDX = 1;
Chris Ye6393a262020-08-04 19:41:36 -070086
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -070087static constexpr size_t EVENT_BUFFER_SIZE = 256;
88
Chris Yee2b1e5c2021-03-10 22:45:12 -080089// Mapping for input battery class node IDs lookup.
90// https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
91static const std::unordered_map<std::string, InputBatteryClass> BATTERY_CLASSES =
92 {{"capacity", InputBatteryClass::CAPACITY},
93 {"capacity_level", InputBatteryClass::CAPACITY_LEVEL},
94 {"status", InputBatteryClass::STATUS}};
95
96// Mapping for input battery class node names lookup.
97// https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
98static const std::unordered_map<InputBatteryClass, std::string> BATTERY_NODES =
99 {{InputBatteryClass::CAPACITY, "capacity"},
100 {InputBatteryClass::CAPACITY_LEVEL, "capacity_level"},
101 {InputBatteryClass::STATUS, "status"}};
102
Kim Low03ea0352020-11-06 12:45:07 -0800103// must be kept in sync with definitions in kernel /drivers/power/supply/power_supply_sysfs.c
104static const std::unordered_map<std::string, int32_t> BATTERY_STATUS =
105 {{"Unknown", BATTERY_STATUS_UNKNOWN},
106 {"Charging", BATTERY_STATUS_CHARGING},
107 {"Discharging", BATTERY_STATUS_DISCHARGING},
108 {"Not charging", BATTERY_STATUS_NOT_CHARGING},
109 {"Full", BATTERY_STATUS_FULL}};
110
111// Mapping taken from
112// https://gitlab.freedesktop.org/upower/upower/-/blob/master/src/linux/up-device-supply.c#L484
113static const std::unordered_map<std::string, int32_t> BATTERY_LEVEL = {{"Critical", 5},
114 {"Low", 10},
115 {"Normal", 55},
116 {"High", 70},
117 {"Full", 100},
118 {"Unknown", 50}};
119
Chris Ye3fdbfef2021-01-06 18:45:18 -0800120// Mapping for input led class node names lookup.
121// https://www.kernel.org/doc/html/latest/leds/leds-class.html
122static const std::unordered_map<std::string, InputLightClass> LIGHT_CLASSES =
123 {{"red", InputLightClass::RED},
124 {"green", InputLightClass::GREEN},
125 {"blue", InputLightClass::BLUE},
126 {"global", InputLightClass::GLOBAL},
127 {"brightness", InputLightClass::BRIGHTNESS},
128 {"multi_index", InputLightClass::MULTI_INDEX},
129 {"multi_intensity", InputLightClass::MULTI_INTENSITY},
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000130 {"max_brightness", InputLightClass::MAX_BRIGHTNESS},
DingYong99f2c3c2023-12-20 15:46:06 +0800131 {"kbd_backlight", InputLightClass::KEYBOARD_BACKLIGHT},
DingYongffe24cc2024-08-15 08:24:02 +0000132 {"mic_mute", InputLightClass::KEYBOARD_MIC_MUTE},
133 {"mute", InputLightClass::KEYBOARD_VOLUME_MUTE}};
Chris Ye3fdbfef2021-01-06 18:45:18 -0800134
135// Mapping for input multicolor led class node names.
136// https://www.kernel.org/doc/html/latest/leds/leds-class-multicolor.html
137static const std::unordered_map<InputLightClass, std::string> LIGHT_NODES =
138 {{InputLightClass::BRIGHTNESS, "brightness"},
139 {InputLightClass::MULTI_INDEX, "multi_index"},
140 {InputLightClass::MULTI_INTENSITY, "multi_intensity"}};
141
142// Mapping for light color name and the light color
143const std::unordered_map<std::string, LightColor> LIGHT_COLORS = {{"red", LightColor::RED},
144 {"green", LightColor::GREEN},
145 {"blue", LightColor::BLUE}};
146
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000147// Mapping for country code to Layout info.
148// See bCountryCode in 6.2.1 of https://usb.org/sites/default/files/hid1_11.pdf.
149const std::unordered_map<std::int32_t, RawLayoutInfo> LAYOUT_INFOS =
150 {{0, RawLayoutInfo{.languageTag = "", .layoutType = ""}}, // NOT_SUPPORTED
151 {1, RawLayoutInfo{.languageTag = "ar-Arab", .layoutType = ""}}, // ARABIC
152 {2, RawLayoutInfo{.languageTag = "fr-BE", .layoutType = ""}}, // BELGIAN
153 {3, RawLayoutInfo{.languageTag = "fr-CA", .layoutType = ""}}, // CANADIAN_BILINGUAL
154 {4, RawLayoutInfo{.languageTag = "fr-CA", .layoutType = ""}}, // CANADIAN_FRENCH
155 {5, RawLayoutInfo{.languageTag = "cs", .layoutType = ""}}, // CZECH_REPUBLIC
156 {6, RawLayoutInfo{.languageTag = "da", .layoutType = ""}}, // DANISH
157 {7, RawLayoutInfo{.languageTag = "fi", .layoutType = ""}}, // FINNISH
158 {8, RawLayoutInfo{.languageTag = "fr-FR", .layoutType = ""}}, // FRENCH
159 {9, RawLayoutInfo{.languageTag = "de", .layoutType = ""}}, // GERMAN
160 {10, RawLayoutInfo{.languageTag = "el", .layoutType = ""}}, // GREEK
161 {11, RawLayoutInfo{.languageTag = "iw", .layoutType = ""}}, // HEBREW
162 {12, RawLayoutInfo{.languageTag = "hu", .layoutType = ""}}, // HUNGARY
163 {13, RawLayoutInfo{.languageTag = "en", .layoutType = "extended"}}, // INTERNATIONAL (ISO)
164 {14, RawLayoutInfo{.languageTag = "it", .layoutType = ""}}, // ITALIAN
165 {15, RawLayoutInfo{.languageTag = "ja", .layoutType = ""}}, // JAPAN
166 {16, RawLayoutInfo{.languageTag = "ko", .layoutType = ""}}, // KOREAN
167 {17, RawLayoutInfo{.languageTag = "es-419", .layoutType = ""}}, // LATIN_AMERICA
168 {18, RawLayoutInfo{.languageTag = "nl", .layoutType = ""}}, // DUTCH
169 {19, RawLayoutInfo{.languageTag = "nb", .layoutType = ""}}, // NORWEGIAN
170 {20, RawLayoutInfo{.languageTag = "fa", .layoutType = ""}}, // PERSIAN
171 {21, RawLayoutInfo{.languageTag = "pl", .layoutType = ""}}, // POLAND
172 {22, RawLayoutInfo{.languageTag = "pt", .layoutType = ""}}, // PORTUGUESE
173 {23, RawLayoutInfo{.languageTag = "ru", .layoutType = ""}}, // RUSSIA
174 {24, RawLayoutInfo{.languageTag = "sk", .layoutType = ""}}, // SLOVAKIA
175 {25, RawLayoutInfo{.languageTag = "es-ES", .layoutType = ""}}, // SPANISH
176 {26, RawLayoutInfo{.languageTag = "sv", .layoutType = ""}}, // SWEDISH
177 {27, RawLayoutInfo{.languageTag = "fr-CH", .layoutType = ""}}, // SWISS_FRENCH
178 {28, RawLayoutInfo{.languageTag = "de-CH", .layoutType = ""}}, // SWISS_GERMAN
179 {29, RawLayoutInfo{.languageTag = "de-CH", .layoutType = ""}}, // SWITZERLAND
180 {30, RawLayoutInfo{.languageTag = "zh-TW", .layoutType = ""}}, // TAIWAN
181 {31, RawLayoutInfo{.languageTag = "tr", .layoutType = "turkish_q"}}, // TURKISH_Q
182 {32, RawLayoutInfo{.languageTag = "en-GB", .layoutType = ""}}, // UK
183 {33, RawLayoutInfo{.languageTag = "en-US", .layoutType = ""}}, // US
184 {34, RawLayoutInfo{.languageTag = "", .layoutType = ""}}, // YUGOSLAVIA
185 {35, RawLayoutInfo{.languageTag = "tr", .layoutType = "turkish_f"}}}; // TURKISH_F
186
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100187static std::string sha1(const std::string& in) {
Dan Albert677d87e2014-06-16 17:31:28 -0700188 SHA_CTX ctx;
189 SHA1_Init(&ctx);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100190 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
Dan Albert677d87e2014-06-16 17:31:28 -0700191 u_char digest[SHA_DIGEST_LENGTH];
192 SHA1_Final(digest, &ctx);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800193
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100194 std::string out;
Dan Albert677d87e2014-06-16 17:31:28 -0700195 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100196 out += StringPrintf("%02x", digest[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800197 }
198 return out;
199}
200
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800201/**
202 * Return true if name matches "v4l-touch*"
203 */
Chris Ye8594e192020-07-14 10:34:06 -0700204static bool isV4lTouchNode(std::string name) {
205 return name.find("v4l-touch") != std::string::npos;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800206}
207
Philip Quinn39b81682019-01-09 22:20:39 -0800208/**
209 * Returns true if V4L devices should be scanned.
210 *
211 * The system property ro.input.video_enabled can be used to control whether
212 * EventHub scans and opens V4L devices. As V4L does not support multiple
213 * clients, EventHub effectively blocks access to these devices when it opens
Siarhei Vishniakou29f88492019-04-05 14:11:43 -0700214 * them.
215 *
216 * Setting this to "false" would prevent any video devices from being discovered and
217 * associated with input devices.
218 *
219 * This property can be used as follows:
220 * 1. To turn off features that are dependent on video device presence.
221 * 2. During testing and development, to allow other clients to read video devices
222 * directly from /dev.
Philip Quinn39b81682019-01-09 22:20:39 -0800223 */
224static bool isV4lScanningEnabled() {
Harry Cutts33476232023-01-30 19:57:29 +0000225 return property_get_bool("ro.input.video_enabled", /*default_value=*/true);
Philip Quinn39b81682019-01-09 22:20:39 -0800226}
227
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800228static nsecs_t processEventTimestamp(const struct input_event& event) {
229 // Use the time specified in the event instead of the current time
230 // so that downstream code can get more accurate estimates of
231 // event dispatch latency from the time the event is enqueued onto
232 // the evdev client buffer.
233 //
234 // The event's timestamp fortuitously uses the same monotonic clock
235 // time base as the rest of Android. The kernel event device driver
236 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
237 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
238 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
239 // system call that also queries ktime_get_ts().
240
Colin Cross5b799302022-10-18 21:52:41 -0700241 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.input_event_sec) +
242 microseconds_to_nanoseconds(event.input_event_usec);
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800243 return inputEventTime;
244}
245
Kim Low03ea0352020-11-06 12:45:07 -0800246/**
Prabir Pradhancb42b472022-08-23 16:01:19 +0000247 * Returns the sysfs root path of the input device.
Kim Low03ea0352020-11-06 12:45:07 -0800248 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800249static std::optional<std::filesystem::path> getSysfsRootPath(const char* devicePath) {
Kim Low03ea0352020-11-06 12:45:07 -0800250 std::error_code errorCode;
251
252 // Stat the device path to get the major and minor number of the character file
253 struct stat statbuf;
254 if (stat(devicePath, &statbuf) == -1) {
255 ALOGE("Could not stat device %s due to error: %s.", devicePath, std::strerror(errno));
Chris Ye3fdbfef2021-01-06 18:45:18 -0800256 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800257 }
258
259 unsigned int major_num = major(statbuf.st_rdev);
260 unsigned int minor_num = minor(statbuf.st_rdev);
261
262 // Realpath "/sys/dev/char/{major}:{minor}" to get the sysfs path to the input event
263 auto sysfsPath = std::filesystem::path("/sys/dev/char/");
264 sysfsPath /= std::to_string(major_num) + ":" + std::to_string(minor_num);
265 sysfsPath = std::filesystem::canonical(sysfsPath, errorCode);
266
267 // Make sure nothing went wrong in call to canonical()
268 if (errorCode) {
269 ALOGW("Could not run filesystem::canonical() due to error %d : %s.", errorCode.value(),
270 errorCode.message().c_str());
Chris Ye3fdbfef2021-01-06 18:45:18 -0800271 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800272 }
273
274 // Continue to go up a directory until we reach a directory named "input"
275 while (sysfsPath != "/" && sysfsPath.filename() != "input") {
276 sysfsPath = sysfsPath.parent_path();
277 }
278
279 // Then go up one more and you will be at the sysfs root of the device
280 sysfsPath = sysfsPath.parent_path();
281
282 // Make sure we didn't reach root path and that directory actually exists
283 if (sysfsPath == "/" || !std::filesystem::exists(sysfsPath, errorCode)) {
284 if (errorCode) {
285 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
286 errorCode.message().c_str());
287 }
288
289 // Not found
Chris Ye3fdbfef2021-01-06 18:45:18 -0800290 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800291 }
292
293 return sysfsPath;
294}
295
296/**
Chris Ye3fdbfef2021-01-06 18:45:18 -0800297 * Returns the list of files under a specified path.
Kim Low03ea0352020-11-06 12:45:07 -0800298 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800299static std::vector<std::filesystem::path> allFilesInPath(const std::filesystem::path& path) {
300 std::vector<std::filesystem::path> nodes;
301 std::error_code errorCode;
302 auto iter = std::filesystem::directory_iterator(path, errorCode);
303 while (!errorCode && iter != std::filesystem::directory_iterator()) {
304 nodes.push_back(iter->path());
305 iter++;
306 }
307 return nodes;
308}
309
310/**
311 * Returns the list of files under a specified directory in a sysfs path.
312 * Example:
313 * findSysfsNodes(sysfsRootPath, SysfsClass::LEDS) will return all led nodes under "leds" directory
314 * in the sysfs path.
315 */
316static std::vector<std::filesystem::path> findSysfsNodes(const std::filesystem::path& sysfsRoot,
317 SysfsClass clazz) {
Dominik Laskowski75788452021-02-09 18:51:25 -0800318 std::string nodeStr = ftl::enum_string(clazz);
Chris Ye3fdbfef2021-01-06 18:45:18 -0800319 std::for_each(nodeStr.begin(), nodeStr.end(),
320 [](char& c) { c = std::tolower(static_cast<unsigned char>(c)); });
321 std::vector<std::filesystem::path> nodes;
322 for (auto path = sysfsRoot; path != "/" && nodes.empty(); path = path.parent_path()) {
323 nodes = allFilesInPath(path / nodeStr);
324 }
325 return nodes;
326}
327
328static std::optional<std::array<LightColor, COLOR_NUM>> getColorIndexArray(
329 std::filesystem::path path) {
330 std::string indexStr;
331 if (!base::ReadFileToString(path, &indexStr)) {
332 return std::nullopt;
333 }
334
335 // Parse the multi color LED index file, refer to kernel docs
336 // leds/leds-class-multicolor.html
337 std::regex indexPattern("(red|green|blue)\\s(red|green|blue)\\s(red|green|blue)[\\n]");
338 std::smatch results;
339 std::array<LightColor, COLOR_NUM> colors;
340 if (!std::regex_match(indexStr, results, indexPattern)) {
341 return std::nullopt;
342 }
343
344 for (size_t i = 1; i < results.size(); i++) {
345 const auto it = LIGHT_COLORS.find(results[i].str());
346 if (it != LIGHT_COLORS.end()) {
347 // intensities.emplace(it->second, 0);
348 colors[i - 1] = it->second;
Kim Low03ea0352020-11-06 12:45:07 -0800349 }
350 }
Chris Ye3fdbfef2021-01-06 18:45:18 -0800351 return colors;
Kim Low03ea0352020-11-06 12:45:07 -0800352}
353
Prabir Pradhancb42b472022-08-23 16:01:19 +0000354/**
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000355 * Read country code information exposed through the sysfs path and convert it to Layout info.
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000356 */
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000357static std::optional<RawLayoutInfo> readLayoutConfiguration(
358 const std::filesystem::path& sysfsRootPath) {
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000359 // Check the sysfs root path
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000360 int32_t hidCountryCode = -1;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000361 std::string str;
362 if (base::ReadFileToString(sysfsRootPath / "country", &str)) {
363 hidCountryCode = std::stoi(str, nullptr, 16);
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000364 // Update this condition if new supported country codes are added to HID spec.
Vaibhav Devmurari990ff7b2022-12-22 18:23:21 +0000365 if (hidCountryCode > 35 || hidCountryCode < 0) {
366 ALOGE("HID country code should be in range [0, 35], but for sysfs path %s it was %d",
367 sysfsRootPath.c_str(), hidCountryCode);
Vaibhav Devmurari990ff7b2022-12-22 18:23:21 +0000368 }
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000369 }
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000370 const auto it = LAYOUT_INFOS.find(hidCountryCode);
371 if (it != LAYOUT_INFOS.end()) {
372 return it->second;
373 }
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000374
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000375 return std::nullopt;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000376}
377
378/**
Prabir Pradhancb42b472022-08-23 16:01:19 +0000379 * Read information about batteries exposed through the sysfs path.
380 */
381static std::unordered_map<int32_t /*batteryId*/, RawBatteryInfo> readBatteryConfiguration(
382 const std::filesystem::path& sysfsRootPath) {
383 std::unordered_map<int32_t, RawBatteryInfo> batteryInfos;
384 int32_t nextBatteryId = 0;
385 // Check if device has any battery.
386 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::POWER_SUPPLY);
387 for (const auto& nodePath : paths) {
388 RawBatteryInfo info;
389 info.id = ++nextBatteryId;
390 info.path = nodePath;
391 info.name = nodePath.filename();
392
393 // Scan the path for all the files
394 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
395 const auto& files = allFilesInPath(nodePath);
396 for (const auto& file : files) {
397 const auto it = BATTERY_CLASSES.find(file.filename().string());
398 if (it != BATTERY_CLASSES.end()) {
399 info.flags |= it->second;
400 }
401 }
402 batteryInfos.insert_or_assign(info.id, info);
403 ALOGD("configureBatteryLocked rawBatteryId %d name %s", info.id, info.name.c_str());
404 }
405 return batteryInfos;
406}
407
408/**
409 * Read information about lights exposed through the sysfs path.
410 */
411static std::unordered_map<int32_t /*lightId*/, RawLightInfo> readLightsConfiguration(
412 const std::filesystem::path& sysfsRootPath) {
413 std::unordered_map<int32_t, RawLightInfo> lightInfos;
414 int32_t nextLightId = 0;
415 // Check if device has any lights.
416 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::LEDS);
417 for (const auto& nodePath : paths) {
418 RawLightInfo info;
419 info.id = ++nextLightId;
420 info.path = nodePath;
421 info.name = nodePath.filename();
422 info.maxBrightness = std::nullopt;
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000423
424 // Light name should follow the naming pattern <name>:<color>:<function>
425 // Refer kernel docs /leds/leds-class.html for valid supported LED names.
426 std::regex indexPattern("([a-zA-Z0-9_.:]*:)?([a-zA-Z0-9_.]*):([a-zA-Z0-9_.]*)");
427 std::smatch results;
428
429 if (std::regex_match(info.name, results, indexPattern)) {
430 // regex_match will return full match at index 0 and <name> at index 1. For RawLightInfo
431 // we only care about sections <color> and <function> which will be at index 2 and 3.
432 for (int i = 2; i <= 3; i++) {
433 const auto it = LIGHT_CLASSES.find(results.str(i));
434 if (it != LIGHT_CLASSES.end()) {
435 info.flags |= it->second;
436 }
Prabir Pradhancb42b472022-08-23 16:01:19 +0000437 }
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000438
439 // Set name of the raw light to <function> which represents playerIDs for LEDs that
440 // turn on/off based on the current player ID (Refer to PeripheralController.cpp for
441 // player ID logic)
442 info.name = results.str(3);
Prabir Pradhancb42b472022-08-23 16:01:19 +0000443 }
444 // Scan the path for all the files
445 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
446 const auto& files = allFilesInPath(nodePath);
447 for (const auto& file : files) {
448 const auto it = LIGHT_CLASSES.find(file.filename().string());
449 if (it != LIGHT_CLASSES.end()) {
450 info.flags |= it->second;
451 // If the node has maximum brightness, read it
452 if (it->second == InputLightClass::MAX_BRIGHTNESS) {
453 std::string str;
454 if (base::ReadFileToString(file, &str)) {
455 info.maxBrightness = std::stoi(str);
456 }
457 }
458 }
459 }
460 lightInfos.insert_or_assign(info.id, info);
461 ALOGD("configureLightsLocked rawLightId %d name %s", info.id, info.name.c_str());
462 }
463 return lightInfos;
464}
465
Michael Wrightd02c5b62014-02-10 15:10:22 -0800466// --- Global Functions ---
467
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700468ftl::Flags<InputDeviceClass> getAbsAxisUsage(int32_t axis,
469 ftl::Flags<InputDeviceClass> deviceClasses) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800470 // Touch devices get dibs on touch-related axes.
Chris Ye1b0c7342020-07-28 21:57:03 -0700471 if (deviceClasses.test(InputDeviceClass::TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800472 switch (axis) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700473 case ABS_X:
474 case ABS_Y:
475 case ABS_PRESSURE:
476 case ABS_TOOL_WIDTH:
477 case ABS_DISTANCE:
478 case ABS_TILT_X:
479 case ABS_TILT_Y:
480 case ABS_MT_SLOT:
481 case ABS_MT_TOUCH_MAJOR:
482 case ABS_MT_TOUCH_MINOR:
483 case ABS_MT_WIDTH_MAJOR:
484 case ABS_MT_WIDTH_MINOR:
485 case ABS_MT_ORIENTATION:
486 case ABS_MT_POSITION_X:
487 case ABS_MT_POSITION_Y:
488 case ABS_MT_TOOL_TYPE:
489 case ABS_MT_BLOB_ID:
490 case ABS_MT_TRACKING_ID:
491 case ABS_MT_PRESSURE:
492 case ABS_MT_DISTANCE:
Chris Ye1b0c7342020-07-28 21:57:03 -0700493 return InputDeviceClass::TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800494 }
495 }
496
Chris Yef59a2f42020-10-16 12:55:26 -0700497 if (deviceClasses.test(InputDeviceClass::SENSOR)) {
498 switch (axis) {
499 case ABS_X:
500 case ABS_Y:
501 case ABS_Z:
502 case ABS_RX:
503 case ABS_RY:
504 case ABS_RZ:
505 return InputDeviceClass::SENSOR;
506 }
507 }
508
Michael Wright842500e2015-03-13 17:32:02 -0700509 // External stylus gets the pressure axis
Chris Ye1b0c7342020-07-28 21:57:03 -0700510 if (deviceClasses.test(InputDeviceClass::EXTERNAL_STYLUS)) {
Michael Wright842500e2015-03-13 17:32:02 -0700511 if (axis == ABS_PRESSURE) {
Chris Ye1b0c7342020-07-28 21:57:03 -0700512 return InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -0700513 }
514 }
515
Michael Wrightd02c5b62014-02-10 15:10:22 -0800516 // Joystick devices get the rest.
Chris Ye1b0c7342020-07-28 21:57:03 -0700517 return deviceClasses & InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800518}
519
Harry Cuttsea73eaa2023-01-16 17:55:46 +0000520// --- RawAbsoluteAxisInfo ---
521
Prabir Pradhan132f21c2024-07-25 16:48:30 +0000522std::ostream& operator<<(std::ostream& out, const std::optional<RawAbsoluteAxisInfo>& info) {
523 if (info) {
524 out << "min=" << info->minValue << ", max=" << info->maxValue << ", flat=" << info->flat
525 << ", fuzz=" << info->fuzz << ", resolution=" << info->resolution;
Harry Cuttsea73eaa2023-01-16 17:55:46 +0000526 } else {
527 out << "unknown range";
528 }
529 return out;
530}
531
Michael Wrightd02c5b62014-02-10 15:10:22 -0800532// --- EventHub::Device ---
533
Prabir Pradhancb42b472022-08-23 16:01:19 +0000534EventHub::Device::Device(int fd, int32_t id, std::string path, InputDeviceIdentifier identifier,
535 std::shared_ptr<const AssociatedDevice> assocDev)
Chris Ye989bb932020-07-04 16:18:59 -0700536 : fd(fd),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700537 id(id),
Prabir Pradhancb42b472022-08-23 16:01:19 +0000538 path(std::move(path)),
539 identifier(std::move(identifier)),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700540 classes(0),
541 configuration(nullptr),
542 virtualKeyMap(nullptr),
543 ffEffectPlaying(false),
544 ffEffectId(-1),
Prabir Pradhancb42b472022-08-23 16:01:19 +0000545 associatedDevice(std::move(assocDev)),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700546 controllerNumber(0),
547 enabled(true),
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000548 isVirtual(fd < 0),
549 currentFrameDropped(false) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800550
551EventHub::Device::~Device() {
552 close();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800553}
554
555void EventHub::Device::close() {
556 if (fd >= 0) {
557 ::close(fd);
558 fd = -1;
559 }
560}
561
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700562status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100563 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700564 if (fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100565 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700566 return -errno;
567 }
568 enabled = true;
569 return OK;
570}
571
572status_t EventHub::Device::disable() {
573 close();
574 enabled = false;
575 return OK;
576}
577
Chris Ye989bb932020-07-04 16:18:59 -0700578bool EventHub::Device::hasValidFd() const {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700579 return !isVirtual && enabled;
580}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800581
Chris Ye3a1e4462020-08-12 10:13:15 -0700582const std::shared_ptr<KeyCharacterMap> EventHub::Device::getKeyCharacterMap() const {
Chris Ye989bb932020-07-04 16:18:59 -0700583 return keyMap.keyCharacterMap;
584}
585
586template <std::size_t N>
587status_t EventHub::Device::readDeviceBitMask(unsigned long ioctlCode, BitArray<N>& bitArray) {
588 if (!hasValidFd()) {
589 return BAD_VALUE;
590 }
591 if ((_IOC_SIZE(ioctlCode) == 0)) {
592 ioctlCode |= _IOC(0, 0, 0, bitArray.bytes());
593 }
594
595 typename BitArray<N>::Buffer buffer;
596 status_t ret = ioctl(fd, ioctlCode, buffer.data());
597 bitArray.loadFromBuffer(buffer);
598 return ret;
599}
600
601void EventHub::Device::configureFd() {
602 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
603 if (classes.test(InputDeviceClass::KEYBOARD)) {
604 // Disable kernel key repeat since we handle it ourselves
605 unsigned int repeatRate[] = {0, 0};
606 if (ioctl(fd, EVIOCSREP, repeatRate)) {
607 ALOGW("Unable to disable kernel key repeat for %s: %s", path.c_str(), strerror(errno));
608 }
609 }
610
611 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
612 // associated with input events. This is important because the input system
613 // uses the timestamps extensively and assumes they were recorded using the monotonic
614 // clock.
615 int clockId = CLOCK_MONOTONIC;
Chris Yef59a2f42020-10-16 12:55:26 -0700616 if (classes.test(InputDeviceClass::SENSOR)) {
617 // Each new sensor event should use the same time base as
618 // SystemClock.elapsedRealtimeNanos().
619 clockId = CLOCK_BOOTTIME;
620 }
Chris Ye989bb932020-07-04 16:18:59 -0700621 bool usingClockIoctl = !ioctl(fd, EVIOCSCLOCKID, &clockId);
622 ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000623
624 // Query the initial state of keys and switches, which is tracked by EventHub.
625 readDeviceState();
626}
627
628void EventHub::Device::readDeviceState() {
629 if (readDeviceBitMask(EVIOCGKEY(0), keyState) < 0) {
630 ALOGD("Unable to query the global key state for %s: %s", path.c_str(), strerror(errno));
631 }
632 if (readDeviceBitMask(EVIOCGSW(0), swState) < 0) {
633 ALOGD("Unable to query the global switch state for %s: %s", path.c_str(), strerror(errno));
634 }
Prabir Pradhan341d0782023-07-14 19:04:10 +0000635
636 // Read absolute axis info and values for all available axes for the device.
637 populateAbsoluteAxisStates();
638}
639
640void EventHub::Device::populateAbsoluteAxisStates() {
641 absState.clear();
642
643 for (int axis = 0; axis <= ABS_MAX; axis++) {
644 if (!absBitmask.test(axis)) {
645 continue;
646 }
647 struct input_absinfo info {};
648 if (ioctl(fd, EVIOCGABS(axis), &info)) {
649 ALOGE("Error reading absolute controller %d for device %s fd %d: %s", axis,
650 identifier.name.c_str(), fd, strerror(errno));
651 continue;
652 }
Prabir Pradhan341d0782023-07-14 19:04:10 +0000653 auto& [axisInfo, value] = absState[axis];
Prabir Pradhan341d0782023-07-14 19:04:10 +0000654 axisInfo.minValue = info.minimum;
655 axisInfo.maxValue = info.maximum;
656 axisInfo.flat = info.flat;
657 axisInfo.fuzz = info.fuzz;
658 axisInfo.resolution = info.resolution;
659 value = info.value;
660 }
Chris Ye989bb932020-07-04 16:18:59 -0700661}
662
663bool EventHub::Device::hasKeycodeLocked(int keycode) const {
Vaibhav Devmurari5a71e882024-09-30 15:54:41 +0000664 if (hasKeycodeInternalLocked(keycode)) {
665 return true;
666 }
Rishi Sikka956a6ce2024-10-10 11:31:18 +0000667 if (!keyMap.haveKeyCharacterMap()) {
Rishi Sikka8cb62fe2024-10-10 11:31:18 +0000668 return false;
669 }
Rishi Sikka956a6ce2024-10-10 11:31:18 +0000670 for (auto& fromKey : getKeyCharacterMap()->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 Cuttsd6a3fb52024-10-23 09:48:55 +00001026 ALOGE("Couldn't find device with ID %d, so returning null axis info for axis %s", deviceId,
1027 InputEventLookup::getLinuxEvdevLabel(EV_ABS, axis, 0).code.c_str());
Harry Cutts207674d2024-06-06 18:53:41 +00001028 return std::nullopt;
Arpit Singh77140f42023-06-13 11:35:27 +00001029 }
Prabir Pradhan341d0782023-07-14 19:04:10 +00001030 // We can read the RawAbsoluteAxisInfo even if the device is disabled and doesn't have a valid
1031 // fd, because the info is populated once when the device is first opened, and it doesn't change
1032 // throughout the device lifecycle.
1033 auto it = device->absState.find(axis);
1034 if (it == device->absState.end()) {
Harry Cutts207674d2024-06-06 18:53:41 +00001035 return std::nullopt;
Arpit Singh77140f42023-06-13 11:35:27 +00001036 }
Harry Cutts207674d2024-06-06 18:53:41 +00001037 return it->second.info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001038}
1039
1040bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
1041 if (axis >= 0 && axis <= REL_MAX) {
Chris Ye87143712020-11-10 05:05:58 +00001042 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001043 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001044 return device != nullptr ? device->relBitmask.test(axis) : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001045 }
1046 return false;
1047}
1048
1049bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
Chris Ye87143712020-11-10 05:05:58 +00001050 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001051
Chris Ye989bb932020-07-04 16:18:59 -07001052 Device* device = getDeviceLocked(deviceId);
1053 return property >= 0 && property <= INPUT_PROP_MAX && device != nullptr
1054 ? device->propBitmask.test(property)
1055 : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001056}
1057
Chris Yef59a2f42020-10-16 12:55:26 -07001058bool EventHub::hasMscEvent(int32_t deviceId, int mscEvent) const {
1059 std::scoped_lock _l(mLock);
1060
1061 Device* device = getDeviceLocked(deviceId);
1062 return mscEvent >= 0 && mscEvent <= MSC_MAX && device != nullptr
1063 ? device->mscBitmask.test(mscEvent)
1064 : false;
1065}
1066
Michael Wrightd02c5b62014-02-10 15:10:22 -08001067int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001068 if (scanCode < 0 || scanCode > KEY_MAX) {
1069 return AKEY_STATE_UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001070 }
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001071 std::scoped_lock _l(mLock);
1072 const Device* device = getDeviceLocked(deviceId);
1073 if (device == nullptr || !device->hasValidFd() || !device->keyBitmask.test(scanCode)) {
1074 return AKEY_STATE_UNKNOWN;
1075 }
1076 return device->keyState.test(scanCode) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001077}
1078
1079int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
Chris Ye87143712020-11-10 05:05:58 +00001080 std::scoped_lock _l(mLock);
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001081 const Device* device = getDeviceLocked(deviceId);
1082 if (device == nullptr || !device->hasValidFd() || !device->keyMap.haveKeyLayout()) {
1083 return AKEY_STATE_UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001084 }
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001085 const std::vector<int32_t> scanCodes =
1086 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode);
1087 if (scanCodes.empty()) {
1088 return AKEY_STATE_UNKNOWN;
1089 }
1090 return std::any_of(scanCodes.begin(), scanCodes.end(),
1091 [&device](const int32_t sc) {
1092 return sc >= 0 && sc <= KEY_MAX && device->keyState.test(sc);
1093 })
1094 ? AKEY_STATE_DOWN
1095 : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001096}
1097
Philip Junker4af3b3d2021-12-14 10:36:55 +01001098int32_t EventHub::getKeyCodeForKeyLocation(int32_t deviceId, int32_t locationKeyCode) const {
1099 std::scoped_lock _l(mLock);
1100
1101 Device* device = getDeviceLocked(deviceId);
1102 if (device == nullptr || !device->hasValidFd() || device->keyMap.keyCharacterMap == nullptr ||
1103 device->keyMap.keyLayoutMap == nullptr) {
1104 return AKEYCODE_UNKNOWN;
1105 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001106 std::vector<int32_t> scanCodes =
1107 device->keyMap.keyLayoutMap->findScanCodesForKey(locationKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +01001108 if (scanCodes.empty()) {
1109 ALOGW("Failed to get key code for key location: no scan code maps to key code %d for input"
1110 "device %d",
1111 locationKeyCode, deviceId);
1112 return AKEYCODE_UNKNOWN;
1113 }
1114 if (scanCodes.size() > 1) {
1115 ALOGW("Multiple scan codes map to the same key code %d, returning only the first match",
1116 locationKeyCode);
1117 }
1118 int32_t outKeyCode;
1119 status_t mapKeyRes =
Harry Cutts33476232023-01-30 19:57:29 +00001120 device->getKeyCharacterMap()->mapKey(scanCodes[0], /*usageCode=*/0, &outKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +01001121 switch (mapKeyRes) {
1122 case OK:
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001123 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +01001124 case NAME_NOT_FOUND:
1125 // key character map doesn't re-map this scanCode, hence the keyCode remains the same
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001126 outKeyCode = locationKeyCode;
1127 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +01001128 default:
1129 ALOGW("Failed to get key code for key location: Key character map returned error %s",
1130 statusToString(mapKeyRes).c_str());
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001131 outKeyCode = AKEYCODE_UNKNOWN;
1132 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +01001133 }
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001134 // Remap if there is a Key remapping added to the KCM and return the remapped key
1135 return device->getKeyCharacterMap()->applyKeyRemapping(outKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +01001136}
1137
Michael Wrightd02c5b62014-02-10 15:10:22 -08001138int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001139 if (sw < 0 || sw > SW_MAX) {
1140 return AKEY_STATE_UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001141 }
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001142 std::scoped_lock _l(mLock);
1143 const Device* device = getDeviceLocked(deviceId);
1144 if (device == nullptr || !device->hasValidFd() || !device->swBitmask.test(sw)) {
1145 return AKEY_STATE_UNKNOWN;
1146 }
1147 return device->swState.test(sw) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001148}
1149
Harry Cuttse2c5e202024-06-21 17:08:48 +00001150std::optional<int32_t> EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis) const {
Prabir Pradhan341d0782023-07-14 19:04:10 +00001151 if (axis < 0 || axis > ABS_MAX) {
Harry Cuttse2c5e202024-06-21 17:08:48 +00001152 return std::nullopt;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001153 }
Prabir Pradhan341d0782023-07-14 19:04:10 +00001154 std::scoped_lock _l(mLock);
1155 const Device* device = getDeviceLocked(deviceId);
1156 if (device == nullptr || !device->hasValidFd()) {
Harry Cuttse2c5e202024-06-21 17:08:48 +00001157 return std::nullopt;
Prabir Pradhan341d0782023-07-14 19:04:10 +00001158 }
1159 const auto it = device->absState.find(axis);
1160 if (it == device->absState.end()) {
Harry Cuttse2c5e202024-06-21 17:08:48 +00001161 return std::nullopt;
Prabir Pradhan341d0782023-07-14 19:04:10 +00001162 }
Harry Cuttse2c5e202024-06-21 17:08:48 +00001163 return it->second.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001164}
1165
Arpit Singh4b4a4572023-11-24 18:19:56 +00001166base::Result<std::vector<int32_t>> EventHub::getMtSlotValues(int32_t deviceId, int32_t axis,
1167 size_t slotCount) const {
1168 std::scoped_lock _l(mLock);
1169 const Device* device = getDeviceLocked(deviceId);
1170 if (device == nullptr || !device->hasValidFd() || !device->absBitmask.test(axis)) {
1171 return base::ResultError("device problem or axis not supported", NAME_NOT_FOUND);
1172 }
1173 std::vector<int32_t> outValues(slotCount + 1);
1174 outValues[0] = axis;
1175 const size_t bufferSize = outValues.size() * sizeof(int32_t);
1176 if (ioctl(device->fd, EVIOCGMTSLOTS(bufferSize), outValues.data()) != OK) {
1177 return base::ErrnoError();
1178 }
1179 return std::move(outValues);
1180}
1181
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001182bool EventHub::markSupportedKeyCodes(int32_t deviceId, const std::vector<int32_t>& keyCodes,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001183 uint8_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +00001184 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001185
1186 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001187 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001188 for (size_t codeIndex = 0; codeIndex < keyCodes.size(); codeIndex++) {
Sergej Salnikove5420e72023-05-11 11:52:54 +00001189 if (device->hasKeycodeLocked(keyCodes[codeIndex])) {
1190 outFlags[codeIndex] = 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001191 }
1192 }
1193 return true;
1194 }
1195 return false;
1196}
1197
Linnan Lie5657f22024-09-13 21:54:37 +08001198void EventHub::setKeyRemapping(int32_t deviceId,
1199 const std::map<int32_t, int32_t>& keyRemapping) const {
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001200 std::scoped_lock _l(mLock);
1201 Device* device = getDeviceLocked(deviceId);
1202 if (device == nullptr) {
1203 return;
1204 }
1205 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
1206 if (kcm) {
Linnan Lie5657f22024-09-13 21:54:37 +08001207 kcm->setKeyRemapping(keyRemapping);
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001208 }
1209}
1210
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001211status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
1212 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +00001213 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001214 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001215 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001216
Chris Ye66fbac32020-07-06 20:36:43 -07001217 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001218 // Check the key character map first.
Chris Ye3a1e4462020-08-12 10:13:15 -07001219 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
1220 if (kcm) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001221 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
1222 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001223 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001224 }
1225 }
1226
1227 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001228 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -08001229 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001230 status = NO_ERROR;
1231 }
1232 }
1233
1234 if (status == NO_ERROR) {
Chris Ye3a1e4462020-08-12 10:13:15 -07001235 if (kcm) {
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001236 // Remap keys based on user-defined key remappings and key behavior defined in the
1237 // corresponding kcm file
1238 *outKeycode = kcm->applyKeyRemapping(*outKeycode);
1239
1240 // Remap keys based on Key behavior defined in KCM file
1241 std::tie(*outKeycode, *outMetaState) =
1242 kcm->applyKeyBehavior(*outKeycode, metaState);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001243 } else {
1244 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001245 }
1246 }
1247 }
1248
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001249 if (status != NO_ERROR) {
1250 *outKeycode = 0;
1251 *outFlags = 0;
1252 *outMetaState = metaState;
1253 }
1254
1255 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001256}
1257
1258status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
Chris Ye87143712020-11-10 05:05:58 +00001259 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001260 Device* device = getDeviceLocked(deviceId);
1261
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001262 if (device == nullptr || !device->keyMap.haveKeyLayout()) {
1263 return NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001264 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001265 std::optional<AxisInfo> info = device->keyMap.keyLayoutMap->mapAxis(scanCode);
1266 if (!info.has_value()) {
1267 return NAME_NOT_FOUND;
1268 }
1269 *outAxisInfo = *info;
1270 return NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001271}
1272
Chris Yef59a2f42020-10-16 12:55:26 -07001273base::Result<std::pair<InputDeviceSensorType, int32_t>> EventHub::mapSensor(int32_t deviceId,
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001274 int32_t absCode) const {
Chris Yef59a2f42020-10-16 12:55:26 -07001275 std::scoped_lock _l(mLock);
1276 Device* device = getDeviceLocked(deviceId);
1277
1278 if (device != nullptr && device->keyMap.haveKeyLayout()) {
1279 return device->keyMap.keyLayoutMap->mapSensor(absCode);
1280 }
1281 return Errorf("Device not found or device has no key layout.");
1282}
1283
Chris Yee2b1e5c2021-03-10 22:45:12 -08001284// Gets the battery info map from battery ID to RawBatteryInfo of the miscellaneous device
1285// associated with the device ID. Returns an empty map if no miscellaneous device found.
1286const std::unordered_map<int32_t, RawBatteryInfo>& EventHub::getBatteryInfoLocked(
1287 int32_t deviceId) const {
1288 static const std::unordered_map<int32_t, RawBatteryInfo> EMPTY_BATTERY_INFO = {};
1289 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001290 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001291 return EMPTY_BATTERY_INFO;
1292 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001293 return device->associatedDevice->batteryInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001294}
1295
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001296std::vector<int32_t> EventHub::getRawBatteryIds(int32_t deviceId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001297 std::scoped_lock _l(mLock);
1298 std::vector<int32_t> batteryIds;
1299
Prabir Pradhan51894782022-08-23 16:29:10 +00001300 for (const auto& [id, info] : getBatteryInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001301 batteryIds.push_back(id);
1302 }
1303
1304 return batteryIds;
1305}
1306
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001307std::optional<RawBatteryInfo> EventHub::getRawBatteryInfo(int32_t deviceId,
1308 int32_t batteryId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001309 std::scoped_lock _l(mLock);
1310
1311 const auto infos = getBatteryInfoLocked(deviceId);
1312
1313 auto it = infos.find(batteryId);
1314 if (it != infos.end()) {
1315 return it->second;
1316 }
1317
1318 return std::nullopt;
1319}
1320
1321// Gets the light info map from light ID to RawLightInfo of the miscellaneous device associated
Prabir Pradhan51894782022-08-23 16:29:10 +00001322// with the device ID. Returns an empty map if no miscellaneous device found.
Chris Yee2b1e5c2021-03-10 22:45:12 -08001323const std::unordered_map<int32_t, RawLightInfo>& EventHub::getLightInfoLocked(
1324 int32_t deviceId) const {
1325 static const std::unordered_map<int32_t, RawLightInfo> EMPTY_LIGHT_INFO = {};
1326 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001327 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001328 return EMPTY_LIGHT_INFO;
1329 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001330 return device->associatedDevice->lightInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001331}
1332
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001333std::vector<int32_t> EventHub::getRawLightIds(int32_t deviceId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001334 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001335 std::vector<int32_t> lightIds;
1336
Prabir Pradhan51894782022-08-23 16:29:10 +00001337 for (const auto& [id, info] : getLightInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001338 lightIds.push_back(id);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001339 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001340
Chris Ye3fdbfef2021-01-06 18:45:18 -08001341 return lightIds;
1342}
1343
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001344std::optional<RawLightInfo> EventHub::getRawLightInfo(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001345 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001346
Chris Yee2b1e5c2021-03-10 22:45:12 -08001347 const auto infos = getLightInfoLocked(deviceId);
1348
1349 auto it = infos.find(lightId);
1350 if (it != infos.end()) {
1351 return it->second;
Chris Ye3fdbfef2021-01-06 18:45:18 -08001352 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001353
Chris Ye3fdbfef2021-01-06 18:45:18 -08001354 return std::nullopt;
1355}
1356
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001357std::optional<int32_t> EventHub::getLightBrightness(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001358 std::scoped_lock _l(mLock);
1359
Chris Yee2b1e5c2021-03-10 22:45:12 -08001360 const auto infos = getLightInfoLocked(deviceId);
1361 auto it = infos.find(lightId);
1362 if (it == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001363 return std::nullopt;
1364 }
1365 std::string buffer;
1366 if (!base::ReadFileToString(it->second.path / LIGHT_NODES.at(InputLightClass::BRIGHTNESS),
1367 &buffer)) {
1368 return std::nullopt;
1369 }
1370 return std::stoi(buffer);
1371}
1372
1373std::optional<std::unordered_map<LightColor, int32_t>> EventHub::getLightIntensities(
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001374 int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001375 std::scoped_lock _l(mLock);
1376
Chris Yee2b1e5c2021-03-10 22:45:12 -08001377 const auto infos = getLightInfoLocked(deviceId);
1378 auto lightIt = infos.find(lightId);
1379 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001380 return std::nullopt;
1381 }
1382
1383 auto ret =
1384 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1385
1386 if (!ret.has_value()) {
1387 return std::nullopt;
1388 }
1389 std::array<LightColor, COLOR_NUM> colors = ret.value();
1390
1391 std::string intensityStr;
1392 if (!base::ReadFileToString(lightIt->second.path /
1393 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY),
1394 &intensityStr)) {
1395 return std::nullopt;
1396 }
1397
1398 // Intensity node outputs 3 color values
1399 std::regex intensityPattern("([0-9]+)\\s([0-9]+)\\s([0-9]+)[\\n]");
1400 std::smatch results;
1401
1402 if (!std::regex_match(intensityStr, results, intensityPattern)) {
1403 return std::nullopt;
1404 }
1405 std::unordered_map<LightColor, int32_t> intensities;
1406 for (size_t i = 1; i < results.size(); i++) {
1407 int value = std::stoi(results[i].str());
1408 intensities.emplace(colors[i - 1], value);
1409 }
1410 return intensities;
1411}
1412
1413void EventHub::setLightBrightness(int32_t deviceId, int32_t lightId, int32_t brightness) {
1414 std::scoped_lock _l(mLock);
1415
Chris Yee2b1e5c2021-03-10 22:45:12 -08001416 const auto infos = getLightInfoLocked(deviceId);
1417 auto lightIt = infos.find(lightId);
1418 if (lightIt == infos.end()) {
1419 ALOGE("%s lightId %d not found ", __func__, lightId);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001420 return;
1421 }
1422
1423 if (!base::WriteStringToFile(std::to_string(brightness),
1424 lightIt->second.path /
1425 LIGHT_NODES.at(InputLightClass::BRIGHTNESS))) {
1426 ALOGE("Can not write to file, error: %s", strerror(errno));
1427 }
1428}
1429
1430void EventHub::setLightIntensities(int32_t deviceId, int32_t lightId,
1431 std::unordered_map<LightColor, int32_t> intensities) {
1432 std::scoped_lock _l(mLock);
1433
Chris Yee2b1e5c2021-03-10 22:45:12 -08001434 const auto infos = getLightInfoLocked(deviceId);
1435 auto lightIt = infos.find(lightId);
1436 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001437 ALOGE("Light Id %d does not exist.", lightId);
1438 return;
1439 }
1440
1441 auto ret =
1442 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1443
1444 if (!ret.has_value()) {
1445 return;
1446 }
1447 std::array<LightColor, COLOR_NUM> colors = ret.value();
1448
1449 std::string rgbStr;
1450 for (size_t i = 0; i < COLOR_NUM; i++) {
1451 auto it = intensities.find(colors[i]);
1452 if (it != intensities.end()) {
1453 rgbStr += std::to_string(it->second);
1454 // Insert space between colors
1455 if (i < COLOR_NUM - 1) {
1456 rgbStr += " ";
1457 }
1458 }
1459 }
1460 // Append new line
1461 rgbStr += "\n";
1462
1463 if (!base::WriteStringToFile(rgbStr,
1464 lightIt->second.path /
1465 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY))) {
1466 ALOGE("Can not write to file, error: %s", strerror(errno));
1467 }
1468}
1469
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001470std::optional<RawLayoutInfo> EventHub::getRawLayoutInfo(int32_t deviceId) const {
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001471 std::scoped_lock _l(mLock);
1472 Device* device = getDeviceLocked(deviceId);
1473 if (device == nullptr || !device->associatedDevice) {
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001474 return std::nullopt;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001475 }
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001476 return device->associatedDevice->layoutInfo;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001477}
1478
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001479void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Chris Ye87143712020-11-10 05:05:58 +00001480 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001481
1482 mExcludedDevices = devices;
1483}
1484
1485bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
Chris Ye87143712020-11-10 05:05:58 +00001486 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001487 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001488 if (device != nullptr && scanCode >= 0 && scanCode <= KEY_MAX) {
1489 return device->keyBitmask.test(scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001490 }
1491 return false;
1492}
1493
Arthur Hungcb40a002021-08-03 14:31:01 +00001494bool EventHub::hasKeyCode(int32_t deviceId, int32_t keyCode) const {
1495 std::scoped_lock _l(mLock);
1496 Device* device = getDeviceLocked(deviceId);
1497 if (device != nullptr) {
1498 return device->hasKeycodeLocked(keyCode);
1499 }
1500 return false;
1501}
1502
Michael Wrightd02c5b62014-02-10 15:10:22 -08001503bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
Chris Ye87143712020-11-10 05:05:58 +00001504 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001505 Device* device = getDeviceLocked(deviceId);
1506 int32_t sc;
Chris Ye989bb932020-07-04 16:18:59 -07001507 if (device != nullptr && device->mapLed(led, &sc) == NO_ERROR) {
Chris Ye66fbac32020-07-06 20:36:43 -07001508 return device->ledBitmask.test(sc);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001509 }
1510 return false;
1511}
1512
1513void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
Chris Ye87143712020-11-10 05:05:58 +00001514 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001515 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -07001516 if (device != nullptr && device->hasValidFd()) {
1517 device->setLedStateLocked(led, on);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001518 }
1519}
1520
1521void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001522 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001523 outVirtualKeys.clear();
1524
Chris Ye87143712020-11-10 05:05:58 +00001525 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001526 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001527 if (device != nullptr && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001528 const std::vector<VirtualKeyDefinition> virtualKeys =
1529 device->virtualKeyMap->getVirtualKeys();
1530 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001531 }
1532}
1533
Chris Ye3a1e4462020-08-12 10:13:15 -07001534const std::shared_ptr<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001535 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001536 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001537 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001538 return device->getKeyCharacterMap();
1539 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001540 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001541}
1542
Vaibhav Devmurari23e8ae92022-12-29 12:07:56 +00001543// If provided map is null, it will reset key character map to default KCM.
Chris Ye3a1e4462020-08-12 10:13:15 -07001544bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, std::shared_ptr<KeyCharacterMap> map) {
Chris Ye87143712020-11-10 05:05:58 +00001545 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001546 Device* device = getDeviceLocked(deviceId);
Vaibhav Devmurari23e8ae92022-12-29 12:07:56 +00001547 if (device == nullptr || device->keyMap.keyCharacterMap == nullptr) {
Philip Junker90bc9492021-12-10 18:39:42 +01001548 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001549 }
Vaibhav Devmurari23e8ae92022-12-29 12:07:56 +00001550 if (map == nullptr) {
1551 device->keyMap.keyCharacterMap->clearLayoutOverlay();
1552 return true;
1553 }
Philip Junker90bc9492021-12-10 18:39:42 +01001554 device->keyMap.keyCharacterMap->combine(*map);
1555 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001556}
1557
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001558static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
1559 std::string rawDescriptor;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001560 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001561 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001562 if (!identifier.uniqueId.empty()) {
1563 rawDescriptor += "uniqueId:";
1564 rawDescriptor += identifier.uniqueId;
Josh Bartel938632f2022-07-19 15:34:22 -05001565 }
1566 if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001567 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001568 }
1569
1570 if (identifier.vendor == 0 && identifier.product == 0) {
1571 // If we don't know the vendor and product id, then the device is probably
1572 // built-in so we need to rely on other information to uniquely identify
1573 // the input device. Usually we try to avoid relying on the device name or
1574 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001575 if (!identifier.name.empty()) {
1576 rawDescriptor += "name:";
1577 rawDescriptor += identifier.name;
1578 } else if (!identifier.location.empty()) {
1579 rawDescriptor += "location:";
1580 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001581 }
1582 }
1583 identifier.descriptor = sha1(rawDescriptor);
1584 return rawDescriptor;
1585}
1586
1587void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
1588 // Compute a device descriptor that uniquely identifies the device.
1589 // The descriptor is assumed to be a stable identifier. Its value should not
1590 // change between reboots, reconnections, firmware updates or new releases
1591 // of Android. In practice we sometimes get devices that cannot be uniquely
1592 // identified. In this case we enforce uniqueness between connected devices.
1593 // Ideally, we also want the descriptor to be short and relatively opaque.
Josh Bartel938632f2022-07-19 15:34:22 -05001594 // Note that we explicitly do not use the path or location for external devices
1595 // as their path or location will change as they are plugged/unplugged or moved
1596 // to different ports. We do fallback to using name and location in the case of
1597 // internal devices which are detected by the vendor and product being 0 in
1598 // generateDescriptor. If two identical descriptors are detected we will fallback
1599 // to using a 'nonce' and incrementing it until the new descriptor no longer has
1600 // a match with any existing descriptors.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001601
1602 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001603 std::string rawDescriptor = generateDescriptor(identifier);
Josh Bartel938632f2022-07-19 15:34:22 -05001604 // Enforce that the generated descriptor is unique.
1605 while (hasDeviceWithDescriptorLocked(identifier.descriptor)) {
1606 identifier.nonce++;
1607 rawDescriptor = generateDescriptor(identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001608 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001609 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001610 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001611}
1612
Prabir Pradhancb42b472022-08-23 16:01:19 +00001613std::shared_ptr<const EventHub::AssociatedDevice> EventHub::obtainAssociatedDeviceLocked(
1614 const std::filesystem::path& devicePath) const {
1615 const std::optional<std::filesystem::path> sysfsRootPathOpt =
1616 getSysfsRootPath(devicePath.c_str());
1617 if (!sysfsRootPathOpt) {
1618 return nullptr;
1619 }
1620
1621 const auto& path = *sysfsRootPathOpt;
Prabir Pradhancb42b472022-08-23 16:01:19 +00001622
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00001623 std::shared_ptr<const AssociatedDevice> associatedDevice = std::make_shared<AssociatedDevice>(
Prabir Pradhancb42b472022-08-23 16:01:19 +00001624 AssociatedDevice{.sysfsRootPath = path,
1625 .batteryInfos = readBatteryConfiguration(path),
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001626 .lightInfos = readLightsConfiguration(path),
1627 .layoutInfo = readLayoutConfiguration(path)});
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00001628
1629 bool associatedDeviceChanged = false;
1630 for (const auto& [id, dev] : mDevices) {
1631 if (dev->associatedDevice && dev->associatedDevice->sysfsRootPath == path) {
1632 if (*associatedDevice != *dev->associatedDevice) {
1633 associatedDeviceChanged = true;
1634 dev->associatedDevice = associatedDevice;
1635 }
1636 associatedDevice = dev->associatedDevice;
1637 }
1638 }
1639 ALOGI_IF(associatedDeviceChanged,
1640 "The AssociatedDevice changed for path '%s'. Using new AssociatedDevice: %s",
1641 path.c_str(), associatedDevice->dump().c_str());
1642
1643 return associatedDevice;
Prabir Pradhancb42b472022-08-23 16:01:19 +00001644}
1645
Vaibhav Devmurari5fc7d852023-03-17 18:43:33 +00001646bool EventHub::AssociatedDevice::isChanged() const {
1647 std::unordered_map<int32_t, RawBatteryInfo> newBatteryInfos =
1648 readBatteryConfiguration(sysfsRootPath);
1649 std::unordered_map<int32_t, RawLightInfo> newLightInfos =
1650 readLightsConfiguration(sysfsRootPath);
1651 std::optional<RawLayoutInfo> newLayoutInfo = readLayoutConfiguration(sysfsRootPath);
1652
1653 if (newBatteryInfos == batteryInfos && newLightInfos == lightInfos &&
1654 newLayoutInfo == layoutInfo) {
1655 return false;
1656 }
1657 return true;
1658}
1659
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001660void EventHub::vibrate(int32_t deviceId, const VibrationElement& element) {
Chris Ye87143712020-11-10 05:05:58 +00001661 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001662 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001663 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001664 ff_effect effect;
1665 memset(&effect, 0, sizeof(effect));
1666 effect.type = FF_RUMBLE;
1667 effect.id = device->ffEffectId;
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001668 // evdev FF_RUMBLE effect only supports two channels of vibration.
Chris Ye6393a262020-08-04 19:41:36 -07001669 effect.u.rumble.strong_magnitude = element.getMagnitude(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1670 effect.u.rumble.weak_magnitude = element.getMagnitude(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001671 effect.replay.length = element.duration.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001672 effect.replay.delay = 0;
1673 if (ioctl(device->fd, EVIOCSFF, &effect)) {
1674 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001675 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001676 return;
1677 }
1678 device->ffEffectId = effect.id;
1679
1680 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -07001681 ev.input_event_sec = 0;
1682 ev.input_event_usec = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001683 ev.type = EV_FF;
1684 ev.code = device->ffEffectId;
1685 ev.value = 1;
1686 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1687 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001688 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001689 return;
1690 }
1691 device->ffEffectPlaying = true;
1692 }
1693}
1694
1695void EventHub::cancelVibrate(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001696 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001697 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001698 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001699 if (device->ffEffectPlaying) {
1700 device->ffEffectPlaying = false;
1701
1702 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -07001703 ev.input_event_sec = 0;
1704 ev.input_event_usec = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001705 ev.type = EV_FF;
1706 ev.code = device->ffEffectId;
1707 ev.value = 0;
1708 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1709 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001710 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001711 return;
1712 }
1713 }
1714 }
1715}
1716
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001717std::vector<int32_t> EventHub::getVibratorIds(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001718 std::scoped_lock _l(mLock);
1719 std::vector<int32_t> vibrators;
1720 Device* device = getDeviceLocked(deviceId);
1721 if (device != nullptr && device->hasValidFd() &&
1722 device->classes.test(InputDeviceClass::VIBRATOR)) {
1723 vibrators.push_back(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1724 vibrators.push_back(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
1725 }
1726 return vibrators;
1727}
1728
Josh Bartel938632f2022-07-19 15:34:22 -05001729/**
1730 * Checks both mDevices and mOpeningDevices for a device with the descriptor passed.
1731 */
1732bool EventHub::hasDeviceWithDescriptorLocked(const std::string& descriptor) const {
1733 for (const auto& device : mOpeningDevices) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001734 if (descriptor == device->identifier.descriptor) {
Josh Bartel938632f2022-07-19 15:34:22 -05001735 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001736 }
1737 }
Josh Bartel938632f2022-07-19 15:34:22 -05001738
1739 for (const auto& [id, device] : mDevices) {
1740 if (descriptor == device->identifier.descriptor) {
1741 return true;
1742 }
1743 }
1744 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001745}
1746
1747EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001748 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001749 deviceId = mBuiltInKeyboardId;
1750 }
Chris Ye989bb932020-07-04 16:18:59 -07001751 const auto& it = mDevices.find(deviceId);
1752 return it != mDevices.end() ? it->second.get() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001753}
1754
Chris Ye8594e192020-07-14 10:34:06 -07001755EventHub::Device* EventHub::getDeviceByPathLocked(const std::string& devicePath) const {
Chris Ye989bb932020-07-04 16:18:59 -07001756 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001757 if (device->path == devicePath) {
Chris Ye989bb932020-07-04 16:18:59 -07001758 return device.get();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001759 }
1760 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001761 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001762}
1763
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001764/**
1765 * The file descriptor could be either input device, or a video device (associated with a
1766 * specific input device). Check both cases here, and return the device that this event
1767 * belongs to. Caller can compare the fd's once more to determine event type.
1768 * Looks through all input devices, and only attached video devices. Unattached video
1769 * devices are ignored.
1770 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001771EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
Chris Ye989bb932020-07-04 16:18:59 -07001772 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001773 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001774 // This is an input device event
Chris Ye989bb932020-07-04 16:18:59 -07001775 return device.get();
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001776 }
1777 if (device->videoDevice && device->videoDevice->getFd() == fd) {
1778 // This is a video device event
Chris Ye989bb932020-07-04 16:18:59 -07001779 return device.get();
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001780 }
1781 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001782 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
1783 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001784 return nullptr;
1785}
1786
Chris Yee2b1e5c2021-03-10 22:45:12 -08001787std::optional<int32_t> EventHub::getBatteryCapacity(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001788 std::filesystem::path batteryPath;
1789 {
1790 // Do not read the sysfs node to get the battery state while holding
1791 // the EventHub lock. For some peripheral devices, reading battery state
1792 // can be broken and take 5+ seconds. Holding the lock in this case would
1793 // block all other event processing during this time. For now, we assume this
1794 // call never happens on the InputReader thread and read the sysfs node outside
1795 // the lock to prevent event processing from being blocked by this call.
1796 std::scoped_lock _l(mLock);
Kim Low03ea0352020-11-06 12:45:07 -08001797
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001798 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001799 auto it = infos.find(batteryId);
1800 if (it == infos.end()) {
1801 return std::nullopt;
1802 }
1803 batteryPath = it->second.path;
1804 } // release lock
1805
Chris Yee2b1e5c2021-03-10 22:45:12 -08001806 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001807
1808 // Some devices report battery capacity as an integer through the "capacity" file
Andy Chenf9f1a022022-08-29 20:07:10 -04001809 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001810 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001811 return std::stoi(base::Trim(buffer));
Kim Low03ea0352020-11-06 12:45:07 -08001812 }
1813
1814 // Other devices report capacity as an enum value POWER_SUPPLY_CAPACITY_LEVEL_XXX
1815 // These values are taken from kernel source code include/linux/power_supply.h
Andy Chenf9f1a022022-08-29 20:07:10 -04001816 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY_LEVEL),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001817 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001818 // Remove any white space such as trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001819 const auto levelIt = BATTERY_LEVEL.find(base::Trim(buffer));
1820 if (levelIt != BATTERY_LEVEL.end()) {
1821 return levelIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001822 }
1823 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001824
Kim Low03ea0352020-11-06 12:45:07 -08001825 return std::nullopt;
1826}
1827
Chris Yee2b1e5c2021-03-10 22:45:12 -08001828std::optional<int32_t> EventHub::getBatteryStatus(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001829 std::filesystem::path batteryPath;
1830 {
1831 // Do not read the sysfs node to get the battery state while holding
1832 // the EventHub lock. For some peripheral devices, reading battery state
1833 // can be broken and take 5+ seconds. Holding the lock in this case would
1834 // block all other event processing during this time. For now, we assume this
1835 // call never happens on the InputReader thread and read the sysfs node outside
1836 // the lock to prevent event processing from being blocked by this call.
1837 std::scoped_lock _l(mLock);
1838
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001839 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001840 auto it = infos.find(batteryId);
1841 if (it == infos.end()) {
1842 return std::nullopt;
1843 }
1844 batteryPath = it->second.path;
1845 } // release lock
1846
Chris Yee2b1e5c2021-03-10 22:45:12 -08001847 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001848
Andy Chenf9f1a022022-08-29 20:07:10 -04001849 if (!base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::STATUS),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001850 &buffer)) {
Kim Low03ea0352020-11-06 12:45:07 -08001851 ALOGE("Failed to read sysfs battery info: %s", strerror(errno));
1852 return std::nullopt;
1853 }
1854
Chris Yed1936772021-02-22 10:30:40 -08001855 // Remove white space like trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001856 const auto statusIt = BATTERY_STATUS.find(base::Trim(buffer));
1857 if (statusIt != BATTERY_STATUS.end()) {
1858 return statusIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001859 }
1860
1861 return std::nullopt;
1862}
1863
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001864std::vector<RawEvent> EventHub::getEvents(int timeoutMillis) {
Chris Ye87143712020-11-10 05:05:58 +00001865 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001866
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001867 std::array<input_event, EVENT_BUFFER_SIZE> readBuffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001868
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001869 std::vector<RawEvent> events;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001870 bool awoken = false;
1871 for (;;) {
1872 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
1873
1874 // Reopen input devices if needed.
1875 if (mNeedToReopenDevices) {
1876 mNeedToReopenDevices = false;
1877
1878 ALOGI("Reopening all input devices due to a configuration change.");
1879
1880 closeAllDevicesLocked();
1881 mNeedToScanDevices = true;
1882 break; // return to the caller before we actually rescan
1883 }
1884
1885 // Report any devices that had last been added/removed.
Chris Ye989bb932020-07-04 16:18:59 -07001886 for (auto it = mClosingDevices.begin(); it != mClosingDevices.end();) {
1887 std::unique_ptr<Device> device = std::move(*it);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001888 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001889 const int32_t deviceId = (device->id == mBuiltInKeyboardId)
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001890 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
1891 : device->id;
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001892 events.push_back({
1893 .when = now,
1894 .deviceId = deviceId,
1895 .type = DEVICE_REMOVED,
1896 });
Chris Ye989bb932020-07-04 16:18:59 -07001897 it = mClosingDevices.erase(it);
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001898 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001899 break;
1900 }
1901 }
1902
1903 if (mNeedToScanDevices) {
1904 mNeedToScanDevices = false;
1905 scanDevicesLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001906 }
1907
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001908 while (!mOpeningDevices.empty()) {
1909 std::unique_ptr<Device> device = std::move(*mOpeningDevices.rbegin());
1910 mOpeningDevices.pop_back();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001911 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001912 const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1913 events.push_back({
1914 .when = now,
1915 .deviceId = deviceId,
1916 .type = DEVICE_ADDED,
1917 });
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001918
1919 // Try to find a matching video device by comparing device names
1920 for (auto it = mUnattachedVideoDevices.begin(); it != mUnattachedVideoDevices.end();
1921 it++) {
1922 std::unique_ptr<TouchVideoDevice>& videoDevice = *it;
Chris Yed3fef462021-03-07 17:10:08 -08001923 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001924 // videoDevice was transferred to 'device'
1925 it = mUnattachedVideoDevices.erase(it);
1926 break;
1927 }
1928 }
1929
1930 auto [dev_it, inserted] = mDevices.insert_or_assign(device->id, std::move(device));
1931 if (!inserted) {
Chris Ye989bb932020-07-04 16:18:59 -07001932 ALOGW("Device id %d exists, replaced.", device->id);
1933 }
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001934 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001935 break;
1936 }
1937 }
1938
1939 // Grab the next input event.
1940 bool deviceChanged = false;
1941 while (mPendingEventIndex < mPendingEventCount) {
1942 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001943 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001944 if (eventItem.events & EPOLLIN) {
1945 mPendingINotify = true;
1946 } else {
1947 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
1948 }
1949 continue;
1950 }
1951
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001952 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001953 if (eventItem.events & EPOLLIN) {
1954 ALOGV("awoken after wake()");
1955 awoken = true;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001956 char wakeReadBuffer[16];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001957 ssize_t nRead;
1958 do {
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001959 nRead = read(mWakeReadPipeFd, wakeReadBuffer, sizeof(wakeReadBuffer));
1960 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(wakeReadBuffer));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001961 } else {
1962 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001963 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001964 }
1965 continue;
1966 }
1967
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001968 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Chris Ye989bb932020-07-04 16:18:59 -07001969 if (device == nullptr) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001970 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
1971 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001972 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001973 continue;
1974 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001975 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
1976 if (eventItem.events & EPOLLIN) {
1977 size_t numFrames = device->videoDevice->readAndQueueFrames();
1978 if (numFrames == 0) {
1979 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001980 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001981 }
1982 } else if (eventItem.events & EPOLLHUP) {
1983 // TODO(b/121395353) - consider adding EPOLLRDHUP
1984 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001985 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001986 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1987 device->videoDevice = nullptr;
1988 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001989 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1990 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001991 ALOG_ASSERT(!DEBUG);
1992 }
1993 continue;
1994 }
1995 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -08001996 if (eventItem.events & EPOLLIN) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001997 int32_t readSize =
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001998 read(device->fd, readBuffer.data(),
1999 sizeof(decltype(readBuffer)::value_type) * readBuffer.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002000 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
2001 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -07002002 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07002003 " capacity: %zu errno: %d)\n",
2004 device->fd, readSize, readBuffer.size(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002005 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07002006 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002007 } else if (readSize < 0) {
2008 if (errno != EAGAIN && errno != EINTR) {
2009 ALOGW("could not get event (errno=%d)", errno);
2010 }
2011 } else if ((readSize % sizeof(struct input_event)) != 0) {
2012 ALOGE("could not get event (wrong size: %d)", readSize);
2013 } else {
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002014 const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002015
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002016 const size_t count = size_t(readSize) / sizeof(struct input_event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002017 for (size_t i = 0; i < count; i++) {
2018 struct input_event& iev = readBuffer[i];
Prabir Pradhan9762ac92023-07-13 21:45:12 +00002019 device->trackInputEvent(iev);
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002020 events.push_back({
2021 .when = processEventTimestamp(iev),
2022 .readTime = systemTime(SYSTEM_TIME_MONOTONIC),
2023 .deviceId = deviceId,
2024 .type = iev.type,
2025 .code = iev.code,
2026 .value = iev.value,
2027 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08002028 }
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07002029 if (events.size() >= EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002030 // The result buffer is full. Reset the pending event index
2031 // so we will try to read the device again on the next iteration.
2032 mPendingEventIndex -= 1;
2033 break;
2034 }
2035 }
2036 } else if (eventItem.events & EPOLLHUP) {
2037 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002038 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002039 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07002040 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002041 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002042 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
2043 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002044 }
2045 }
2046
2047 // readNotify() will modify the list of devices so this must be done after
2048 // processing all other events to ensure that we read all remaining events
2049 // before closing the devices.
2050 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
2051 mPendingINotify = false;
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002052 const auto res = readNotifyLocked();
2053 if (!res.ok()) {
2054 ALOGW("Failed to read from inotify: %s", res.error().message().c_str());
2055 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002056 deviceChanged = true;
2057 }
2058
2059 // Report added or removed devices immediately.
2060 if (deviceChanged) {
2061 continue;
2062 }
2063
2064 // Return now if we have collected any events or if we were explicitly awoken.
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002065 if (!events.empty() || awoken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002066 break;
2067 }
2068
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01002069 // Poll for events.
2070 // When a device driver has pending (unread) events, it acquires
2071 // a kernel wake lock. Once the last pending event has been read, the device
2072 // driver will release the kernel wake lock, but the epoll will hold the wakelock,
2073 // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
2074 // is called again for the same fd that produced the event.
2075 // Thus the system can only sleep if there are no events pending or
2076 // currently being processed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002077 //
2078 // The timeout is advisory only. If the device is asleep, it will not wake just to
2079 // service the timeout.
2080 mPendingEventIndex = 0;
2081
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01002082 mLock.unlock(); // release lock before poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08002083
2084 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
2085
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01002086 mLock.lock(); // reacquire lock after poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08002087
2088 if (pollResult == 0) {
2089 // Timed out.
2090 mPendingEventCount = 0;
2091 break;
2092 }
2093
2094 if (pollResult < 0) {
2095 // An error occurred.
2096 mPendingEventCount = 0;
2097
2098 // Sleep after errors to avoid locking up the system.
2099 // Hopefully the error is transient.
2100 if (errno != EINTR) {
2101 ALOGW("poll failed (errno=%d)\n", errno);
2102 usleep(100000);
2103 }
2104 } else {
2105 // Some events occurred.
2106 mPendingEventCount = size_t(pollResult);
2107 }
2108 }
2109
2110 // All done, return the number of events we read.
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002111 return events;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002112}
2113
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08002114std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002115 std::scoped_lock _l(mLock);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08002116
2117 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07002118 if (device == nullptr || !device->videoDevice) {
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08002119 return {};
2120 }
2121 return device->videoDevice->consumeFrames();
2122}
2123
Michael Wrightd02c5b62014-02-10 15:10:22 -08002124void EventHub::wake() {
2125 ALOGV("wake() called");
2126
2127 ssize_t nWrite;
2128 do {
2129 nWrite = write(mWakeWritePipeFd, "W", 1);
2130 } while (nWrite == -1 && errno == EINTR);
2131
2132 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002133 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002134 }
2135}
2136
2137void EventHub::scanDevicesLocked() {
Usama Arifb27c8e62021-06-03 16:44:09 +01002138 status_t result;
2139 std::error_code errorCode;
2140
2141 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
2142 result = scanDirLocked(DEVICE_INPUT_PATH);
2143 if (result < 0) {
2144 ALOGE("scan dir failed for %s", DEVICE_INPUT_PATH);
2145 }
2146 } else {
2147 if (errorCode) {
2148 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
2149 errorCode.message().c_str());
2150 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002151 }
Philip Quinn39b81682019-01-09 22:20:39 -08002152 if (isV4lScanningEnabled()) {
Usama Arifb27c8e62021-06-03 16:44:09 +01002153 result = scanVideoDirLocked(DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08002154 if (result != OK) {
Usama Arifb27c8e62021-06-03 16:44:09 +01002155 ALOGE("scan video dir failed for %s", DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08002156 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002157 }
Chris Ye989bb932020-07-04 16:18:59 -07002158 if (mDevices.find(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) == mDevices.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002159 createVirtualKeyboardLocked();
2160 }
2161}
2162
2163// ----------------------------------------------------------------------------
2164
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002165status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002166 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002167 struct epoll_event eventItem = {};
2168 eventItem.events = EPOLLIN | EPOLLWAKEUP;
2169 eventItem.data.fd = fd;
2170 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
2171 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002172 return -errno;
2173 }
2174 return OK;
2175}
2176
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002177status_t EventHub::unregisterFdFromEpoll(int fd) {
2178 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
2179 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
2180 return -errno;
2181 }
2182 return OK;
2183}
2184
Chris Ye989bb932020-07-04 16:18:59 -07002185status_t EventHub::registerDeviceForEpollLocked(Device& device) {
2186 status_t result = registerFdForEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002187 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07002188 ALOGE("Could not add input device fd to epoll for device %" PRId32, device.id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002189 return result;
2190 }
Chris Ye989bb932020-07-04 16:18:59 -07002191 if (device.videoDevice) {
2192 registerVideoDeviceForEpollLocked(*device.videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002193 }
2194 return result;
2195}
2196
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002197void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
2198 status_t result = registerFdForEpoll(videoDevice.getFd());
2199 if (result != OK) {
2200 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
2201 }
2202}
2203
Chris Ye989bb932020-07-04 16:18:59 -07002204status_t EventHub::unregisterDeviceFromEpollLocked(Device& device) {
2205 if (device.hasValidFd()) {
2206 status_t result = unregisterFdFromEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002207 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07002208 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device.id);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002209 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002210 }
2211 }
Chris Ye989bb932020-07-04 16:18:59 -07002212 if (device.videoDevice) {
2213 unregisterVideoDeviceFromEpollLocked(*device.videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002214 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002215 return OK;
2216}
2217
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002218void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
2219 if (videoDevice.hasValidFd()) {
2220 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
2221 if (result != OK) {
2222 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002223 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002224 }
2225 }
2226}
2227
Chris Yed3fef462021-03-07 17:10:08 -08002228void EventHub::reportDeviceAddedForStatisticsLocked(const InputDeviceIdentifier& identifier,
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002229 ftl::Flags<InputDeviceClass> classes) {
Chris Ye657c2f02021-05-25 16:24:37 -07002230 SHA256_CTX ctx;
2231 SHA256_Init(&ctx);
2232 SHA256_Update(&ctx, reinterpret_cast<const uint8_t*>(identifier.uniqueId.c_str()),
2233 identifier.uniqueId.size());
2234 std::array<uint8_t, SHA256_DIGEST_LENGTH> digest;
2235 SHA256_Final(digest.data(), &ctx);
2236
2237 std::string obfuscatedId;
2238 for (size_t i = 0; i < OBFUSCATED_LENGTH; i++) {
2239 obfuscatedId += StringPrintf("%02x", digest[i]);
2240 }
2241
Chris Yed3fef462021-03-07 17:10:08 -08002242 android::util::stats_write(android::util::INPUTDEVICE_REGISTERED, identifier.name.c_str(),
2243 identifier.vendor, identifier.product, identifier.version,
Chris Ye657c2f02021-05-25 16:24:37 -07002244 identifier.bus, obfuscatedId.c_str(), classes.get());
Chris Yed3fef462021-03-07 17:10:08 -08002245}
2246
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002247void EventHub::openDeviceLocked(const std::string& devicePath) {
2248 // If an input device happens to register around the time when EventHub's constructor runs, it
2249 // is possible that the same input event node (for example, /dev/input/event3) will be noticed
2250 // in both 'inotify' callback and also in the 'scanDirLocked' pass. To prevent duplicate devices
2251 // from getting registered, ensure that this path is not already covered by an existing device.
2252 for (const auto& [deviceId, device] : mDevices) {
2253 if (device->path == devicePath) {
2254 return; // device was already registered
2255 }
2256 }
2257
Michael Wrightd02c5b62014-02-10 15:10:22 -08002258 char buffer[80];
2259
Chris Ye8594e192020-07-14 10:34:06 -07002260 ALOGV("Opening device: %s", devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002261
Chris Ye8594e192020-07-14 10:34:06 -07002262 int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002263 if (fd < 0) {
Chris Ye8594e192020-07-14 10:34:06 -07002264 ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002265 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002266 }
2267
2268 InputDeviceIdentifier identifier;
2269
2270 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002271 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Chris Ye8594e192020-07-14 10:34:06 -07002272 ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002273 } else {
2274 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002275 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002276 }
2277
2278 // Check to see if the device is on our excluded list
2279 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002280 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002281 if (identifier.name == item) {
Chris Ye8594e192020-07-14 10:34:06 -07002282 ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002283 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002284 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002285 }
2286 }
2287
2288 // Get device driver version.
2289 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002290 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Chris Ye8594e192020-07-14 10:34:06 -07002291 ALOGE("could not get driver version for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002292 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002293 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002294 }
2295
2296 // Get device identifier.
2297 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002298 if (ioctl(fd, EVIOCGID, &inputId)) {
Chris Ye8594e192020-07-14 10:34:06 -07002299 ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002300 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002301 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002302 }
2303 identifier.bus = inputId.bustype;
2304 identifier.product = inputId.product;
2305 identifier.vendor = inputId.vendor;
2306 identifier.version = inputId.version;
2307
2308 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002309 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
2310 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002311 } else {
2312 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002313 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002314 }
2315
2316 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002317 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
2318 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002319 } else {
2320 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002321 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002322 }
2323
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002324 // Attempt to get the bluetooth address of an input device from the uniqueId.
2325 if (identifier.bus == BUS_BLUETOOTH &&
2326 std::regex_match(identifier.uniqueId,
2327 std::regex("^[A-Fa-f0-9]{2}(?::[A-Fa-f0-9]{2}){5}$"))) {
2328 identifier.bluetoothAddress = identifier.uniqueId;
2329 // The Bluetooth stack requires alphabetic characters to be uppercase in a valid address.
2330 for (auto& c : *identifier.bluetoothAddress) {
2331 c = ::toupper(c);
2332 }
2333 }
2334
Michael Wrightd02c5b62014-02-10 15:10:22 -08002335 // Fill in the descriptor.
2336 assignDescriptorLocked(identifier);
2337
Michael Wrightd02c5b62014-02-10 15:10:22 -08002338 // Allocate device. (The device object takes ownership of the fd at this point.)
2339 int32_t deviceId = mNextDeviceId++;
Prabir Pradhancb42b472022-08-23 16:01:19 +00002340 std::unique_ptr<Device> device =
2341 std::make_unique<Device>(fd, deviceId, devicePath, identifier,
2342 obtainAssociatedDeviceLocked(devicePath));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002343
Chris Ye8594e192020-07-14 10:34:06 -07002344 ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002345 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002346 " vendor %04x\n"
2347 " product %04x\n"
2348 " version %04x\n",
2349 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002350 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
2351 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
2352 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
2353 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002354 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
2355 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002356
2357 // Load the configuration file for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002358 device->loadConfigurationLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002359
2360 // Figure out the kinds of events the device reports.
Chris Ye66fbac32020-07-06 20:36:43 -07002361 device->readDeviceBitMask(EVIOCGBIT(EV_KEY, 0), device->keyBitmask);
2362 device->readDeviceBitMask(EVIOCGBIT(EV_ABS, 0), device->absBitmask);
2363 device->readDeviceBitMask(EVIOCGBIT(EV_REL, 0), device->relBitmask);
2364 device->readDeviceBitMask(EVIOCGBIT(EV_SW, 0), device->swBitmask);
2365 device->readDeviceBitMask(EVIOCGBIT(EV_LED, 0), device->ledBitmask);
2366 device->readDeviceBitMask(EVIOCGBIT(EV_FF, 0), device->ffBitmask);
Chris Yef59a2f42020-10-16 12:55:26 -07002367 device->readDeviceBitMask(EVIOCGBIT(EV_MSC, 0), device->mscBitmask);
Chris Ye66fbac32020-07-06 20:36:43 -07002368 device->readDeviceBitMask(EVIOCGPROP(0), device->propBitmask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002369
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002370 // See if this is a device with keys. This could be full keyboard, or other devices like
2371 // gamepads, joysticks, and styluses with buttons that should generate key presses.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002372 bool haveKeyboardKeys =
Chris Ye66fbac32020-07-06 20:36:43 -07002373 device->keyBitmask.any(0, BTN_MISC) || device->keyBitmask.any(BTN_WHEEL, KEY_MAX + 1);
2374 bool haveGamepadButtons = device->keyBitmask.any(BTN_MISC, BTN_MOUSE) ||
2375 device->keyBitmask.any(BTN_JOYSTICK, BTN_DIGI);
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002376 bool haveStylusButtons = device->keyBitmask.test(BTN_STYLUS) ||
2377 device->keyBitmask.test(BTN_STYLUS2) || device->keyBitmask.test(BTN_STYLUS3);
2378 if (haveKeyboardKeys || haveGamepadButtons || haveStylusButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002379 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002380 }
2381
2382 // See if this is a cursor device such as a trackball or mouse.
Chris Ye66fbac32020-07-06 20:36:43 -07002383 if (device->keyBitmask.test(BTN_MOUSE) && device->relBitmask.test(REL_X) &&
2384 device->relBitmask.test(REL_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002385 device->classes |= InputDeviceClass::CURSOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002386 }
2387
Prabir Pradhana3621852022-10-14 18:57:23 +00002388 // See if the device is specially configured to be of a certain type.
Harry Cuttsf13161a2023-03-08 14:15:49 +00002389 if (device->configuration) {
2390 std::string deviceType = device->configuration->getString("device.type").value_or("");
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07002391 if (deviceType == "rotaryEncoder") {
Chris Ye1b0c7342020-07-28 21:57:03 -07002392 device->classes |= InputDeviceClass::ROTARY_ENCODER;
Prabir Pradhana3621852022-10-14 18:57:23 +00002393 } else if (deviceType == "externalStylus") {
2394 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002395 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002396 }
2397
Michael Wrightd02c5b62014-02-10 15:10:22 -08002398 // See if this is a touch pad.
2399 // Is this a new modern multi-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002400 if (device->absBitmask.test(ABS_MT_POSITION_X) && device->absBitmask.test(ABS_MT_POSITION_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002401 // Some joysticks such as the PS3 controller report axes that conflict
2402 // with the ABS_MT range. Try to confirm that the device really is
2403 // a touch screen.
Chris Ye66fbac32020-07-06 20:36:43 -07002404 if (device->keyBitmask.test(BTN_TOUCH) || !haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002405 device->classes |= (InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT);
Harry Cutts79cc9fa2022-10-28 15:32:39 +00002406 if (device->propBitmask.test(INPUT_PROP_POINTER) &&
2407 !device->keyBitmask.any(BTN_TOOL_PEN, BTN_TOOL_FINGER) && !haveStylusButtons) {
2408 device->classes |= InputDeviceClass::TOUCHPAD;
2409 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002410 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002411 // Is this an old style single-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002412 } else if (device->keyBitmask.test(BTN_TOUCH) && device->absBitmask.test(ABS_X) &&
2413 device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002414 device->classes |= InputDeviceClass::TOUCH;
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002415 // Is this a stylus that reports contact/pressure independently of touch coordinates?
Chris Ye66fbac32020-07-06 20:36:43 -07002416 } else if ((device->absBitmask.test(ABS_PRESSURE) || device->keyBitmask.test(BTN_TOUCH)) &&
2417 !device->absBitmask.test(ABS_X) && !device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002418 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002419 }
2420
2421 // See if this device is a joystick.
2422 // Assumes that joysticks always have gamepad buttons in order to distinguish them
2423 // from other devices such as accelerometers that also have absolute axes.
2424 if (haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002425 auto assumedClasses = device->classes | InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002426 for (int i = 0; i <= ABS_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002427 if (device->absBitmask.test(i) &&
Chris Ye1b0c7342020-07-28 21:57:03 -07002428 (getAbsAxisUsage(i, assumedClasses).test(InputDeviceClass::JOYSTICK))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002429 device->classes = assumedClasses;
2430 break;
2431 }
2432 }
2433 }
2434
Chris Yef59a2f42020-10-16 12:55:26 -07002435 // Check whether this device is an accelerometer.
2436 if (device->propBitmask.test(INPUT_PROP_ACCELEROMETER)) {
2437 device->classes |= InputDeviceClass::SENSOR;
2438 }
2439
Michael Wrightd02c5b62014-02-10 15:10:22 -08002440 // Check whether this device has switches.
2441 for (int i = 0; i <= SW_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002442 if (device->swBitmask.test(i)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002443 device->classes |= InputDeviceClass::SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002444 break;
2445 }
2446 }
2447
2448 // Check whether this device supports the vibrator.
Chris Ye66fbac32020-07-06 20:36:43 -07002449 if (device->ffBitmask.test(FF_RUMBLE)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002450 device->classes |= InputDeviceClass::VIBRATOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002451 }
2452
2453 // Configure virtual keys.
Chris Ye1b0c7342020-07-28 21:57:03 -07002454 if ((device->classes.test(InputDeviceClass::TOUCH))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002455 // Load the virtual keys for the touch screen, if any.
2456 // We do this now so that we can make sure to load the keymap if necessary.
Chris Ye989bb932020-07-04 16:18:59 -07002457 bool success = device->loadVirtualKeyMapLocked();
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06002458 if (success) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002459 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002460 }
2461 }
2462
2463 // Load the key map.
Chris Yef59a2f42020-10-16 12:55:26 -07002464 // We need to do this for joysticks too because the key layout may specify axes, and for
2465 // sensor as well because the key layout may specify the axes to sensor data mapping.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002466 status_t keyMapStatus = NAME_NOT_FOUND;
Chris Yef59a2f42020-10-16 12:55:26 -07002467 if (device->classes.any(InputDeviceClass::KEYBOARD | InputDeviceClass::JOYSTICK |
2468 InputDeviceClass::SENSOR)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002469 // Load the keymap for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002470 keyMapStatus = device->loadKeyMapLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002471 }
2472
2473 // Configure the keyboard, gamepad or virtual keyboard.
Chris Ye1b0c7342020-07-28 21:57:03 -07002474 if (device->classes.test(InputDeviceClass::KEYBOARD)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002475 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002476 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002477 isEligibleBuiltInKeyboard(device->identifier, device->configuration.get(),
2478 &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002479 mBuiltInKeyboardId = device->id;
2480 }
2481
2482 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
Chris Ye989bb932020-07-04 16:18:59 -07002483 if (device->hasKeycodeLocked(AKEYCODE_Q)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002484 device->classes |= InputDeviceClass::ALPHAKEY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002485 }
2486
Prabir Pradhanae10ee62023-05-12 19:44:18 +00002487 // See if this device has a D-pad.
2488 if (std::all_of(DPAD_REQUIRED_KEYCODES.begin(), DPAD_REQUIRED_KEYCODES.end(),
2489 [&](int32_t keycode) { return device->hasKeycodeLocked(keycode); })) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002490 device->classes |= InputDeviceClass::DPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002491 }
2492
2493 // See if this device has a gamepad.
Prabir Pradhanae10ee62023-05-12 19:44:18 +00002494 if (std::any_of(GAMEPAD_KEYCODES.begin(), GAMEPAD_KEYCODES.end(),
2495 [&](int32_t keycode) { return device->hasKeycodeLocked(keycode); })) {
2496 device->classes |= InputDeviceClass::GAMEPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002497 }
Prabir Pradhana3621852022-10-14 18:57:23 +00002498
2499 // See if this device has any stylus buttons that we would want to fuse with touch data.
Prabir Pradhanae10ee62023-05-12 19:44:18 +00002500 if (!device->classes.any(InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT) &&
Prabir Pradhan3c28b942023-08-18 20:02:01 +00002501 !device->classes.any(InputDeviceClass::ALPHAKEY) &&
Prabir Pradhanae10ee62023-05-12 19:44:18 +00002502 std::any_of(STYLUS_BUTTON_KEYCODES.begin(), STYLUS_BUTTON_KEYCODES.end(),
2503 [&](int32_t keycode) { return device->hasKeycodeLocked(keycode); })) {
2504 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Prabir Pradhana3621852022-10-14 18:57:23 +00002505 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002506 }
2507
Vladimir Komsiyskidd438e22024-02-13 11:47:54 +01002508 // See if the device is a rotary encoder with a single scroll axis and nothing else.
2509 if (vd_flags::virtual_rotary() && device->classes == ftl::Flags<InputDeviceClass>(0) &&
2510 device->relBitmask.test(REL_WHEEL) && !device->relBitmask.test(REL_HWHEEL)) {
2511 device->classes |= InputDeviceClass::ROTARY_ENCODER;
2512 }
2513
Michael Wrightd02c5b62014-02-10 15:10:22 -08002514 // If the device isn't recognized as something we handle, don't monitor it.
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002515 if (device->classes == ftl::Flags<InputDeviceClass>(0)) {
Chris Ye8594e192020-07-14 10:34:06 -07002516 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002517 device->identifier.name.c_str());
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002518 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002519 }
2520
Chris Ye3fdbfef2021-01-06 18:45:18 -08002521 // Classify InputDeviceClass::BATTERY.
Prabir Pradhan51894782022-08-23 16:29:10 +00002522 if (device->associatedDevice && !device->associatedDevice->batteryInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002523 device->classes |= InputDeviceClass::BATTERY;
2524 }
Kim Low03ea0352020-11-06 12:45:07 -08002525
Chris Ye3fdbfef2021-01-06 18:45:18 -08002526 // Classify InputDeviceClass::LIGHT.
Prabir Pradhan51894782022-08-23 16:29:10 +00002527 if (device->associatedDevice && !device->associatedDevice->lightInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002528 device->classes |= InputDeviceClass::LIGHT;
Kim Low03ea0352020-11-06 12:45:07 -08002529 }
2530
Tim Kilbourn063ff532015-04-08 10:26:18 -07002531 // Determine whether the device has a mic.
Chris Ye989bb932020-07-04 16:18:59 -07002532 if (device->deviceHasMicLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002533 device->classes |= InputDeviceClass::MIC;
Tim Kilbourn063ff532015-04-08 10:26:18 -07002534 }
2535
Michael Wrightd02c5b62014-02-10 15:10:22 -08002536 // Determine whether the device is external or internal.
Chris Ye989bb932020-07-04 16:18:59 -07002537 if (device->isExternalDeviceLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002538 device->classes |= InputDeviceClass::EXTERNAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002539 }
2540
Chris Ye1b0c7342020-07-28 21:57:03 -07002541 if (device->classes.any(InputDeviceClass::JOYSTICK | InputDeviceClass::DPAD) &&
2542 device->classes.test(InputDeviceClass::GAMEPAD)) {
Chris Ye989bb932020-07-04 16:18:59 -07002543 device->controllerNumber = getNextControllerNumberLocked(device->identifier.name);
2544 device->setLedForControllerLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002545 }
2546
Chris Ye989bb932020-07-04 16:18:59 -07002547 if (registerDeviceForEpollLocked(*device) != OK) {
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002548 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002549 }
2550
Chris Ye989bb932020-07-04 16:18:59 -07002551 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002552
Chris Ye1b0c7342020-07-28 21:57:03 -07002553 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=%s, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002554 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Chris Ye1b0c7342020-07-28 21:57:03 -07002555 deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(),
2556 device->classes.string().c_str(), device->configurationFile.c_str(),
2557 device->keyMap.keyLayoutFile.c_str(), device->keyMap.keyCharacterMapFile.c_str(),
2558 toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002559
Chris Ye989bb932020-07-04 16:18:59 -07002560 addDeviceLocked(std::move(device));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002561}
2562
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002563void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
2564 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
2565 if (!videoDevice) {
2566 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
2567 return;
2568 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002569 // Transfer ownership of this video device to a matching input device
Chris Ye989bb932020-07-04 16:18:59 -07002570 for (const auto& [id, device] : mDevices) {
Chris Yed3fef462021-03-07 17:10:08 -08002571 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002572 return; // 'device' now owns 'videoDevice'
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002573 }
2574 }
2575
2576 // Couldn't find a matching input device, so just add it to a temporary holding queue.
2577 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002578 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002579 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002580 mUnattachedVideoDevices.push_back(std::move(videoDevice));
2581}
2582
Chris Yed3fef462021-03-07 17:10:08 -08002583bool EventHub::tryAddVideoDeviceLocked(EventHub::Device& device,
2584 std::unique_ptr<TouchVideoDevice>& videoDevice) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002585 if (videoDevice->getName() != device.identifier.name) {
2586 return false;
2587 }
2588 device.videoDevice = std::move(videoDevice);
2589 if (device.enabled) {
2590 registerVideoDeviceForEpollLocked(*device.videoDevice);
2591 }
2592 return true;
2593}
2594
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002595bool EventHub::isDeviceEnabled(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00002596 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002597 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002598 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002599 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2600 return false;
2601 }
2602 return device->enabled;
2603}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002604
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002605status_t EventHub::enableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002606 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002607 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002608 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002609 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2610 return BAD_VALUE;
2611 }
2612 if (device->enabled) {
2613 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
2614 return OK;
2615 }
2616 status_t result = device->enable();
2617 if (result != OK) {
2618 ALOGE("Failed to enable device %" PRId32, deviceId);
2619 return result;
2620 }
2621
Chris Ye989bb932020-07-04 16:18:59 -07002622 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002623
Chris Ye989bb932020-07-04 16:18:59 -07002624 return registerDeviceForEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002625}
2626
2627status_t EventHub::disableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002628 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002629 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002630 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002631 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2632 return BAD_VALUE;
2633 }
2634 if (!device->enabled) {
2635 ALOGW("Duplicate call to %s, input device already disabled", __func__);
2636 return OK;
2637 }
Chris Ye989bb932020-07-04 16:18:59 -07002638 unregisterDeviceFromEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002639 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002640}
2641
Vaibhav Devmurari5fc7d852023-03-17 18:43:33 +00002642// TODO(b/274755573): Shift to uevent handling on native side and remove this method
2643// Currently using Java UEventObserver to trigger this which uses UEvent infrastructure that uses a
2644// NETLINK socket to observe UEvents. We can create similar infrastructure on Eventhub side to
2645// directly observe UEvents instead of triggering from Java side.
2646void EventHub::sysfsNodeChanged(const std::string& sysfsNodePath) {
2647 std::scoped_lock _l(mLock);
2648
2649 // Check in opening devices
2650 for (auto it = mOpeningDevices.begin(); it != mOpeningDevices.end(); it++) {
2651 std::unique_ptr<Device>& device = *it;
2652 if (device->associatedDevice &&
2653 sysfsNodePath.find(device->associatedDevice->sysfsRootPath.string()) !=
2654 std::string::npos &&
2655 device->associatedDevice->isChanged()) {
2656 it = mOpeningDevices.erase(it);
2657 openDeviceLocked(device->path);
2658 }
2659 }
2660
2661 // Check in already added device
2662 std::vector<Device*> devicesToReopen;
2663 for (const auto& [id, device] : mDevices) {
2664 if (device->associatedDevice &&
2665 sysfsNodePath.find(device->associatedDevice->sysfsRootPath.string()) !=
2666 std::string::npos &&
2667 device->associatedDevice->isChanged()) {
2668 devicesToReopen.push_back(device.get());
2669 }
2670 }
2671 for (const auto& device : devicesToReopen) {
2672 closeDeviceLocked(*device);
2673 openDeviceLocked(device->path);
2674 }
2675 devicesToReopen.clear();
2676}
2677
Michael Wrightd02c5b62014-02-10 15:10:22 -08002678void EventHub::createVirtualKeyboardLocked() {
2679 InputDeviceIdentifier identifier;
2680 identifier.name = "Virtual";
2681 identifier.uniqueId = "<virtual>";
2682 assignDescriptorLocked(identifier);
2683
Chris Ye989bb932020-07-04 16:18:59 -07002684 std::unique_ptr<Device> device =
2685 std::make_unique<Device>(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
Harry Cutts33476232023-01-30 19:57:29 +00002686 identifier, /*associatedDevice=*/nullptr);
Chris Ye1b0c7342020-07-28 21:57:03 -07002687 device->classes = InputDeviceClass::KEYBOARD | InputDeviceClass::ALPHAKEY |
2688 InputDeviceClass::DPAD | InputDeviceClass::VIRTUAL;
Chris Ye989bb932020-07-04 16:18:59 -07002689 device->loadKeyMapLocked();
2690 addDeviceLocked(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002691}
2692
Chris Ye989bb932020-07-04 16:18:59 -07002693void EventHub::addDeviceLocked(std::unique_ptr<Device> device) {
Chris Yed3fef462021-03-07 17:10:08 -08002694 reportDeviceAddedForStatisticsLocked(device->identifier, device->classes);
Chris Ye989bb932020-07-04 16:18:59 -07002695 mOpeningDevices.push_back(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002696}
2697
Chris Ye989bb932020-07-04 16:18:59 -07002698int32_t EventHub::getNextControllerNumberLocked(const std::string& name) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002699 if (mControllerNumbers.isFull()) {
2700 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Chris Ye989bb932020-07-04 16:18:59 -07002701 name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002702 return 0;
2703 }
2704 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
2705 // one
2706 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
2707}
2708
Chris Ye989bb932020-07-04 16:18:59 -07002709void EventHub::releaseControllerNumberLocked(int32_t num) {
2710 if (num > 0) {
2711 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002712 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002713}
2714
Chris Ye8594e192020-07-14 10:34:06 -07002715void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002716 Device* device = getDeviceByPathLocked(devicePath);
Chris Ye989bb932020-07-04 16:18:59 -07002717 if (device != nullptr) {
2718 closeDeviceLocked(*device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002719 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002720 }
Chris Ye8594e192020-07-14 10:34:06 -07002721 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002722}
2723
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002724/**
2725 * Find the video device by filename, and close it.
2726 * The video device is closed by path during an inotify event, where we don't have the
2727 * additional context about the video device fd, or the associated input device.
2728 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002729void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002730 // A video device may be owned by an existing input device, or it may be stored in
2731 // the mUnattachedVideoDevices queue. Check both locations.
Chris Ye989bb932020-07-04 16:18:59 -07002732 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002733 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002734 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002735 device->videoDevice = nullptr;
2736 return;
2737 }
2738 }
Siarhei Vishniakouf47c339e2021-12-30 11:22:26 -08002739 std::erase_if(mUnattachedVideoDevices,
2740 [&devicePath](const std::unique_ptr<TouchVideoDevice>& videoDevice) {
2741 return videoDevice->getPath() == devicePath;
2742 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08002743}
2744
2745void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002746 mUnattachedVideoDevices.clear();
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002747 while (!mDevices.empty()) {
2748 closeDeviceLocked(*(mDevices.begin()->second));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002749 }
2750}
2751
Chris Ye989bb932020-07-04 16:18:59 -07002752void EventHub::closeDeviceLocked(Device& device) {
2753 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=%s", device.path.c_str(),
2754 device.identifier.name.c_str(), device.id, device.fd, device.classes.string().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002755
Chris Ye989bb932020-07-04 16:18:59 -07002756 if (device.id == mBuiltInKeyboardId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002757 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Chris Ye989bb932020-07-04 16:18:59 -07002758 device.path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002759 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
2760 }
2761
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002762 unregisterDeviceFromEpollLocked(device);
Chris Ye989bb932020-07-04 16:18:59 -07002763 if (device.videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002764 // This must be done after the video device is removed from epoll
Chris Ye989bb932020-07-04 16:18:59 -07002765 mUnattachedVideoDevices.push_back(std::move(device.videoDevice));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002766 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002767
Chris Ye989bb932020-07-04 16:18:59 -07002768 releaseControllerNumberLocked(device.controllerNumber);
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002769 device.controllerNumber = 0;
Chris Ye989bb932020-07-04 16:18:59 -07002770 device.close();
Chris Ye989bb932020-07-04 16:18:59 -07002771 mClosingDevices.push_back(std::move(mDevices[device.id]));
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002772
Chris Ye989bb932020-07-04 16:18:59 -07002773 mDevices.erase(device.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002774}
2775
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002776base::Result<void> EventHub::readNotifyLocked() {
2777 static constexpr auto EVENT_SIZE = static_cast<ssize_t>(sizeof(inotify_event));
2778 uint8_t eventBuffer[512];
2779 ssize_t sizeRead;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002780
2781 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002782 do {
2783 sizeRead = read(mINotifyFd, eventBuffer, sizeof(eventBuffer));
2784 } while (sizeRead < 0 && errno == EINTR);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002785
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002786 if (sizeRead < EVENT_SIZE) return Errorf("could not get event, %s", strerror(errno));
2787
2788 for (ssize_t eventPos = 0; sizeRead >= EVENT_SIZE;) {
2789 const inotify_event* event;
2790 event = (const inotify_event*)(eventBuffer + eventPos);
2791 if (event->len == 0) continue;
2792
2793 handleNotifyEventLocked(*event);
2794
2795 const ssize_t eventSize = EVENT_SIZE + event->len;
2796 sizeRead -= eventSize;
2797 eventPos += eventSize;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002798 }
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002799 return {};
2800}
2801
2802void EventHub::handleNotifyEventLocked(const inotify_event& event) {
2803 if (event.wd == mDeviceInputWd) {
2804 std::string filename = std::string(DEVICE_INPUT_PATH) + "/" + event.name;
2805 if (event.mask & IN_CREATE) {
2806 openDeviceLocked(filename);
2807 } else {
2808 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
2809 closeDeviceByPathLocked(filename);
2810 }
2811 } else if (event.wd == mDeviceWd) {
2812 if (isV4lTouchNode(event.name)) {
2813 std::string filename = std::string(DEVICE_PATH) + "/" + event.name;
2814 if (event.mask & IN_CREATE) {
2815 openVideoDeviceLocked(filename);
2816 } else {
2817 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
2818 closeVideoDeviceByPathLocked(filename);
2819 }
2820 } else if (strcmp(event.name, "input") == 0 && event.mask & IN_CREATE) {
2821 addDeviceInputInotify();
2822 }
2823 } else {
2824 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event.wd);
2825 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002826}
2827
Chris Ye8594e192020-07-14 10:34:06 -07002828status_t EventHub::scanDirLocked(const std::string& dirname) {
2829 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2830 openDeviceLocked(entry.path());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002831 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002832 return 0;
2833}
2834
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002835/**
2836 * Look for all dirname/v4l-touch* devices, and open them.
2837 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002838status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Chris Ye8594e192020-07-14 10:34:06 -07002839 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2840 if (isV4lTouchNode(entry.path())) {
2841 ALOGI("Found touch video device %s", entry.path().c_str());
2842 openVideoDeviceLocked(entry.path());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002843 }
2844 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002845 return OK;
2846}
2847
Michael Wrightd02c5b62014-02-10 15:10:22 -08002848void EventHub::requestReopenDevices() {
2849 ALOGV("requestReopenDevices() called");
2850
Chris Ye87143712020-11-10 05:05:58 +00002851 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002852 mNeedToReopenDevices = true;
2853}
2854
Yanye Li81a590c2024-10-22 19:25:54 +00002855bool EventHub::setKernelWakeEnabled(int32_t deviceId, bool enabled) {
2856 std::scoped_lock _l(mLock);
2857 std::string enabledStr = enabled ? "enabled" : "disabled";
2858 Device* device = getDeviceLocked(deviceId);
2859 if (device == nullptr) {
2860 ALOGE("Device Id %d does not exist for setting power wakeup", deviceId);
2861 return false;
2862 }
2863 if (device->associatedDevice == nullptr) {
2864 return false;
2865 }
2866 std::filesystem::path currentPath = device->associatedDevice->sysfsRootPath;
2867 while (!currentPath.empty() && currentPath != "/") {
2868 std::string nodePath = currentPath / "power/wakeup";
2869 if (std::filesystem::exists(nodePath)) {
2870 if (base::WriteStringToFile(enabledStr, nodePath)) {
2871 return true;
2872
2873 }
2874 // No need to continue searching in parent directories as power/wakeup nodes
2875 // higher up may control other subdevices.
2876 ALOGW("Failed to set power/wakeup node at %s", nodePath.c_str());
2877 return false;
2878 }
2879 currentPath = currentPath.parent_path();
2880 }
2881 return false;
2882}
2883
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002884void EventHub::dump(std::string& dump) const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002885 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002886
2887 { // acquire lock
Chris Ye87143712020-11-10 05:05:58 +00002888 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002889
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002890 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002891
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002892 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002893
Chris Ye989bb932020-07-04 16:18:59 -07002894 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002895 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002896 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002897 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002898 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002899 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002900 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002901 }
Chris Ye1b0c7342020-07-28 21:57:03 -07002902 dump += StringPrintf(INDENT3 "Classes: %s\n", device->classes.string().c_str());
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002903 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002904 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002905 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
2906 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002907 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002908 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002909 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002910 "product=0x%04x, version=0x%04x, bluetoothAddress=%s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002911 device->identifier.bus, device->identifier.vendor,
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002912 device->identifier.product, device->identifier.version,
2913 toString(device->identifier.bluetoothAddress).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002914 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002915 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002916 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002917 device->keyMap.keyCharacterMapFile.c_str());
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00002918 if (device->associatedDevice && device->associatedDevice->layoutInfo) {
2919 dump += StringPrintf(INDENT3 "LanguageTag: %s\n",
2920 device->associatedDevice->layoutInfo->languageTag.c_str());
2921 dump += StringPrintf(INDENT3 "LayoutType: %s\n",
2922 device->associatedDevice->layoutInfo->layoutType.c_str());
2923 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002924 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002925 device->configurationFile.c_str());
Prabir Pradhan51894782022-08-23 16:29:10 +00002926 dump += StringPrintf(INDENT3 "VideoDevice: %s\n",
2927 device->videoDevice ? device->videoDevice->dump().c_str()
2928 : "<none>");
2929 dump += StringPrintf(INDENT3 "SysfsDevicePath: %s\n",
2930 device->associatedDevice
2931 ? device->associatedDevice->sysfsRootPath.c_str()
2932 : "<none>");
Prabir Pradhan955b6132023-07-14 19:44:34 +00002933 if (device->keyBitmask.any(0, KEY_MAX + 1)) {
2934 const auto pressedKeys = device->keyState.dumpSetIndices(", ", [](int i) {
2935 return InputEventLookup::getLinuxEvdevLabel(EV_KEY, i, 1).code;
2936 });
2937 dump += StringPrintf(INDENT3 "KeyState (pressed): %s\n", pressedKeys.c_str());
2938 }
2939 if (device->swBitmask.any(0, SW_MAX + 1)) {
2940 const auto pressedSwitches = device->swState.dumpSetIndices(", ", [](int i) {
2941 return InputEventLookup::getLinuxEvdevLabel(EV_SW, i, 1).code;
2942 });
2943 dump += StringPrintf(INDENT3 "SwState (pressed): %s\n", pressedSwitches.c_str());
2944 }
2945 if (!device->absState.empty()) {
2946 std::string axisValues;
2947 for (const auto& [axis, state] : device->absState) {
2948 if (!axisValues.empty()) {
2949 axisValues += ", ";
2950 }
2951 axisValues += StringPrintf("%s=%d",
2952 InputEventLookup::getLinuxEvdevLabel(EV_ABS, axis, 0)
2953 .code.c_str(),
2954 state.value);
2955 }
2956 dump += INDENT3 "AbsState: " + axisValues + "\n";
2957 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002958 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002959
2960 dump += INDENT "Unattached video devices:\n";
2961 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
2962 dump += INDENT2 + videoDevice->dump() + "\n";
2963 }
2964 if (mUnattachedVideoDevices.empty()) {
2965 dump += INDENT2 "<none>\n";
2966 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002967 } // release lock
2968}
2969
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002970void EventHub::monitor() const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002971 // Acquire and release the lock to ensure that the event hub has not deadlocked.
Chris Ye1c2e0892020-11-30 21:41:44 -08002972 std::unique_lock<std::mutex> lock(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002973}
2974
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00002975std::string EventHub::AssociatedDevice::dump() const {
2976 return StringPrintf("path=%s, numBatteries=%zu, numLight=%zu", sysfsRootPath.c_str(),
2977 batteryInfos.size(), lightInfos.size());
2978}
2979
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002980} // namespace android