1 /*
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
17 #include <assert.h>
18 #include <dirent.h>
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <inttypes.h>
22 #include <linux/ioctl.h>
23 #include <memory.h>
24 #include <stdint.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <sys/capability.h>
29 #include <sys/epoll.h>
30 #include <sys/inotify.h>
31 #include <sys/ioctl.h>
32 #include <sys/stat.h>
33 #include <sys/sysmacros.h>
34 #include <unistd.h>
35
36 #include <android_companion_virtualdevice_flags.h>
37
38 #define LOG_TAG "EventHub"
39
40 // #define LOG_NDEBUG 0
41 #include <android-base/file.h>
42 #include <android-base/stringprintf.h>
43 #include <android-base/strings.h>
44 #include <cutils/properties.h>
45 #include <ftl/enum.h>
46 #include <input/InputEventLabels.h>
47 #include <input/KeyCharacterMap.h>
48 #include <input/KeyLayoutMap.h>
49 #include <input/PrintTools.h>
50 #include <input/VirtualKeyMap.h>
51 #include <openssl/sha.h>
52 #include <statslog.h>
53 #include <utils/Errors.h>
54 #include <utils/Log.h>
55 #include <utils/Timers.h>
56
57 #include <filesystem>
58 #include <optional>
59 #include <regex>
60 #include <utility>
61
62 #include "EventHub.h"
63
64 #include "KeyCodeClassifications.h"
65
66 #define INDENT " "
67 #define INDENT2 " "
68 #define INDENT3 " "
69
70 using android::base::StringPrintf;
71
72 namespace android {
73
74 namespace vd_flags = android::companion::virtualdevice::flags;
75
76 using namespace ftl::flag_operators;
77
78 static const char* DEVICE_INPUT_PATH = "/dev/input";
79 // v4l2 devices go directly into /dev
80 static const char* DEVICE_PATH = "/dev";
81
82 static constexpr size_t OBFUSCATED_LENGTH = 8;
83
84 static constexpr int32_t FF_STRONG_MAGNITUDE_CHANNEL_IDX = 0;
85 static constexpr int32_t FF_WEAK_MAGNITUDE_CHANNEL_IDX = 1;
86
87 static constexpr size_t EVENT_BUFFER_SIZE = 256;
88
89 // Mapping for input battery class node IDs lookup.
90 // https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
91 static 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
98 static const std::unordered_map<InputBatteryClass, std::string> BATTERY_NODES =
99 {{InputBatteryClass::CAPACITY, "capacity"},
100 {InputBatteryClass::CAPACITY_LEVEL, "capacity_level"},
101 {InputBatteryClass::STATUS, "status"}};
102
103 // must be kept in sync with definitions in kernel /drivers/power/supply/power_supply_sysfs.c
104 static 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
113 static 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
120 // Mapping for input led class node names lookup.
121 // https://www.kernel.org/doc/html/latest/leds/leds-class.html
122 static 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},
130 {"max_brightness", InputLightClass::MAX_BRIGHTNESS},
131 {"kbd_backlight", InputLightClass::KEYBOARD_BACKLIGHT},
132 {"mic_mute", InputLightClass::KEYBOARD_MIC_MUTE},
133 {"mute", InputLightClass::KEYBOARD_VOLUME_MUTE}};
134
135 // Mapping for input multicolor led class node names.
136 // https://www.kernel.org/doc/html/latest/leds/leds-class-multicolor.html
137 static 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
143 const std::unordered_map<std::string, LightColor> LIGHT_COLORS = {{"red", LightColor::RED},
144 {"green", LightColor::GREEN},
145 {"blue", LightColor::BLUE}};
146
147 // Mapping for country code to Layout info.
148 // See bCountryCode in 6.2.1 of https://usb.org/sites/default/files/hid1_11.pdf.
149 const 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
sha1(const std::string & in)187 static std::string sha1(const std::string& in) {
188 SHA_CTX ctx;
189 SHA1_Init(&ctx);
190 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
191 u_char digest[SHA_DIGEST_LENGTH];
192 SHA1_Final(digest, &ctx);
193
194 std::string out;
195 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
196 out += StringPrintf("%02x", digest[i]);
197 }
198 return out;
199 }
200
201 /**
202 * Return true if name matches "v4l-touch*"
203 */
isV4lTouchNode(std::string name)204 static bool isV4lTouchNode(std::string name) {
205 return name.find("v4l-touch") != std::string::npos;
206 }
207
208 /**
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
214 * 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.
223 */
isV4lScanningEnabled()224 static bool isV4lScanningEnabled() {
225 return property_get_bool("ro.input.video_enabled", /*default_value=*/true);
226 }
227
processEventTimestamp(const struct input_event & event)228 static 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
241 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.input_event_sec) +
242 microseconds_to_nanoseconds(event.input_event_usec);
243 return inputEventTime;
244 }
245
246 /**
247 * Returns the sysfs root path of the input device.
248 */
getSysfsRootForEvdevDevicePath(const char * devicePath)249 static std::optional<std::filesystem::path> getSysfsRootForEvdevDevicePath(const char* devicePath) {
250 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));
256 return std::nullopt;
257 }
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());
271 return std::nullopt;
272 }
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
290 return std::nullopt;
291 }
292
293 return sysfsPath;
294 }
295
296 /**
297 * Returns the list of files under a specified path.
298 */
allFilesInPath(const std::filesystem::path & path)299 static 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 */
findSysfsNodes(const std::filesystem::path & sysfsRoot,SysfsClass clazz)316 static std::vector<std::filesystem::path> findSysfsNodes(const std::filesystem::path& sysfsRoot,
317 SysfsClass clazz) {
318 std::string nodeStr = ftl::enum_string(clazz);
319 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
getColorIndexArray(std::filesystem::path path)328 static 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;
349 }
350 }
351 return colors;
352 }
353
loadConfiguration(const InputDeviceIdentifier & ident)354 static base::Result<std::shared_ptr<PropertyMap>> loadConfiguration(
355 const InputDeviceIdentifier& ident) {
356 std::string configurationFile =
357 getInputDeviceConfigurationFilePathByDeviceIdentifier(ident,
358 InputDeviceConfigurationFileType::
359 CONFIGURATION);
360 if (configurationFile.empty()) {
361 ALOGD("No input device configuration file found for device '%s'.", ident.name.c_str());
362 return base::Result<std::shared_ptr<PropertyMap>>(nullptr);
363 }
364 base::Result<std::shared_ptr<PropertyMap>> propertyMap =
365 PropertyMap::load(configurationFile.c_str());
366
367 return propertyMap;
368 }
369
370 /**
371 * Read country code information exposed through the sysfs path and convert it to Layout info.
372 */
readLayoutConfiguration(const std::filesystem::path & sysfsRootPath)373 static std::optional<RawLayoutInfo> readLayoutConfiguration(
374 const std::filesystem::path& sysfsRootPath) {
375 // Check the sysfs root path
376 int32_t hidCountryCode = -1;
377 std::string str;
378 if (base::ReadFileToString(sysfsRootPath / "country", &str)) {
379 hidCountryCode = std::stoi(str, nullptr, 16);
380 // Update this condition if new supported country codes are added to HID spec.
381 if (hidCountryCode > 35 || hidCountryCode < 0) {
382 ALOGE("HID country code should be in range [0, 35], but for sysfs path %s it was %d",
383 sysfsRootPath.c_str(), hidCountryCode);
384 }
385 }
386 const auto it = LAYOUT_INFOS.find(hidCountryCode);
387 if (it != LAYOUT_INFOS.end()) {
388 return it->second;
389 }
390
391 return std::nullopt;
392 }
393
394 /**
395 * Read information about batteries exposed through the sysfs path.
396 */
readBatteryConfiguration(const std::filesystem::path & sysfsRootPath)397 static std::unordered_map<int32_t /*batteryId*/, RawBatteryInfo> readBatteryConfiguration(
398 const std::filesystem::path& sysfsRootPath) {
399 std::unordered_map<int32_t, RawBatteryInfo> batteryInfos;
400 int32_t nextBatteryId = 0;
401 // Check if device has any battery.
402 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::POWER_SUPPLY);
403 for (const auto& nodePath : paths) {
404 RawBatteryInfo info;
405 info.id = ++nextBatteryId;
406 info.path = nodePath;
407 info.name = nodePath.filename();
408
409 // Scan the path for all the files
410 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
411 const auto& files = allFilesInPath(nodePath);
412 for (const auto& file : files) {
413 const auto it = BATTERY_CLASSES.find(file.filename().string());
414 if (it != BATTERY_CLASSES.end()) {
415 info.flags |= it->second;
416 }
417 }
418 batteryInfos.insert_or_assign(info.id, info);
419 ALOGD("configureBatteryLocked rawBatteryId %d name %s", info.id, info.name.c_str());
420 }
421 return batteryInfos;
422 }
423
424 /**
425 * Read information about lights exposed through the sysfs path.
426 */
readLightsConfiguration(const std::filesystem::path & sysfsRootPath,const std::shared_ptr<PropertyMap> & config)427 static std::unordered_map<int32_t /*lightId*/, RawLightInfo> readLightsConfiguration(
428 const std::filesystem::path& sysfsRootPath, const std::shared_ptr<PropertyMap>& config) {
429 std::unordered_map<int32_t, RawLightInfo> lightInfos;
430 int32_t nextLightId = 0;
431 // Check if device has any lights. If the Input Device Configuration file specifies any lights,
432 // use those in addition to searching the device node itself for lights.
433 std::vector<std::filesystem::path> paths = findSysfsNodes(sysfsRootPath, SysfsClass::LEDS);
434
435 if (config) {
436 auto additionalLights = config->getString("device.additionalSysfsLedsNode");
437 if (additionalLights) {
438 ALOGI("IDC specifies additional path for lights at '%s'",
439 additionalLights.value().c_str());
440 paths.push_back(std::filesystem::path(additionalLights.value()));
441 }
442 }
443
444 for (const auto& nodePath : paths) {
445 RawLightInfo info;
446 info.id = ++nextLightId;
447 info.path = nodePath;
448 info.name = nodePath.filename();
449 info.maxBrightness = std::nullopt;
450
451 // Light name should follow the naming pattern <name>:<color>:<function>
452 // Refer kernel docs /leds/leds-class.html for valid supported LED names.
453 std::regex indexPattern("([a-zA-Z0-9_.:]*:)?([a-zA-Z0-9_.]*):([a-zA-Z0-9_.]*)");
454 std::smatch results;
455
456 if (std::regex_match(info.name, results, indexPattern)) {
457 // regex_match will return full match at index 0 and <name> at index 1. For RawLightInfo
458 // we only care about sections <color> and <function> which will be at index 2 and 3.
459 for (int i = 2; i <= 3; i++) {
460 const auto it = LIGHT_CLASSES.find(results.str(i));
461 if (it != LIGHT_CLASSES.end()) {
462 info.flags |= it->second;
463 }
464 }
465
466 // Set name of the raw light to <function> which represents playerIDs for LEDs that
467 // turn on/off based on the current player ID (Refer to PeripheralController.cpp for
468 // player ID logic)
469 info.name = results.str(3);
470 }
471 // Scan the path for all the files
472 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
473 const auto& files = allFilesInPath(nodePath);
474 for (const auto& file : files) {
475 const auto it = LIGHT_CLASSES.find(file.filename().string());
476 if (it != LIGHT_CLASSES.end()) {
477 info.flags |= it->second;
478 // If the node has maximum brightness, read it
479 if (it->second == InputLightClass::MAX_BRIGHTNESS) {
480 std::string str;
481 if (base::ReadFileToString(file, &str)) {
482 info.maxBrightness = std::stoi(str);
483 }
484 }
485 }
486 }
487 lightInfos.insert_or_assign(info.id, info);
488 ALOGD("configureLightsLocked rawLightId %d name %s", info.id, info.name.c_str());
489 }
490 return lightInfos;
491 }
492
493 // --- Global Functions ---
494
getAbsAxisUsage(int32_t axis,ftl::Flags<InputDeviceClass> deviceClasses)495 ftl::Flags<InputDeviceClass> getAbsAxisUsage(int32_t axis,
496 ftl::Flags<InputDeviceClass> deviceClasses) {
497 // Touch devices get dibs on touch-related axes.
498 if (deviceClasses.test(InputDeviceClass::TOUCH)) {
499 switch (axis) {
500 case ABS_X:
501 case ABS_Y:
502 case ABS_PRESSURE:
503 case ABS_TOOL_WIDTH:
504 case ABS_DISTANCE:
505 case ABS_TILT_X:
506 case ABS_TILT_Y:
507 case ABS_MT_SLOT:
508 case ABS_MT_TOUCH_MAJOR:
509 case ABS_MT_TOUCH_MINOR:
510 case ABS_MT_WIDTH_MAJOR:
511 case ABS_MT_WIDTH_MINOR:
512 case ABS_MT_ORIENTATION:
513 case ABS_MT_POSITION_X:
514 case ABS_MT_POSITION_Y:
515 case ABS_MT_TOOL_TYPE:
516 case ABS_MT_BLOB_ID:
517 case ABS_MT_TRACKING_ID:
518 case ABS_MT_PRESSURE:
519 case ABS_MT_DISTANCE:
520 return InputDeviceClass::TOUCH;
521 }
522 }
523
524 if (deviceClasses.test(InputDeviceClass::SENSOR)) {
525 switch (axis) {
526 case ABS_X:
527 case ABS_Y:
528 case ABS_Z:
529 case ABS_RX:
530 case ABS_RY:
531 case ABS_RZ:
532 return InputDeviceClass::SENSOR;
533 }
534 }
535
536 // External stylus gets the pressure axis
537 if (deviceClasses.test(InputDeviceClass::EXTERNAL_STYLUS)) {
538 if (axis == ABS_PRESSURE) {
539 return InputDeviceClass::EXTERNAL_STYLUS;
540 }
541 }
542
543 // Joystick devices get the rest.
544 return deviceClasses & InputDeviceClass::JOYSTICK;
545 }
546
547 // --- RawAbsoluteAxisInfo ---
548
operator <<(std::ostream & out,const std::optional<RawAbsoluteAxisInfo> & info)549 std::ostream& operator<<(std::ostream& out, const std::optional<RawAbsoluteAxisInfo>& info) {
550 if (info) {
551 out << "min=" << info->minValue << ", max=" << info->maxValue << ", flat=" << info->flat
552 << ", fuzz=" << info->fuzz << ", resolution=" << info->resolution;
553 } else {
554 out << "unknown range";
555 }
556 return out;
557 }
558
559 // --- EventHub::Device ---
560
Device(int fd,int32_t id,std::string path,InputDeviceIdentifier identifier,std::shared_ptr<PropertyMap> config)561 EventHub::Device::Device(int fd, int32_t id, std::string path, InputDeviceIdentifier identifier,
562 std::shared_ptr<PropertyMap> config)
563 : fd(fd),
564 id(id),
565 path(std::move(path)),
566 identifier(std::move(identifier)),
567 classes(0),
568 configuration(std::move(config)),
569 virtualKeyMap(nullptr),
570 ffEffectPlaying(false),
571 ffEffectId(-1),
572 controllerNumber(0),
573 enabled(true),
574 isVirtual(fd < 0),
575 currentFrameDropped(false) {}
576
~Device()577 EventHub::Device::~Device() {
578 close();
579 }
580
close()581 void EventHub::Device::close() {
582 if (fd >= 0) {
583 ::close(fd);
584 fd = -1;
585 }
586 }
587
enable()588 status_t EventHub::Device::enable() {
589 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
590 if (fd < 0) {
591 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
592 return -errno;
593 }
594 enabled = true;
595 return OK;
596 }
597
disable()598 status_t EventHub::Device::disable() {
599 close();
600 enabled = false;
601 return OK;
602 }
603
hasValidFd() const604 bool EventHub::Device::hasValidFd() const {
605 return !isVirtual && enabled;
606 }
607
getKeyCharacterMap() const608 const std::shared_ptr<KeyCharacterMap> EventHub::Device::getKeyCharacterMap() const {
609 return keyMap.keyCharacterMap;
610 }
611
612 template <std::size_t N>
readDeviceBitMask(unsigned long ioctlCode,BitArray<N> & bitArray)613 status_t EventHub::Device::readDeviceBitMask(unsigned long ioctlCode, BitArray<N>& bitArray) {
614 if (!hasValidFd()) {
615 return BAD_VALUE;
616 }
617 if ((_IOC_SIZE(ioctlCode) == 0)) {
618 ioctlCode |= _IOC(0, 0, 0, bitArray.bytes());
619 }
620
621 typename BitArray<N>::Buffer buffer;
622 status_t ret = ioctl(fd, ioctlCode, buffer.data());
623 bitArray.loadFromBuffer(buffer);
624 return ret;
625 }
626
configureFd()627 void EventHub::Device::configureFd() {
628 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
629 if (classes.test(InputDeviceClass::KEYBOARD)) {
630 // Disable kernel key repeat since we handle it ourselves
631 unsigned int repeatRate[] = {0, 0};
632 if (ioctl(fd, EVIOCSREP, repeatRate)) {
633 ALOGW("Unable to disable kernel key repeat for %s: %s", path.c_str(), strerror(errno));
634 }
635 }
636
637 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
638 // associated with input events. This is important because the input system
639 // uses the timestamps extensively and assumes they were recorded using the monotonic
640 // clock.
641 int clockId = CLOCK_MONOTONIC;
642 if (classes.test(InputDeviceClass::SENSOR)) {
643 // Each new sensor event should use the same time base as
644 // SystemClock.elapsedRealtimeNanos().
645 clockId = CLOCK_BOOTTIME;
646 }
647 bool usingClockIoctl = !ioctl(fd, EVIOCSCLOCKID, &clockId);
648 ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
649
650 // Query the initial state of keys and switches, which is tracked by EventHub.
651 readDeviceState();
652 }
653
readDeviceState()654 void EventHub::Device::readDeviceState() {
655 if (readDeviceBitMask(EVIOCGKEY(0), keyState) < 0) {
656 ALOGD("Unable to query the global key state for %s: %s", path.c_str(), strerror(errno));
657 }
658 if (readDeviceBitMask(EVIOCGSW(0), swState) < 0) {
659 ALOGD("Unable to query the global switch state for %s: %s", path.c_str(), strerror(errno));
660 }
661
662 // Read absolute axis info and values for all available axes for the device.
663 populateAbsoluteAxisStates();
664 }
665
populateAbsoluteAxisStates()666 void EventHub::Device::populateAbsoluteAxisStates() {
667 absState.clear();
668
669 for (int axis = 0; axis <= ABS_MAX; axis++) {
670 if (!absBitmask.test(axis)) {
671 continue;
672 }
673 struct input_absinfo info {};
674 if (ioctl(fd, EVIOCGABS(axis), &info)) {
675 ALOGE("Error reading absolute controller %d for device %s fd %d: %s", axis,
676 identifier.name.c_str(), fd, strerror(errno));
677 continue;
678 }
679 auto& [axisInfo, value] = absState[axis];
680 axisInfo.minValue = info.minimum;
681 axisInfo.maxValue = info.maximum;
682 axisInfo.flat = info.flat;
683 axisInfo.fuzz = info.fuzz;
684 axisInfo.resolution = info.resolution;
685 value = info.value;
686 }
687 }
688
hasKeycodeLocked(int keycode) const689 bool EventHub::Device::hasKeycodeLocked(int keycode) const {
690 if (hasKeycodeInternalLocked(keycode)) {
691 return true;
692 }
693 if (!keyMap.haveKeyCharacterMap()) {
694 return false;
695 }
696 for (auto& fromKey : getKeyCharacterMap()->findKeyCodesMappedToKeyCode(keycode)) {
697 if (hasKeycodeInternalLocked(fromKey)) {
698 return true;
699 }
700 }
701 return false;
702 }
703
hasKeycodeInternalLocked(int keycode) const704 bool EventHub::Device::hasKeycodeInternalLocked(int keycode) const {
705 if (!keyMap.haveKeyLayout()) {
706 return false;
707 }
708
709 std::vector<int32_t> scanCodes = keyMap.keyLayoutMap->findScanCodesForKey(keycode);
710 const size_t N = scanCodes.size();
711 for (size_t i = 0; i < N && i <= KEY_MAX; i++) {
712 int32_t sc = scanCodes[i];
713 if (sc >= 0 && sc <= KEY_MAX && keyBitmask.test(sc)) {
714 return true;
715 }
716 }
717
718 std::vector<int32_t> usageCodes = keyMap.keyLayoutMap->findUsageCodesForKey(keycode);
719 if (usageCodes.size() > 0 && mscBitmask.test(MSC_SCAN)) {
720 return true;
721 }
722 return false;
723 }
724
loadVirtualKeyMapLocked()725 bool EventHub::Device::loadVirtualKeyMapLocked() {
726 // The virtual key map is supplied by the kernel as a system board property file.
727 std::string propPath = "/sys/board_properties/virtualkeys.";
728 propPath += identifier.getCanonicalName();
729 if (access(propPath.c_str(), R_OK)) {
730 return false;
731 }
732 virtualKeyMap = VirtualKeyMap::load(propPath);
733 return virtualKeyMap != nullptr;
734 }
735
loadKeyMapLocked()736 status_t EventHub::Device::loadKeyMapLocked() {
737 return keyMap.load(identifier, configuration.get());
738 }
739
isExternalDeviceLocked()740 bool EventHub::Device::isExternalDeviceLocked() {
741 if (configuration) {
742 std::optional<bool> isInternal = configuration->getBool("device.internal");
743 if (isInternal.has_value()) {
744 return !isInternal.value();
745 }
746 }
747 return identifier.bus == BUS_USB || identifier.bus == BUS_BLUETOOTH;
748 }
749
deviceHasMicLocked()750 bool EventHub::Device::deviceHasMicLocked() {
751 if (configuration) {
752 std::optional<bool> hasMic = configuration->getBool("audio.mic");
753 if (hasMic.has_value()) {
754 return hasMic.value();
755 }
756 }
757 return false;
758 }
759
setLedStateLocked(int32_t led,bool on)760 void EventHub::Device::setLedStateLocked(int32_t led, bool on) {
761 int32_t sc;
762 if (hasValidFd() && mapLed(led, &sc) != NAME_NOT_FOUND) {
763 struct input_event ev;
764 ev.input_event_sec = 0;
765 ev.input_event_usec = 0;
766 ev.type = EV_LED;
767 ev.code = sc;
768 ev.value = on ? 1 : 0;
769
770 ssize_t nWrite;
771 do {
772 nWrite = write(fd, &ev, sizeof(struct input_event));
773 } while (nWrite == -1 && errno == EINTR);
774 }
775 }
776
setLedForControllerLocked()777 void EventHub::Device::setLedForControllerLocked() {
778 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
779 setLedStateLocked(ALED_CONTROLLER_1 + i, controllerNumber == i + 1);
780 }
781 }
782
mapLed(int32_t led,int32_t * outScanCode) const783 status_t EventHub::Device::mapLed(int32_t led, int32_t* outScanCode) const {
784 if (!keyMap.haveKeyLayout()) {
785 return NAME_NOT_FOUND;
786 }
787
788 std::optional<int32_t> scanCode = keyMap.keyLayoutMap->findScanCodeForLed(led);
789 if (scanCode.has_value()) {
790 if (*scanCode >= 0 && *scanCode <= LED_MAX && ledBitmask.test(*scanCode)) {
791 *outScanCode = *scanCode;
792 return NO_ERROR;
793 }
794 }
795 return NAME_NOT_FOUND;
796 }
797
trackInputEvent(const struct input_event & event)798 void EventHub::Device::trackInputEvent(const struct input_event& event) {
799 switch (event.type) {
800 case EV_KEY: {
801 LOG_ALWAYS_FATAL_IF(!currentFrameDropped &&
802 !keyState.set(static_cast<size_t>(event.code),
803 event.value != 0),
804 "%s: device '%s' received invalid EV_KEY event code: %s value: %d",
805 __func__, identifier.name.c_str(),
806 InputEventLookup::getLinuxEvdevLabel(EV_KEY, event.code, 1)
807 .code.c_str(),
808 event.value);
809 break;
810 }
811 case EV_SW: {
812 LOG_ALWAYS_FATAL_IF(!currentFrameDropped &&
813 !swState.set(static_cast<size_t>(event.code),
814 event.value != 0),
815 "%s: device '%s' received invalid EV_SW event code: %s value: %d",
816 __func__, identifier.name.c_str(),
817 InputEventLookup::getLinuxEvdevLabel(EV_SW, event.code, 1)
818 .code.c_str(),
819 event.value);
820 break;
821 }
822 case EV_ABS: {
823 if (currentFrameDropped) {
824 break;
825 }
826 auto it = absState.find(event.code);
827 LOG_ALWAYS_FATAL_IF(it == absState.end(),
828 "%s: device '%s' received invalid EV_ABS event code: %s value: %d",
829 __func__, identifier.name.c_str(),
830 InputEventLookup::getLinuxEvdevLabel(EV_ABS, event.code, 0)
831 .code.c_str(),
832 event.value);
833 it->second.value = event.value;
834 break;
835 }
836 case EV_SYN: {
837 switch (event.code) {
838 case SYN_REPORT:
839 if (currentFrameDropped) {
840 // To recover after a SYN_DROPPED, we need to query the state of the device
841 // to synchronize our device state with the kernel's to account for the
842 // dropped events on receiving the next SYN_REPORT.
843 // Note we don't drop the SYN_REPORT at this point but it is used by the
844 // InputDevice to reset and repopulate mapper state
845 readDeviceState();
846 currentFrameDropped = false;
847 }
848 break;
849 case SYN_DROPPED:
850 // When we receive SYN_DROPPED, all events in the current frame should be
851 // dropped up to and including next SYN_REPORT
852 currentFrameDropped = true;
853 break;
854 default:
855 break;
856 }
857 break;
858 }
859 default:
860 break;
861 }
862 }
863
864 /**
865 * Get the capabilities for the current process.
866 * Crashes the system if unable to create / check / destroy the capabilities object.
867 */
868 class Capabilities final {
869 public:
Capabilities()870 explicit Capabilities() {
871 mCaps = cap_get_proc();
872 LOG_ALWAYS_FATAL_IF(mCaps == nullptr, "Could not get capabilities of the current process");
873 }
874
875 /**
876 * Check whether the current process has a specific capability
877 * in the set of effective capabilities.
878 * Return CAP_SET if the process has the requested capability
879 * Return CAP_CLEAR otherwise.
880 */
checkEffectiveCapability(cap_value_t capability)881 cap_flag_value_t checkEffectiveCapability(cap_value_t capability) {
882 cap_flag_value_t value;
883 const int result = cap_get_flag(mCaps, capability, CAP_EFFECTIVE, &value);
884 LOG_ALWAYS_FATAL_IF(result == -1, "Could not obtain the requested capability");
885 return value;
886 }
887
~Capabilities()888 ~Capabilities() {
889 const int result = cap_free(mCaps);
890 LOG_ALWAYS_FATAL_IF(result == -1, "Could not release the capabilities structure");
891 }
892
893 private:
894 cap_t mCaps;
895 };
896
ensureProcessCanBlockSuspend()897 static void ensureProcessCanBlockSuspend() {
898 Capabilities capabilities;
899 const bool canBlockSuspend =
900 capabilities.checkEffectiveCapability(CAP_BLOCK_SUSPEND) == CAP_SET;
901 LOG_ALWAYS_FATAL_IF(!canBlockSuspend,
902 "Input must be able to block suspend to properly process events");
903 }
904
905 // --- EventHub ---
906
907 const int EventHub::EPOLL_MAX_EVENTS;
908
EventHub(void)909 EventHub::EventHub(void)
910 : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
911 mNextDeviceId(1),
912 mControllerNumbers(),
913 mNeedToReopenDevices(false),
914 mNeedToScanDevices(true),
915 mPendingEventCount(0),
916 mPendingEventIndex(0),
917 mPendingINotify(false) {
918 ensureProcessCanBlockSuspend();
919
920 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
921 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
922
923 mINotifyFd = inotify_init1(IN_CLOEXEC);
924 LOG_ALWAYS_FATAL_IF(mINotifyFd < 0, "Could not create inotify instance: %s", strerror(errno));
925
926 std::error_code errorCode;
927 bool isDeviceInotifyAdded = false;
928 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
929 addDeviceInputInotify();
930 } else {
931 addDeviceInotify();
932 isDeviceInotifyAdded = true;
933 if (errorCode) {
934 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
935 errorCode.message().c_str());
936 }
937 }
938
939 if (isV4lScanningEnabled() && !isDeviceInotifyAdded) {
940 addDeviceInotify();
941 } else {
942 ALOGI("Video device scanning disabled");
943 }
944
945 struct epoll_event eventItem = {};
946 eventItem.events = EPOLLIN | EPOLLWAKEUP;
947 eventItem.data.fd = mINotifyFd;
948 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
949 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
950
951 int wakeFds[2];
952 result = pipe2(wakeFds, O_CLOEXEC);
953 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
954
955 mWakeReadPipeFd = wakeFds[0];
956 mWakeWritePipeFd = wakeFds[1];
957
958 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
959 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
960 errno);
961
962 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
963 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
964 errno);
965
966 eventItem.data.fd = mWakeReadPipeFd;
967 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
968 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
969 errno);
970 }
971
~EventHub(void)972 EventHub::~EventHub(void) {
973 closeAllDevicesLocked();
974
975 ::close(mEpollFd);
976 ::close(mINotifyFd);
977 ::close(mWakeReadPipeFd);
978 ::close(mWakeWritePipeFd);
979 }
980
981 /**
982 * On devices that don't have any input devices (like some development boards), the /dev/input
983 * directory will be absent. However, the user may still plug in an input device at a later time.
984 * Add watch for contents of /dev/input only when /dev/input appears.
985 */
addDeviceInputInotify()986 void EventHub::addDeviceInputInotify() {
987 mDeviceInputWd = inotify_add_watch(mINotifyFd, DEVICE_INPUT_PATH, IN_DELETE | IN_CREATE);
988 LOG_ALWAYS_FATAL_IF(mDeviceInputWd < 0, "Could not register INotify for %s: %s",
989 DEVICE_INPUT_PATH, strerror(errno));
990 }
991
addDeviceInotify()992 void EventHub::addDeviceInotify() {
993 mDeviceWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
994 LOG_ALWAYS_FATAL_IF(mDeviceWd < 0, "Could not register INotify for %s: %s", DEVICE_PATH,
995 strerror(errno));
996 }
997
getDeviceIdentifier(int32_t deviceId) const998 InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
999 std::scoped_lock _l(mLock);
1000 Device* device = getDeviceLocked(deviceId);
1001 return device != nullptr ? device->identifier : InputDeviceIdentifier();
1002 }
1003
getDeviceClasses(int32_t deviceId) const1004 ftl::Flags<InputDeviceClass> EventHub::getDeviceClasses(int32_t deviceId) const {
1005 std::scoped_lock _l(mLock);
1006 Device* device = getDeviceLocked(deviceId);
1007 return device != nullptr ? device->classes : ftl::Flags<InputDeviceClass>(0);
1008 }
1009
getDeviceControllerNumber(int32_t deviceId) const1010 int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
1011 std::scoped_lock _l(mLock);
1012 Device* device = getDeviceLocked(deviceId);
1013 return device != nullptr ? device->controllerNumber : 0;
1014 }
1015
getConfiguration(int32_t deviceId) const1016 std::optional<PropertyMap> EventHub::getConfiguration(int32_t deviceId) const {
1017 std::scoped_lock _l(mLock);
1018 Device* device = getDeviceLocked(deviceId);
1019 if (device == nullptr || device->configuration == nullptr) {
1020 return {};
1021 }
1022 return *device->configuration;
1023 }
1024
getAbsoluteAxisInfo(int32_t deviceId,int axis) const1025 std::optional<RawAbsoluteAxisInfo> EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis) const {
1026 if (axis < 0 || axis > ABS_MAX) {
1027 return std::nullopt;
1028 }
1029 std::scoped_lock _l(mLock);
1030 const Device* device = getDeviceLocked(deviceId);
1031 if (device == nullptr) {
1032 ALOGE("Couldn't find device with ID %d, so returning null axis info for axis %s", deviceId,
1033 InputEventLookup::getLinuxEvdevLabel(EV_ABS, axis, 0).code.c_str());
1034 return std::nullopt;
1035 }
1036 // We can read the RawAbsoluteAxisInfo even if the device is disabled and doesn't have a valid
1037 // fd, because the info is populated once when the device is first opened, and it doesn't change
1038 // throughout the device lifecycle.
1039 auto it = device->absState.find(axis);
1040 if (it == device->absState.end()) {
1041 return std::nullopt;
1042 }
1043 return it->second.info;
1044 }
1045
hasRelativeAxis(int32_t deviceId,int axis) const1046 bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
1047 if (axis >= 0 && axis <= REL_MAX) {
1048 std::scoped_lock _l(mLock);
1049 Device* device = getDeviceLocked(deviceId);
1050 return device != nullptr ? device->relBitmask.test(axis) : false;
1051 }
1052 return false;
1053 }
1054
hasInputProperty(int32_t deviceId,int property) const1055 bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
1056 std::scoped_lock _l(mLock);
1057
1058 Device* device = getDeviceLocked(deviceId);
1059 return property >= 0 && property <= INPUT_PROP_MAX && device != nullptr
1060 ? device->propBitmask.test(property)
1061 : false;
1062 }
1063
hasMscEvent(int32_t deviceId,int mscEvent) const1064 bool EventHub::hasMscEvent(int32_t deviceId, int mscEvent) const {
1065 std::scoped_lock _l(mLock);
1066
1067 Device* device = getDeviceLocked(deviceId);
1068 return mscEvent >= 0 && mscEvent <= MSC_MAX && device != nullptr
1069 ? device->mscBitmask.test(mscEvent)
1070 : false;
1071 }
1072
getScanCodeState(int32_t deviceId,int32_t scanCode) const1073 int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
1074 if (scanCode < 0 || scanCode > KEY_MAX) {
1075 return AKEY_STATE_UNKNOWN;
1076 }
1077 std::scoped_lock _l(mLock);
1078 const Device* device = getDeviceLocked(deviceId);
1079 if (device == nullptr || !device->hasValidFd() || !device->keyBitmask.test(scanCode)) {
1080 return AKEY_STATE_UNKNOWN;
1081 }
1082 return device->keyState.test(scanCode) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
1083 }
1084
getKeyCodeState(int32_t deviceId,int32_t keyCode) const1085 int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
1086 std::scoped_lock _l(mLock);
1087 const Device* device = getDeviceLocked(deviceId);
1088 if (device == nullptr || !device->hasValidFd() || !device->keyMap.haveKeyLayout()) {
1089 return AKEY_STATE_UNKNOWN;
1090 }
1091 const std::vector<int32_t> scanCodes =
1092 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode);
1093 if (scanCodes.empty()) {
1094 return AKEY_STATE_UNKNOWN;
1095 }
1096 return std::any_of(scanCodes.begin(), scanCodes.end(),
1097 [&device](const int32_t sc) {
1098 return sc >= 0 && sc <= KEY_MAX && device->keyState.test(sc);
1099 })
1100 ? AKEY_STATE_DOWN
1101 : AKEY_STATE_UP;
1102 }
1103
getKeyCodeForKeyLocation(int32_t deviceId,int32_t locationKeyCode) const1104 int32_t EventHub::getKeyCodeForKeyLocation(int32_t deviceId, int32_t locationKeyCode) const {
1105 std::scoped_lock _l(mLock);
1106
1107 Device* device = getDeviceLocked(deviceId);
1108 if (device == nullptr || !device->hasValidFd() || device->keyMap.keyCharacterMap == nullptr ||
1109 device->keyMap.keyLayoutMap == nullptr) {
1110 return AKEYCODE_UNKNOWN;
1111 }
1112 std::vector<int32_t> scanCodes =
1113 device->keyMap.keyLayoutMap->findScanCodesForKey(locationKeyCode);
1114 if (scanCodes.empty()) {
1115 ALOGW("Failed to get key code for key location: no scan code maps to key code %d for input"
1116 "device %d",
1117 locationKeyCode, deviceId);
1118 return AKEYCODE_UNKNOWN;
1119 }
1120 if (scanCodes.size() > 1) {
1121 ALOGW("Multiple scan codes map to the same key code %d, returning only the first match",
1122 locationKeyCode);
1123 }
1124 int32_t outKeyCode;
1125 status_t mapKeyRes =
1126 device->getKeyCharacterMap()->mapKey(scanCodes[0], /*usageCode=*/0, &outKeyCode);
1127 switch (mapKeyRes) {
1128 case OK:
1129 break;
1130 case NAME_NOT_FOUND:
1131 // key character map doesn't re-map this scanCode, hence the keyCode remains the same
1132 outKeyCode = locationKeyCode;
1133 break;
1134 default:
1135 ALOGW("Failed to get key code for key location: Key character map returned error %s",
1136 statusToString(mapKeyRes).c_str());
1137 outKeyCode = AKEYCODE_UNKNOWN;
1138 break;
1139 }
1140 // Remap if there is a Key remapping added to the KCM and return the remapped key
1141 return device->getKeyCharacterMap()->applyKeyRemapping(outKeyCode);
1142 }
1143
getSwitchState(int32_t deviceId,int32_t sw) const1144 int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
1145 if (sw < 0 || sw > SW_MAX) {
1146 return AKEY_STATE_UNKNOWN;
1147 }
1148 std::scoped_lock _l(mLock);
1149 const Device* device = getDeviceLocked(deviceId);
1150 if (device == nullptr || !device->hasValidFd() || !device->swBitmask.test(sw)) {
1151 return AKEY_STATE_UNKNOWN;
1152 }
1153 return device->swState.test(sw) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
1154 }
1155
getAbsoluteAxisValue(int32_t deviceId,int32_t axis) const1156 std::optional<int32_t> EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis) const {
1157 if (axis < 0 || axis > ABS_MAX) {
1158 return std::nullopt;
1159 }
1160 std::scoped_lock _l(mLock);
1161 const Device* device = getDeviceLocked(deviceId);
1162 if (device == nullptr || !device->hasValidFd()) {
1163 return std::nullopt;
1164 }
1165 const auto it = device->absState.find(axis);
1166 if (it == device->absState.end()) {
1167 return std::nullopt;
1168 }
1169 return it->second.value;
1170 }
1171
getMtSlotValues(int32_t deviceId,int32_t axis,size_t slotCount) const1172 base::Result<std::vector<int32_t>> EventHub::getMtSlotValues(int32_t deviceId, int32_t axis,
1173 size_t slotCount) const {
1174 std::scoped_lock _l(mLock);
1175 const Device* device = getDeviceLocked(deviceId);
1176 if (device == nullptr || !device->hasValidFd() || !device->absBitmask.test(axis)) {
1177 return base::ResultError("device problem or axis not supported", NAME_NOT_FOUND);
1178 }
1179 std::vector<int32_t> outValues(slotCount + 1);
1180 outValues[0] = axis;
1181 const size_t bufferSize = outValues.size() * sizeof(int32_t);
1182 if (ioctl(device->fd, EVIOCGMTSLOTS(bufferSize), outValues.data()) != OK) {
1183 return base::ErrnoError();
1184 }
1185 return std::move(outValues);
1186 }
1187
markSupportedKeyCodes(int32_t deviceId,const std::vector<int32_t> & keyCodes,uint8_t * outFlags) const1188 bool EventHub::markSupportedKeyCodes(int32_t deviceId, const std::vector<int32_t>& keyCodes,
1189 uint8_t* outFlags) const {
1190 std::scoped_lock _l(mLock);
1191
1192 Device* device = getDeviceLocked(deviceId);
1193 if (device != nullptr && device->keyMap.haveKeyLayout()) {
1194 for (size_t codeIndex = 0; codeIndex < keyCodes.size(); codeIndex++) {
1195 if (device->hasKeycodeLocked(keyCodes[codeIndex])) {
1196 outFlags[codeIndex] = 1;
1197 }
1198 }
1199 return true;
1200 }
1201 return false;
1202 }
1203
setKeyRemapping(int32_t deviceId,const std::map<int32_t,int32_t> & keyRemapping) const1204 void EventHub::setKeyRemapping(int32_t deviceId,
1205 const std::map<int32_t, int32_t>& keyRemapping) const {
1206 std::scoped_lock _l(mLock);
1207 Device* device = getDeviceLocked(deviceId);
1208 if (device == nullptr) {
1209 return;
1210 }
1211 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
1212 if (kcm) {
1213 kcm->setKeyRemapping(keyRemapping);
1214 }
1215 }
1216
mapKey(int32_t deviceId,int32_t scanCode,int32_t usageCode,int32_t metaState,int32_t * outKeycode,int32_t * outMetaState,uint32_t * outFlags) const1217 status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
1218 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
1219 std::scoped_lock _l(mLock);
1220 Device* device = getDeviceLocked(deviceId);
1221 status_t status = NAME_NOT_FOUND;
1222
1223 if (device != nullptr) {
1224 // Check the key character map first.
1225 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
1226 if (kcm) {
1227 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
1228 *outFlags = 0;
1229 status = NO_ERROR;
1230 }
1231 }
1232
1233 // Check the key layout next.
1234 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
1235 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
1236 status = NO_ERROR;
1237 }
1238 }
1239
1240 if (status == NO_ERROR) {
1241 if (kcm) {
1242 // Remap keys based on user-defined key remappings and key behavior defined in the
1243 // corresponding kcm file
1244 *outKeycode = kcm->applyKeyRemapping(*outKeycode);
1245
1246 // Remap keys based on Key behavior defined in KCM file
1247 std::tie(*outKeycode, *outMetaState) =
1248 kcm->applyKeyBehavior(*outKeycode, metaState);
1249 } else {
1250 *outMetaState = metaState;
1251 }
1252 }
1253 }
1254
1255 if (status != NO_ERROR) {
1256 *outKeycode = 0;
1257 *outFlags = 0;
1258 *outMetaState = metaState;
1259 }
1260
1261 return status;
1262 }
1263
mapAxis(int32_t deviceId,int32_t scanCode,AxisInfo * outAxisInfo) const1264 status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
1265 std::scoped_lock _l(mLock);
1266 Device* device = getDeviceLocked(deviceId);
1267
1268 if (device == nullptr || !device->keyMap.haveKeyLayout()) {
1269 return NAME_NOT_FOUND;
1270 }
1271 std::optional<AxisInfo> info = device->keyMap.keyLayoutMap->mapAxis(scanCode);
1272 if (!info.has_value()) {
1273 return NAME_NOT_FOUND;
1274 }
1275 *outAxisInfo = *info;
1276 return NO_ERROR;
1277 }
1278
mapSensor(int32_t deviceId,int32_t absCode) const1279 base::Result<std::pair<InputDeviceSensorType, int32_t>> EventHub::mapSensor(int32_t deviceId,
1280 int32_t absCode) const {
1281 std::scoped_lock _l(mLock);
1282 Device* device = getDeviceLocked(deviceId);
1283
1284 if (device != nullptr && device->keyMap.haveKeyLayout()) {
1285 return device->keyMap.keyLayoutMap->mapSensor(absCode);
1286 }
1287 return Errorf("Device not found or device has no key layout.");
1288 }
1289
1290 // Gets the battery info map from battery ID to RawBatteryInfo of the miscellaneous device
1291 // associated with the device ID. Returns an empty map if no miscellaneous device found.
getBatteryInfoLocked(int32_t deviceId) const1292 const std::unordered_map<int32_t, RawBatteryInfo>& EventHub::getBatteryInfoLocked(
1293 int32_t deviceId) const {
1294 static const std::unordered_map<int32_t, RawBatteryInfo> EMPTY_BATTERY_INFO = {};
1295 Device* device = getDeviceLocked(deviceId);
1296 if (device == nullptr || !device->associatedDevice) {
1297 return EMPTY_BATTERY_INFO;
1298 }
1299 return device->associatedDevice->batteryInfos;
1300 }
1301
getRawBatteryIds(int32_t deviceId) const1302 std::vector<int32_t> EventHub::getRawBatteryIds(int32_t deviceId) const {
1303 std::scoped_lock _l(mLock);
1304 std::vector<int32_t> batteryIds;
1305
1306 for (const auto& [id, info] : getBatteryInfoLocked(deviceId)) {
1307 batteryIds.push_back(id);
1308 }
1309
1310 return batteryIds;
1311 }
1312
getRawBatteryInfo(int32_t deviceId,int32_t batteryId) const1313 std::optional<RawBatteryInfo> EventHub::getRawBatteryInfo(int32_t deviceId,
1314 int32_t batteryId) const {
1315 std::scoped_lock _l(mLock);
1316
1317 const auto infos = getBatteryInfoLocked(deviceId);
1318
1319 auto it = infos.find(batteryId);
1320 if (it != infos.end()) {
1321 return it->second;
1322 }
1323
1324 return std::nullopt;
1325 }
1326
1327 // Gets the light info map from light ID to RawLightInfo of the miscellaneous device associated
1328 // with the device ID. Returns an empty map if no miscellaneous device found.
getLightInfoLocked(int32_t deviceId) const1329 const std::unordered_map<int32_t, RawLightInfo>& EventHub::getLightInfoLocked(
1330 int32_t deviceId) const {
1331 static const std::unordered_map<int32_t, RawLightInfo> EMPTY_LIGHT_INFO = {};
1332 Device* device = getDeviceLocked(deviceId);
1333 if (device == nullptr || !device->associatedDevice) {
1334 return EMPTY_LIGHT_INFO;
1335 }
1336 return device->associatedDevice->lightInfos;
1337 }
1338
getRawLightIds(int32_t deviceId) const1339 std::vector<int32_t> EventHub::getRawLightIds(int32_t deviceId) const {
1340 std::scoped_lock _l(mLock);
1341 std::vector<int32_t> lightIds;
1342
1343 for (const auto& [id, info] : getLightInfoLocked(deviceId)) {
1344 lightIds.push_back(id);
1345 }
1346
1347 return lightIds;
1348 }
1349
getRawLightInfo(int32_t deviceId,int32_t lightId) const1350 std::optional<RawLightInfo> EventHub::getRawLightInfo(int32_t deviceId, int32_t lightId) const {
1351 std::scoped_lock _l(mLock);
1352
1353 const auto infos = getLightInfoLocked(deviceId);
1354
1355 auto it = infos.find(lightId);
1356 if (it != infos.end()) {
1357 return it->second;
1358 }
1359
1360 return std::nullopt;
1361 }
1362
getLightBrightness(int32_t deviceId,int32_t lightId) const1363 std::optional<int32_t> EventHub::getLightBrightness(int32_t deviceId, int32_t lightId) const {
1364 std::scoped_lock _l(mLock);
1365
1366 const auto infos = getLightInfoLocked(deviceId);
1367 auto it = infos.find(lightId);
1368 if (it == infos.end()) {
1369 return std::nullopt;
1370 }
1371 std::string buffer;
1372 if (!base::ReadFileToString(it->second.path / LIGHT_NODES.at(InputLightClass::BRIGHTNESS),
1373 &buffer)) {
1374 return std::nullopt;
1375 }
1376 return std::stoi(buffer);
1377 }
1378
getLightIntensities(int32_t deviceId,int32_t lightId) const1379 std::optional<std::unordered_map<LightColor, int32_t>> EventHub::getLightIntensities(
1380 int32_t deviceId, int32_t lightId) const {
1381 std::scoped_lock _l(mLock);
1382
1383 const auto infos = getLightInfoLocked(deviceId);
1384 auto lightIt = infos.find(lightId);
1385 if (lightIt == infos.end()) {
1386 return std::nullopt;
1387 }
1388
1389 auto ret =
1390 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1391
1392 if (!ret.has_value()) {
1393 return std::nullopt;
1394 }
1395 std::array<LightColor, COLOR_NUM> colors = ret.value();
1396
1397 std::string intensityStr;
1398 if (!base::ReadFileToString(lightIt->second.path /
1399 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY),
1400 &intensityStr)) {
1401 return std::nullopt;
1402 }
1403
1404 // Intensity node outputs 3 color values
1405 std::regex intensityPattern("([0-9]+)\\s([0-9]+)\\s([0-9]+)[\\n]");
1406 std::smatch results;
1407
1408 if (!std::regex_match(intensityStr, results, intensityPattern)) {
1409 return std::nullopt;
1410 }
1411 std::unordered_map<LightColor, int32_t> intensities;
1412 for (size_t i = 1; i < results.size(); i++) {
1413 int value = std::stoi(results[i].str());
1414 intensities.emplace(colors[i - 1], value);
1415 }
1416 return intensities;
1417 }
1418
setLightBrightness(int32_t deviceId,int32_t lightId,int32_t brightness)1419 void EventHub::setLightBrightness(int32_t deviceId, int32_t lightId, int32_t brightness) {
1420 std::scoped_lock _l(mLock);
1421
1422 const auto infos = getLightInfoLocked(deviceId);
1423 auto lightIt = infos.find(lightId);
1424 if (lightIt == infos.end()) {
1425 ALOGE("%s lightId %d not found ", __func__, lightId);
1426 return;
1427 }
1428
1429 if (!base::WriteStringToFile(std::to_string(brightness),
1430 lightIt->second.path /
1431 LIGHT_NODES.at(InputLightClass::BRIGHTNESS))) {
1432 ALOGE("Can not write to file, error: %s", strerror(errno));
1433 }
1434 }
1435
setLightIntensities(int32_t deviceId,int32_t lightId,std::unordered_map<LightColor,int32_t> intensities)1436 void EventHub::setLightIntensities(int32_t deviceId, int32_t lightId,
1437 std::unordered_map<LightColor, int32_t> intensities) {
1438 std::scoped_lock _l(mLock);
1439
1440 const auto infos = getLightInfoLocked(deviceId);
1441 auto lightIt = infos.find(lightId);
1442 if (lightIt == infos.end()) {
1443 ALOGE("Light Id %d does not exist.", lightId);
1444 return;
1445 }
1446
1447 auto ret =
1448 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1449
1450 if (!ret.has_value()) {
1451 return;
1452 }
1453 std::array<LightColor, COLOR_NUM> colors = ret.value();
1454
1455 std::string rgbStr;
1456 for (size_t i = 0; i < COLOR_NUM; i++) {
1457 auto it = intensities.find(colors[i]);
1458 if (it != intensities.end()) {
1459 rgbStr += std::to_string(it->second);
1460 // Insert space between colors
1461 if (i < COLOR_NUM - 1) {
1462 rgbStr += " ";
1463 }
1464 }
1465 }
1466 // Append new line
1467 rgbStr += "\n";
1468
1469 if (!base::WriteStringToFile(rgbStr,
1470 lightIt->second.path /
1471 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY))) {
1472 ALOGE("Can not write to file, error: %s", strerror(errno));
1473 }
1474 }
1475
getRawLayoutInfo(int32_t deviceId) const1476 std::optional<RawLayoutInfo> EventHub::getRawLayoutInfo(int32_t deviceId) const {
1477 std::scoped_lock _l(mLock);
1478 Device* device = getDeviceLocked(deviceId);
1479 if (device == nullptr || !device->associatedDevice) {
1480 return std::nullopt;
1481 }
1482 return device->associatedDevice->layoutInfo;
1483 }
1484
setExcludedDevices(const std::vector<std::string> & devices)1485 void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
1486 std::scoped_lock _l(mLock);
1487
1488 mExcludedDevices = devices;
1489 }
1490
hasScanCode(int32_t deviceId,int32_t scanCode) const1491 bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
1492 std::scoped_lock _l(mLock);
1493 Device* device = getDeviceLocked(deviceId);
1494 if (device != nullptr && scanCode >= 0 && scanCode <= KEY_MAX) {
1495 return device->keyBitmask.test(scanCode);
1496 }
1497 return false;
1498 }
1499
hasKeyCode(int32_t deviceId,int32_t keyCode) const1500 bool EventHub::hasKeyCode(int32_t deviceId, int32_t keyCode) const {
1501 std::scoped_lock _l(mLock);
1502 Device* device = getDeviceLocked(deviceId);
1503 if (device != nullptr) {
1504 return device->hasKeycodeLocked(keyCode);
1505 }
1506 return false;
1507 }
1508
hasLed(int32_t deviceId,int32_t led) const1509 bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
1510 std::scoped_lock _l(mLock);
1511 Device* device = getDeviceLocked(deviceId);
1512 int32_t sc;
1513 if (device != nullptr && device->mapLed(led, &sc) == NO_ERROR) {
1514 return device->ledBitmask.test(sc);
1515 }
1516 return false;
1517 }
1518
setLedState(int32_t deviceId,int32_t led,bool on)1519 void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
1520 std::scoped_lock _l(mLock);
1521 Device* device = getDeviceLocked(deviceId);
1522 if (device != nullptr && device->hasValidFd()) {
1523 device->setLedStateLocked(led, on);
1524 }
1525 }
1526
getVirtualKeyDefinitions(int32_t deviceId,std::vector<VirtualKeyDefinition> & outVirtualKeys) const1527 void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
1528 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
1529 outVirtualKeys.clear();
1530
1531 std::scoped_lock _l(mLock);
1532 Device* device = getDeviceLocked(deviceId);
1533 if (device != nullptr && device->virtualKeyMap) {
1534 const std::vector<VirtualKeyDefinition> virtualKeys =
1535 device->virtualKeyMap->getVirtualKeys();
1536 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
1537 }
1538 }
1539
getKeyCharacterMap(int32_t deviceId) const1540 const std::shared_ptr<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
1541 std::scoped_lock _l(mLock);
1542 Device* device = getDeviceLocked(deviceId);
1543 if (device != nullptr) {
1544 return device->getKeyCharacterMap();
1545 }
1546 return nullptr;
1547 }
1548
1549 // If provided map is null, it will reset key character map to default KCM.
setKeyboardLayoutOverlay(int32_t deviceId,std::shared_ptr<KeyCharacterMap> map)1550 bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, std::shared_ptr<KeyCharacterMap> map) {
1551 std::scoped_lock _l(mLock);
1552 Device* device = getDeviceLocked(deviceId);
1553 if (device == nullptr || device->keyMap.keyCharacterMap == nullptr) {
1554 return false;
1555 }
1556 if (map == nullptr) {
1557 device->keyMap.keyCharacterMap->clearLayoutOverlay();
1558 return true;
1559 }
1560 device->keyMap.keyCharacterMap->combine(*map);
1561 return true;
1562 }
1563
generateDescriptor(InputDeviceIdentifier & identifier)1564 static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
1565 std::string rawDescriptor;
1566 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
1567 // TODO add handling for USB devices to not uniqueify kbs that show up twice
1568 if (!identifier.uniqueId.empty()) {
1569 rawDescriptor += "uniqueId:";
1570 rawDescriptor += identifier.uniqueId;
1571 }
1572 if (identifier.nonce != 0) {
1573 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
1574 }
1575
1576 if (identifier.vendor == 0 && identifier.product == 0) {
1577 // If we don't know the vendor and product id, then the device is probably
1578 // built-in so we need to rely on other information to uniquely identify
1579 // the input device. Usually we try to avoid relying on the device name or
1580 // location but for built-in input device, they are unlikely to ever change.
1581 if (!identifier.name.empty()) {
1582 rawDescriptor += "name:";
1583 rawDescriptor += identifier.name;
1584 } else if (!identifier.location.empty()) {
1585 rawDescriptor += "location:";
1586 rawDescriptor += identifier.location;
1587 }
1588 }
1589 identifier.descriptor = sha1(rawDescriptor);
1590 return rawDescriptor;
1591 }
1592
assignDescriptorLocked(InputDeviceIdentifier & identifier)1593 void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
1594 // Compute a device descriptor that uniquely identifies the device.
1595 // The descriptor is assumed to be a stable identifier. Its value should not
1596 // change between reboots, reconnections, firmware updates or new releases
1597 // of Android. In practice we sometimes get devices that cannot be uniquely
1598 // identified. In this case we enforce uniqueness between connected devices.
1599 // Ideally, we also want the descriptor to be short and relatively opaque.
1600 // Note that we explicitly do not use the path or location for external devices
1601 // as their path or location will change as they are plugged/unplugged or moved
1602 // to different ports. We do fallback to using name and location in the case of
1603 // internal devices which are detected by the vendor and product being 0 in
1604 // generateDescriptor. If two identical descriptors are detected we will fallback
1605 // to using a 'nonce' and incrementing it until the new descriptor no longer has
1606 // a match with any existing descriptors.
1607
1608 identifier.nonce = 0;
1609 std::string rawDescriptor = generateDescriptor(identifier);
1610 // Enforce that the generated descriptor is unique.
1611 while (hasDeviceWithDescriptorLocked(identifier.descriptor)) {
1612 identifier.nonce++;
1613 rawDescriptor = generateDescriptor(identifier);
1614 }
1615 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
1616 identifier.descriptor.c_str());
1617 }
1618
obtainAssociatedDeviceLocked(const std::filesystem::path & devicePath,const std::shared_ptr<PropertyMap> & config) const1619 std::shared_ptr<const EventHub::AssociatedDevice> EventHub::obtainAssociatedDeviceLocked(
1620 const std::filesystem::path& devicePath, const std::shared_ptr<PropertyMap>& config) const {
1621 const std::optional<std::filesystem::path> sysfsRootPathOpt =
1622 getSysfsRootForEvdevDevicePath(devicePath.c_str());
1623 if (!sysfsRootPathOpt) {
1624 return nullptr;
1625 }
1626
1627 const auto& path = *sysfsRootPathOpt;
1628
1629 std::shared_ptr<const AssociatedDevice> associatedDevice;
1630 for (const auto& [id, dev] : mDevices) {
1631 if (!dev->associatedDevice || dev->associatedDevice->sysfsRootPath != path) {
1632 continue;
1633 }
1634 if (!associatedDevice) {
1635 // Found matching associated device for the first time.
1636 associatedDevice = dev->associatedDevice;
1637 // Reload this associated device if needed. Use the base device
1638 // config. Note that this will essentially arbitrarily pick one
1639 // Device as the base for the AssociatedDevice configuration. If
1640 // there are multiple Device's that have a configuration for the
1641 // AssociatedDevice, only one configuration will be chosen and will
1642 // be used for all other AssociatedDevices for the same sysfs path.
1643 const auto reloadedDevice = AssociatedDevice(path, associatedDevice->baseDevConfig);
1644 if (reloadedDevice != *dev->associatedDevice) {
1645 ALOGI("The AssociatedDevice changed for path '%s'. Using new AssociatedDevice: %s",
1646 path.c_str(), associatedDevice->dump().c_str());
1647 associatedDevice = std::make_shared<AssociatedDevice>(std::move(reloadedDevice));
1648 }
1649 }
1650 // Update the associatedDevice.
1651 dev->associatedDevice = associatedDevice;
1652 }
1653
1654 if (!associatedDevice) {
1655 // No existing associated device found for this path, so create a new one.
1656 associatedDevice = std::make_shared<AssociatedDevice>(path, config);
1657 }
1658
1659 return associatedDevice;
1660 }
1661
AssociatedDevice(const std::filesystem::path & sysfsRootPath,std::shared_ptr<PropertyMap> config)1662 EventHub::AssociatedDevice::AssociatedDevice(const std::filesystem::path& sysfsRootPath,
1663 std::shared_ptr<PropertyMap> config)
1664 : sysfsRootPath(sysfsRootPath),
1665 baseDevConfig(std::move(config)),
1666 batteryInfos(readBatteryConfiguration(sysfsRootPath)),
1667 lightInfos(readLightsConfiguration(sysfsRootPath, baseDevConfig)),
1668 layoutInfo(readLayoutConfiguration(sysfsRootPath)) {}
1669
dump() const1670 std::string EventHub::AssociatedDevice::dump() const {
1671 return StringPrintf("path=%s, numBatteries=%zu, numLight=%zu", sysfsRootPath.c_str(),
1672 batteryInfos.size(), lightInfos.size());
1673 }
1674
vibrate(int32_t deviceId,const VibrationElement & element)1675 void EventHub::vibrate(int32_t deviceId, const VibrationElement& element) {
1676 std::scoped_lock _l(mLock);
1677 Device* device = getDeviceLocked(deviceId);
1678 if (device != nullptr && device->hasValidFd()) {
1679 ff_effect effect;
1680 memset(&effect, 0, sizeof(effect));
1681 effect.type = FF_RUMBLE;
1682 effect.id = device->ffEffectId;
1683 // evdev FF_RUMBLE effect only supports two channels of vibration.
1684 effect.u.rumble.strong_magnitude = element.getMagnitude(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1685 effect.u.rumble.weak_magnitude = element.getMagnitude(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
1686 effect.replay.length = element.duration.count();
1687 effect.replay.delay = 0;
1688 if (ioctl(device->fd, EVIOCSFF, &effect)) {
1689 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
1690 device->identifier.name.c_str(), errno);
1691 return;
1692 }
1693 device->ffEffectId = effect.id;
1694
1695 struct input_event ev;
1696 ev.input_event_sec = 0;
1697 ev.input_event_usec = 0;
1698 ev.type = EV_FF;
1699 ev.code = device->ffEffectId;
1700 ev.value = 1;
1701 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1702 ALOGW("Could not start force feedback effect on device %s due to error %d.",
1703 device->identifier.name.c_str(), errno);
1704 return;
1705 }
1706 device->ffEffectPlaying = true;
1707 }
1708 }
1709
cancelVibrate(int32_t deviceId)1710 void EventHub::cancelVibrate(int32_t deviceId) {
1711 std::scoped_lock _l(mLock);
1712 Device* device = getDeviceLocked(deviceId);
1713 if (device != nullptr && device->hasValidFd()) {
1714 if (device->ffEffectPlaying) {
1715 device->ffEffectPlaying = false;
1716
1717 struct input_event ev;
1718 ev.input_event_sec = 0;
1719 ev.input_event_usec = 0;
1720 ev.type = EV_FF;
1721 ev.code = device->ffEffectId;
1722 ev.value = 0;
1723 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1724 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
1725 device->identifier.name.c_str(), errno);
1726 return;
1727 }
1728 }
1729 }
1730 }
1731
getVibratorIds(int32_t deviceId) const1732 std::vector<int32_t> EventHub::getVibratorIds(int32_t deviceId) const {
1733 std::scoped_lock _l(mLock);
1734 std::vector<int32_t> vibrators;
1735 Device* device = getDeviceLocked(deviceId);
1736 if (device != nullptr && device->hasValidFd() &&
1737 device->classes.test(InputDeviceClass::VIBRATOR)) {
1738 vibrators.push_back(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1739 vibrators.push_back(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
1740 }
1741 return vibrators;
1742 }
1743
1744 /**
1745 * Checks both mDevices and mOpeningDevices for a device with the descriptor passed.
1746 */
hasDeviceWithDescriptorLocked(const std::string & descriptor) const1747 bool EventHub::hasDeviceWithDescriptorLocked(const std::string& descriptor) const {
1748 for (const auto& device : mOpeningDevices) {
1749 if (descriptor == device->identifier.descriptor) {
1750 return true;
1751 }
1752 }
1753
1754 for (const auto& [id, device] : mDevices) {
1755 if (descriptor == device->identifier.descriptor) {
1756 return true;
1757 }
1758 }
1759 return false;
1760 }
1761
getDeviceLocked(int32_t deviceId) const1762 EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
1763 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
1764 deviceId = mBuiltInKeyboardId;
1765 }
1766 const auto& it = mDevices.find(deviceId);
1767 return it != mDevices.end() ? it->second.get() : nullptr;
1768 }
1769
getDeviceByPathLocked(const std::string & devicePath) const1770 EventHub::Device* EventHub::getDeviceByPathLocked(const std::string& devicePath) const {
1771 for (const auto& [id, device] : mDevices) {
1772 if (device->path == devicePath) {
1773 return device.get();
1774 }
1775 }
1776 return nullptr;
1777 }
1778
1779 /**
1780 * The file descriptor could be either input device, or a video device (associated with a
1781 * specific input device). Check both cases here, and return the device that this event
1782 * belongs to. Caller can compare the fd's once more to determine event type.
1783 * Looks through all input devices, and only attached video devices. Unattached video
1784 * devices are ignored.
1785 */
getDeviceByFdLocked(int fd) const1786 EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
1787 for (const auto& [id, device] : mDevices) {
1788 if (device->fd == fd) {
1789 // This is an input device event
1790 return device.get();
1791 }
1792 if (device->videoDevice && device->videoDevice->getFd() == fd) {
1793 // This is a video device event
1794 return device.get();
1795 }
1796 }
1797 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
1798 // and therefore should never be looked up by fd.
1799 return nullptr;
1800 }
1801
getBatteryCapacity(int32_t deviceId,int32_t batteryId) const1802 std::optional<int32_t> EventHub::getBatteryCapacity(int32_t deviceId, int32_t batteryId) const {
1803 std::filesystem::path batteryPath;
1804 {
1805 // Do not read the sysfs node to get the battery state while holding
1806 // the EventHub lock. For some peripheral devices, reading battery state
1807 // can be broken and take 5+ seconds. Holding the lock in this case would
1808 // block all other event processing during this time. For now, we assume this
1809 // call never happens on the InputReader thread and read the sysfs node outside
1810 // the lock to prevent event processing from being blocked by this call.
1811 std::scoped_lock _l(mLock);
1812
1813 const auto& infos = getBatteryInfoLocked(deviceId);
1814 auto it = infos.find(batteryId);
1815 if (it == infos.end()) {
1816 return std::nullopt;
1817 }
1818 batteryPath = it->second.path;
1819 } // release lock
1820
1821 std::string buffer;
1822
1823 // Some devices report battery capacity as an integer through the "capacity" file
1824 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY),
1825 &buffer)) {
1826 return std::stoi(base::Trim(buffer));
1827 }
1828
1829 // Other devices report capacity as an enum value POWER_SUPPLY_CAPACITY_LEVEL_XXX
1830 // These values are taken from kernel source code include/linux/power_supply.h
1831 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY_LEVEL),
1832 &buffer)) {
1833 // Remove any white space such as trailing new line
1834 const auto levelIt = BATTERY_LEVEL.find(base::Trim(buffer));
1835 if (levelIt != BATTERY_LEVEL.end()) {
1836 return levelIt->second;
1837 }
1838 }
1839
1840 return std::nullopt;
1841 }
1842
getBatteryStatus(int32_t deviceId,int32_t batteryId) const1843 std::optional<int32_t> EventHub::getBatteryStatus(int32_t deviceId, int32_t batteryId) const {
1844 std::filesystem::path batteryPath;
1845 {
1846 // Do not read the sysfs node to get the battery state while holding
1847 // the EventHub lock. For some peripheral devices, reading battery state
1848 // can be broken and take 5+ seconds. Holding the lock in this case would
1849 // block all other event processing during this time. For now, we assume this
1850 // call never happens on the InputReader thread and read the sysfs node outside
1851 // the lock to prevent event processing from being blocked by this call.
1852 std::scoped_lock _l(mLock);
1853
1854 const auto& infos = getBatteryInfoLocked(deviceId);
1855 auto it = infos.find(batteryId);
1856 if (it == infos.end()) {
1857 return std::nullopt;
1858 }
1859 batteryPath = it->second.path;
1860 } // release lock
1861
1862 std::string buffer;
1863
1864 if (!base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::STATUS),
1865 &buffer)) {
1866 ALOGE("Failed to read sysfs battery info: %s", strerror(errno));
1867 return std::nullopt;
1868 }
1869
1870 // Remove white space like trailing new line
1871 const auto statusIt = BATTERY_STATUS.find(base::Trim(buffer));
1872 if (statusIt != BATTERY_STATUS.end()) {
1873 return statusIt->second;
1874 }
1875
1876 return std::nullopt;
1877 }
1878
getEvents(int timeoutMillis)1879 std::vector<RawEvent> EventHub::getEvents(int timeoutMillis) {
1880 std::scoped_lock _l(mLock);
1881
1882 std::array<input_event, EVENT_BUFFER_SIZE> readBuffer;
1883
1884 std::vector<RawEvent> events;
1885 bool awoken = false;
1886 for (;;) {
1887 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
1888
1889 // Reopen input devices if needed.
1890 if (mNeedToReopenDevices) {
1891 mNeedToReopenDevices = false;
1892
1893 ALOGI("Reopening all input devices due to a configuration change.");
1894
1895 closeAllDevicesLocked();
1896 mNeedToScanDevices = true;
1897 break; // return to the caller before we actually rescan
1898 }
1899
1900 handleSysfsNodeChangeNotificationsLocked();
1901
1902 // Use a do-while loop to ensure that we drain the closing and opening devices loop
1903 // at least once, even if there are no devices to re-open.
1904 do {
1905 if (!mDeviceIdsToReopen.empty()) {
1906 // If there are devices that need to be re-opened, ensure that we re-open them
1907 // one at a time to send the DEVICE_REMOVED and DEVICE_ADDED notifications for
1908 // each before moving on to the next. This is to avoid notifying all device
1909 // removals and additions in one batch, which could cause additional unnecessary
1910 // device added/removed notifications for merged InputDevices from InputReader.
1911 const int32_t deviceId = mDeviceIdsToReopen.back();
1912 mDeviceIdsToReopen.erase(mDeviceIdsToReopen.end() - 1);
1913 if (auto it = mDevices.find(deviceId); it != mDevices.end()) {
1914 ALOGI("Reopening input device: id=%d, name=%s", it->second->id,
1915 it->second->identifier.name.c_str());
1916 const auto path = it->second->path;
1917 closeDeviceLocked(*it->second);
1918 openDeviceLocked(path);
1919 }
1920 }
1921
1922 // Report any devices that had last been added/removed.
1923 for (auto it = mClosingDevices.begin(); it != mClosingDevices.end();) {
1924 std::unique_ptr<Device> device = std::move(*it);
1925 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id,
1926 device->path.c_str());
1927 const int32_t deviceId = (device->id == mBuiltInKeyboardId)
1928 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
1929 : device->id;
1930 events.push_back({
1931 .when = now,
1932 .deviceId = deviceId,
1933 .type = DEVICE_REMOVED,
1934 });
1935 it = mClosingDevices.erase(it);
1936 if (events.size() == EVENT_BUFFER_SIZE) {
1937 break;
1938 }
1939 }
1940
1941 if (mNeedToScanDevices) {
1942 mNeedToScanDevices = false;
1943 scanDevicesLocked();
1944 }
1945
1946 while (!mOpeningDevices.empty()) {
1947 std::unique_ptr<Device> device = std::move(*mOpeningDevices.rbegin());
1948 mOpeningDevices.pop_back();
1949 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id,
1950 device->path.c_str());
1951 const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1952 events.push_back({
1953 .when = now,
1954 .deviceId = deviceId,
1955 .type = DEVICE_ADDED,
1956 });
1957
1958 // Try to find a matching video device by comparing device names
1959 for (auto it = mUnattachedVideoDevices.begin(); it != mUnattachedVideoDevices.end();
1960 it++) {
1961 std::unique_ptr<TouchVideoDevice>& videoDevice = *it;
1962 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
1963 // videoDevice was transferred to 'device'
1964 it = mUnattachedVideoDevices.erase(it);
1965 break;
1966 }
1967 }
1968
1969 auto [dev_it, inserted] = mDevices.insert_or_assign(device->id, std::move(device));
1970 if (!inserted) {
1971 ALOGW("Device id %d exists, replaced.", device->id);
1972 }
1973 if (events.size() == EVENT_BUFFER_SIZE) {
1974 break;
1975 }
1976 }
1977
1978 // Perform this loop of re-opening devices so that we re-open one device at a time.
1979 } while (!mDeviceIdsToReopen.empty());
1980
1981 if (events.size() == EVENT_BUFFER_SIZE) {
1982 break;
1983 }
1984
1985 // Grab the next input event.
1986 bool deviceChanged = false;
1987 while (mPendingEventIndex < mPendingEventCount) {
1988 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
1989 if (eventItem.data.fd == mINotifyFd) {
1990 if (eventItem.events & EPOLLIN) {
1991 mPendingINotify = true;
1992 } else {
1993 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
1994 }
1995 continue;
1996 }
1997
1998 if (eventItem.data.fd == mWakeReadPipeFd) {
1999 if (eventItem.events & EPOLLIN) {
2000 ALOGV("awoken after wake()");
2001 awoken = true;
2002 char wakeReadBuffer[16];
2003 ssize_t nRead;
2004 do {
2005 nRead = read(mWakeReadPipeFd, wakeReadBuffer, sizeof(wakeReadBuffer));
2006 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(wakeReadBuffer));
2007 } else {
2008 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
2009 eventItem.events);
2010 }
2011 continue;
2012 }
2013
2014 Device* device = getDeviceByFdLocked(eventItem.data.fd);
2015 if (device == nullptr) {
2016 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
2017 eventItem.data.fd);
2018 ALOG_ASSERT(!DEBUG);
2019 continue;
2020 }
2021 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
2022 if (eventItem.events & EPOLLIN) {
2023 size_t numFrames = device->videoDevice->readAndQueueFrames();
2024 if (numFrames == 0) {
2025 ALOGE("Received epoll event for video device %s, but could not read frame",
2026 device->videoDevice->getName().c_str());
2027 }
2028 } else if (eventItem.events & EPOLLHUP) {
2029 // TODO(b/121395353) - consider adding EPOLLRDHUP
2030 ALOGI("Removing video device %s due to epoll hang-up event.",
2031 device->videoDevice->getName().c_str());
2032 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
2033 device->videoDevice = nullptr;
2034 } else {
2035 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
2036 device->videoDevice->getName().c_str());
2037 ALOG_ASSERT(!DEBUG);
2038 }
2039 continue;
2040 }
2041 // This must be an input event
2042 if (eventItem.events & EPOLLIN) {
2043 int32_t readSize =
2044 read(device->fd, readBuffer.data(),
2045 sizeof(decltype(readBuffer)::value_type) * readBuffer.size());
2046 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
2047 // Device was removed before INotify noticed.
2048 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
2049 " capacity: %zu errno: %d)\n",
2050 device->fd, readSize, readBuffer.size(), errno);
2051 deviceChanged = true;
2052 closeDeviceLocked(*device);
2053 } else if (readSize < 0) {
2054 if (errno != EAGAIN && errno != EINTR) {
2055 ALOGW("could not get event (errno=%d)", errno);
2056 }
2057 } else if ((readSize % sizeof(struct input_event)) != 0) {
2058 ALOGE("could not get event (wrong size: %d)", readSize);
2059 } else {
2060 const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
2061
2062 const size_t count = size_t(readSize) / sizeof(struct input_event);
2063 for (size_t i = 0; i < count; i++) {
2064 struct input_event& iev = readBuffer[i];
2065 device->trackInputEvent(iev);
2066 events.push_back({
2067 .when = processEventTimestamp(iev),
2068 .readTime = systemTime(SYSTEM_TIME_MONOTONIC),
2069 .deviceId = deviceId,
2070 .type = iev.type,
2071 .code = iev.code,
2072 .value = iev.value,
2073 });
2074 }
2075 if (events.size() >= EVENT_BUFFER_SIZE) {
2076 // The result buffer is full. Reset the pending event index
2077 // so we will try to read the device again on the next iteration.
2078 mPendingEventIndex -= 1;
2079 break;
2080 }
2081 }
2082 } else if (eventItem.events & EPOLLHUP) {
2083 ALOGI("Removing device %s due to epoll hang-up event.",
2084 device->identifier.name.c_str());
2085 deviceChanged = true;
2086 closeDeviceLocked(*device);
2087 } else {
2088 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
2089 device->identifier.name.c_str());
2090 }
2091 }
2092
2093 // readNotify() will modify the list of devices so this must be done after
2094 // processing all other events to ensure that we read all remaining events
2095 // before closing the devices.
2096 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
2097 mPendingINotify = false;
2098 const auto res = readNotifyLocked();
2099 if (!res.ok()) {
2100 ALOGW("Failed to read from inotify: %s", res.error().message().c_str());
2101 }
2102 deviceChanged = true;
2103 }
2104
2105 // Report added or removed devices immediately.
2106 if (deviceChanged) {
2107 continue;
2108 }
2109
2110 // Return now if we have collected any events or if we were explicitly awoken.
2111 if (!events.empty() || awoken) {
2112 break;
2113 }
2114
2115 // Poll for events.
2116 // When a device driver has pending (unread) events, it acquires
2117 // a kernel wake lock. Once the last pending event has been read, the device
2118 // driver will release the kernel wake lock, but the epoll will hold the wakelock,
2119 // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
2120 // is called again for the same fd that produced the event.
2121 // Thus the system can only sleep if there are no events pending or
2122 // currently being processed.
2123 //
2124 // The timeout is advisory only. If the device is asleep, it will not wake just to
2125 // service the timeout.
2126 mPendingEventIndex = 0;
2127
2128 mLock.unlock(); // release lock before poll
2129
2130 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
2131
2132 mLock.lock(); // reacquire lock after poll
2133
2134 if (pollResult == 0) {
2135 // Timed out.
2136 mPendingEventCount = 0;
2137 break;
2138 }
2139
2140 if (pollResult < 0) {
2141 // An error occurred.
2142 mPendingEventCount = 0;
2143
2144 // Sleep after errors to avoid locking up the system.
2145 // Hopefully the error is transient.
2146 if (errno != EINTR) {
2147 ALOGW("poll failed (errno=%d)\n", errno);
2148 usleep(100000);
2149 }
2150 } else {
2151 // Some events occurred.
2152 mPendingEventCount = size_t(pollResult);
2153 }
2154 }
2155
2156 // All done, return the number of events we read.
2157 return events;
2158 }
2159
getVideoFrames(int32_t deviceId)2160 std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
2161 std::scoped_lock _l(mLock);
2162
2163 Device* device = getDeviceLocked(deviceId);
2164 if (device == nullptr || !device->videoDevice) {
2165 return {};
2166 }
2167 return device->videoDevice->consumeFrames();
2168 }
2169
wake()2170 void EventHub::wake() {
2171 ALOGV("wake() called");
2172
2173 ssize_t nWrite;
2174 do {
2175 nWrite = write(mWakeWritePipeFd, "W", 1);
2176 } while (nWrite == -1 && errno == EINTR);
2177
2178 if (nWrite != 1 && errno != EAGAIN) {
2179 ALOGW("Could not write wake signal: %s", strerror(errno));
2180 }
2181 }
2182
scanDevicesLocked()2183 void EventHub::scanDevicesLocked() {
2184 status_t result;
2185 std::error_code errorCode;
2186
2187 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
2188 result = scanDirLocked(DEVICE_INPUT_PATH);
2189 if (result < 0) {
2190 ALOGE("scan dir failed for %s", DEVICE_INPUT_PATH);
2191 }
2192 } else {
2193 if (errorCode) {
2194 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
2195 errorCode.message().c_str());
2196 }
2197 }
2198 if (isV4lScanningEnabled()) {
2199 result = scanVideoDirLocked(DEVICE_PATH);
2200 if (result != OK) {
2201 ALOGE("scan video dir failed for %s", DEVICE_PATH);
2202 }
2203 }
2204 if (mDevices.find(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) == mDevices.end()) {
2205 createVirtualKeyboardLocked();
2206 }
2207 }
2208
2209 // ----------------------------------------------------------------------------
2210
registerFdForEpoll(int fd)2211 status_t EventHub::registerFdForEpoll(int fd) {
2212 // TODO(b/121395353) - consider adding EPOLLRDHUP
2213 struct epoll_event eventItem = {};
2214 eventItem.events = EPOLLIN | EPOLLWAKEUP;
2215 eventItem.data.fd = fd;
2216 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
2217 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
2218 return -errno;
2219 }
2220 return OK;
2221 }
2222
unregisterFdFromEpoll(int fd)2223 status_t EventHub::unregisterFdFromEpoll(int fd) {
2224 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
2225 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
2226 return -errno;
2227 }
2228 return OK;
2229 }
2230
registerDeviceForEpollLocked(Device & device)2231 status_t EventHub::registerDeviceForEpollLocked(Device& device) {
2232 status_t result = registerFdForEpoll(device.fd);
2233 if (result != OK) {
2234 ALOGE("Could not add input device fd to epoll for device %" PRId32, device.id);
2235 return result;
2236 }
2237 if (device.videoDevice) {
2238 registerVideoDeviceForEpollLocked(*device.videoDevice);
2239 }
2240 return result;
2241 }
2242
registerVideoDeviceForEpollLocked(const TouchVideoDevice & videoDevice)2243 void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
2244 status_t result = registerFdForEpoll(videoDevice.getFd());
2245 if (result != OK) {
2246 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
2247 }
2248 }
2249
unregisterDeviceFromEpollLocked(Device & device)2250 status_t EventHub::unregisterDeviceFromEpollLocked(Device& device) {
2251 if (device.hasValidFd()) {
2252 status_t result = unregisterFdFromEpoll(device.fd);
2253 if (result != OK) {
2254 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device.id);
2255 return result;
2256 }
2257 }
2258 if (device.videoDevice) {
2259 unregisterVideoDeviceFromEpollLocked(*device.videoDevice);
2260 }
2261 return OK;
2262 }
2263
unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice & videoDevice)2264 void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
2265 if (videoDevice.hasValidFd()) {
2266 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
2267 if (result != OK) {
2268 ALOGW("Could not remove video device fd from epoll for device: %s",
2269 videoDevice.getName().c_str());
2270 }
2271 }
2272 }
2273
reportDeviceAddedForStatisticsLocked(const InputDeviceIdentifier & identifier,ftl::Flags<InputDeviceClass> classes)2274 void EventHub::reportDeviceAddedForStatisticsLocked(const InputDeviceIdentifier& identifier,
2275 ftl::Flags<InputDeviceClass> classes) {
2276 SHA256_CTX ctx;
2277 SHA256_Init(&ctx);
2278 SHA256_Update(&ctx, reinterpret_cast<const uint8_t*>(identifier.uniqueId.c_str()),
2279 identifier.uniqueId.size());
2280 std::array<uint8_t, SHA256_DIGEST_LENGTH> digest;
2281 SHA256_Final(digest.data(), &ctx);
2282
2283 std::string obfuscatedId;
2284 for (size_t i = 0; i < OBFUSCATED_LENGTH; i++) {
2285 obfuscatedId += StringPrintf("%02x", digest[i]);
2286 }
2287
2288 android::util::stats_write(android::util::INPUTDEVICE_REGISTERED, identifier.name.c_str(),
2289 identifier.vendor, identifier.product, identifier.version,
2290 identifier.bus, obfuscatedId.c_str(), classes.get());
2291 }
2292
openDeviceLocked(const std::string & devicePath)2293 void EventHub::openDeviceLocked(const std::string& devicePath) {
2294 // If an input device happens to register around the time when EventHub's constructor runs, it
2295 // is possible that the same input event node (for example, /dev/input/event3) will be noticed
2296 // in both 'inotify' callback and also in the 'scanDirLocked' pass. To prevent duplicate devices
2297 // from getting registered, ensure that this path is not already covered by an existing device.
2298 for (const auto& [deviceId, device] : mDevices) {
2299 if (device->path == devicePath) {
2300 return; // device was already registered
2301 }
2302 }
2303
2304 char buffer[80];
2305
2306 ALOGV("Opening device: %s", devicePath.c_str());
2307
2308 int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
2309 if (fd < 0) {
2310 ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
2311 return;
2312 }
2313
2314 InputDeviceIdentifier identifier;
2315
2316 // Get device name.
2317 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
2318 ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
2319 } else {
2320 buffer[sizeof(buffer) - 1] = '\0';
2321 identifier.name = buffer;
2322 }
2323
2324 // Check to see if the device is on our excluded list
2325 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
2326 const std::string& item = mExcludedDevices[i];
2327 if (identifier.name == item) {
2328 ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
2329 close(fd);
2330 return;
2331 }
2332 }
2333
2334 // Get device driver version.
2335 int driverVersion;
2336 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
2337 ALOGE("could not get driver version for %s, %s\n", devicePath.c_str(), strerror(errno));
2338 close(fd);
2339 return;
2340 }
2341
2342 // Get device identifier.
2343 struct input_id inputId;
2344 if (ioctl(fd, EVIOCGID, &inputId)) {
2345 ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
2346 close(fd);
2347 return;
2348 }
2349 identifier.bus = inputId.bustype;
2350 identifier.product = inputId.product;
2351 identifier.vendor = inputId.vendor;
2352 identifier.version = inputId.version;
2353
2354 // Get device physical location.
2355 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
2356 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
2357 } else {
2358 buffer[sizeof(buffer) - 1] = '\0';
2359 identifier.location = buffer;
2360 }
2361
2362 // Get device unique id.
2363 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
2364 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
2365 } else {
2366 buffer[sizeof(buffer) - 1] = '\0';
2367 identifier.uniqueId = buffer;
2368 }
2369
2370 // Attempt to get the bluetooth address of an input device from the uniqueId.
2371 if (identifier.bus == BUS_BLUETOOTH &&
2372 std::regex_match(identifier.uniqueId,
2373 std::regex("^[A-Fa-f0-9]{2}(?::[A-Fa-f0-9]{2}){5}$"))) {
2374 identifier.bluetoothAddress = identifier.uniqueId;
2375 // The Bluetooth stack requires alphabetic characters to be uppercase in a valid address.
2376 for (auto& c : *identifier.bluetoothAddress) {
2377 c = ::toupper(c);
2378 }
2379 }
2380
2381 // Fill in the descriptor.
2382 assignDescriptorLocked(identifier);
2383
2384 // Load the configuration file for the device.
2385 std::shared_ptr<PropertyMap> configuration = nullptr;
2386 base::Result<std::shared_ptr<PropertyMap>> propertyMapResult = loadConfiguration(identifier);
2387 if (!propertyMapResult.ok()) {
2388 ALOGE("Error loading input device configuration file for device '%s'. "
2389 "Using default configuration. Error: %s",
2390 identifier.name.c_str(), propertyMapResult.error().message().c_str());
2391 } else {
2392 configuration = propertyMapResult.value();
2393 }
2394
2395 // Allocate device. (The device object takes ownership of the fd at this point.)
2396 int32_t deviceId = mNextDeviceId++;
2397 std::unique_ptr<Device> device =
2398 std::make_unique<Device>(fd, deviceId, devicePath, identifier, configuration);
2399
2400 ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
2401 ALOGV(" bus: %04x\n"
2402 " vendor %04x\n"
2403 " product %04x\n"
2404 " version %04x\n",
2405 identifier.bus, identifier.vendor, identifier.product, identifier.version);
2406 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
2407 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
2408 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
2409 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
2410 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
2411 driverVersion & 0xff);
2412
2413 // Obtain the associated device, if any.
2414 device->associatedDevice = obtainAssociatedDeviceLocked(devicePath, device->configuration);
2415
2416 // Figure out the kinds of events the device reports.
2417 device->readDeviceBitMask(EVIOCGBIT(EV_KEY, 0), device->keyBitmask);
2418 device->readDeviceBitMask(EVIOCGBIT(EV_ABS, 0), device->absBitmask);
2419 device->readDeviceBitMask(EVIOCGBIT(EV_REL, 0), device->relBitmask);
2420 device->readDeviceBitMask(EVIOCGBIT(EV_SW, 0), device->swBitmask);
2421 device->readDeviceBitMask(EVIOCGBIT(EV_LED, 0), device->ledBitmask);
2422 device->readDeviceBitMask(EVIOCGBIT(EV_FF, 0), device->ffBitmask);
2423 device->readDeviceBitMask(EVIOCGBIT(EV_MSC, 0), device->mscBitmask);
2424 device->readDeviceBitMask(EVIOCGPROP(0), device->propBitmask);
2425
2426 // See if this is a device with keys. This could be full keyboard, or other devices like
2427 // gamepads, joysticks, and styluses with buttons that should generate key presses.
2428 bool haveKeyboardKeys =
2429 device->keyBitmask.any(0, BTN_MISC) || device->keyBitmask.any(BTN_WHEEL, KEY_MAX + 1);
2430 bool haveGamepadButtons = device->keyBitmask.any(BTN_MISC, BTN_MOUSE) ||
2431 device->keyBitmask.any(BTN_JOYSTICK, BTN_DIGI);
2432 bool haveStylusButtons = device->keyBitmask.test(BTN_STYLUS) ||
2433 device->keyBitmask.test(BTN_STYLUS2) || device->keyBitmask.test(BTN_STYLUS3);
2434 if (haveKeyboardKeys || haveGamepadButtons || haveStylusButtons) {
2435 device->classes |= InputDeviceClass::KEYBOARD;
2436 }
2437
2438 // See if this is a cursor device such as a trackball or mouse.
2439 if (device->keyBitmask.test(BTN_MOUSE) && device->relBitmask.test(REL_X) &&
2440 device->relBitmask.test(REL_Y)) {
2441 device->classes |= InputDeviceClass::CURSOR;
2442 }
2443
2444 // See if the device is specially configured to be of a certain type.
2445 if (device->configuration) {
2446 std::string deviceType = device->configuration->getString("device.type").value_or("");
2447 if (deviceType == "rotaryEncoder") {
2448 device->classes |= InputDeviceClass::ROTARY_ENCODER;
2449 } else if (deviceType == "externalStylus") {
2450 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
2451 }
2452 }
2453
2454 // See if this is a touch pad.
2455 // Is this a new modern multi-touch driver?
2456 if (device->absBitmask.test(ABS_MT_POSITION_X) && device->absBitmask.test(ABS_MT_POSITION_Y)) {
2457 // Some joysticks such as the PS3 controller report axes that conflict
2458 // with the ABS_MT range. Try to confirm that the device really is
2459 // a touch screen.
2460 if (device->keyBitmask.test(BTN_TOUCH) || !haveGamepadButtons) {
2461 device->classes |= (InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT);
2462 if (device->propBitmask.test(INPUT_PROP_POINTER) &&
2463 !device->keyBitmask.any(BTN_TOOL_PEN, BTN_TOOL_FINGER) && !haveStylusButtons) {
2464 device->classes |= InputDeviceClass::TOUCHPAD;
2465 }
2466 }
2467 // Is this an old style single-touch driver?
2468 } else if (device->keyBitmask.test(BTN_TOUCH) && device->absBitmask.test(ABS_X) &&
2469 device->absBitmask.test(ABS_Y)) {
2470 device->classes |= InputDeviceClass::TOUCH;
2471 // Is this a stylus that reports contact/pressure independently of touch coordinates?
2472 } else if ((device->absBitmask.test(ABS_PRESSURE) || device->keyBitmask.test(BTN_TOUCH)) &&
2473 !device->absBitmask.test(ABS_X) && !device->absBitmask.test(ABS_Y)) {
2474 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
2475 }
2476
2477 // See if this device is a joystick.
2478 // Assumes that joysticks always have gamepad buttons in order to distinguish them
2479 // from other devices such as accelerometers that also have absolute axes.
2480 if (haveGamepadButtons) {
2481 auto assumedClasses = device->classes | InputDeviceClass::JOYSTICK;
2482 for (int i = 0; i <= ABS_MAX; i++) {
2483 if (device->absBitmask.test(i) &&
2484 (getAbsAxisUsage(i, assumedClasses).test(InputDeviceClass::JOYSTICK))) {
2485 device->classes = assumedClasses;
2486 break;
2487 }
2488 }
2489 }
2490
2491 // Check whether this device is an accelerometer.
2492 if (device->propBitmask.test(INPUT_PROP_ACCELEROMETER)) {
2493 device->classes |= InputDeviceClass::SENSOR;
2494 }
2495
2496 // Check whether this device has switches.
2497 for (int i = 0; i <= SW_MAX; i++) {
2498 if (device->swBitmask.test(i)) {
2499 device->classes |= InputDeviceClass::SWITCH;
2500 break;
2501 }
2502 }
2503
2504 // Check whether this device supports the vibrator.
2505 if (device->ffBitmask.test(FF_RUMBLE)) {
2506 device->classes |= InputDeviceClass::VIBRATOR;
2507 }
2508
2509 // Configure virtual keys.
2510 if ((device->classes.test(InputDeviceClass::TOUCH))) {
2511 // Load the virtual keys for the touch screen, if any.
2512 // We do this now so that we can make sure to load the keymap if necessary.
2513 bool success = device->loadVirtualKeyMapLocked();
2514 if (success) {
2515 device->classes |= InputDeviceClass::KEYBOARD;
2516 }
2517 }
2518
2519 // Load the key map.
2520 // We need to do this for joysticks too because the key layout may specify axes, and for
2521 // sensor as well because the key layout may specify the axes to sensor data mapping.
2522 status_t keyMapStatus = NAME_NOT_FOUND;
2523 if (device->classes.any(InputDeviceClass::KEYBOARD | InputDeviceClass::JOYSTICK |
2524 InputDeviceClass::SENSOR)) {
2525 // Load the keymap for the device.
2526 keyMapStatus = device->loadKeyMapLocked();
2527 }
2528
2529 // Configure the keyboard, gamepad or virtual keyboard.
2530 if (device->classes.test(InputDeviceClass::KEYBOARD)) {
2531 // Register the keyboard as a built-in keyboard if it is eligible.
2532 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
2533 isEligibleBuiltInKeyboard(device->identifier, device->configuration.get(),
2534 &device->keyMap)) {
2535 mBuiltInKeyboardId = device->id;
2536 }
2537
2538 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
2539 if (device->hasKeycodeLocked(AKEYCODE_Q)) {
2540 device->classes |= InputDeviceClass::ALPHAKEY;
2541 }
2542
2543 // See if this device has a D-pad.
2544 if (std::all_of(DPAD_REQUIRED_KEYCODES.begin(), DPAD_REQUIRED_KEYCODES.end(),
2545 [&](int32_t keycode) { return device->hasKeycodeLocked(keycode); })) {
2546 device->classes |= InputDeviceClass::DPAD;
2547 }
2548
2549 // See if this device has a gamepad.
2550 if (std::any_of(GAMEPAD_KEYCODES.begin(), GAMEPAD_KEYCODES.end(),
2551 [&](int32_t keycode) { return device->hasKeycodeLocked(keycode); })) {
2552 device->classes |= InputDeviceClass::GAMEPAD;
2553 }
2554
2555 // See if this device has any stylus buttons that we would want to fuse with touch data.
2556 if (!device->classes.any(InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT) &&
2557 !device->classes.any(InputDeviceClass::ALPHAKEY) &&
2558 std::any_of(STYLUS_BUTTON_KEYCODES.begin(), STYLUS_BUTTON_KEYCODES.end(),
2559 [&](int32_t keycode) { return device->hasKeycodeLocked(keycode); })) {
2560 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
2561 }
2562 }
2563
2564 // See if the device is a rotary encoder with a single scroll axis and nothing else.
2565 if (vd_flags::virtual_rotary() && device->classes == ftl::Flags<InputDeviceClass>(0) &&
2566 device->relBitmask.test(REL_WHEEL) && !device->relBitmask.test(REL_HWHEEL)) {
2567 device->classes |= InputDeviceClass::ROTARY_ENCODER;
2568 }
2569
2570 // If the device isn't recognized as something we handle, don't monitor it.
2571 if (device->classes == ftl::Flags<InputDeviceClass>(0)) {
2572 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
2573 device->identifier.name.c_str());
2574 return;
2575 }
2576
2577 // Classify InputDeviceClass::BATTERY.
2578 if (device->associatedDevice && !device->associatedDevice->batteryInfos.empty()) {
2579 device->classes |= InputDeviceClass::BATTERY;
2580 }
2581
2582 // Classify InputDeviceClass::LIGHT.
2583 if (device->associatedDevice && !device->associatedDevice->lightInfos.empty()) {
2584 device->classes |= InputDeviceClass::LIGHT;
2585 }
2586
2587 // Determine whether the device has a mic.
2588 if (device->deviceHasMicLocked()) {
2589 device->classes |= InputDeviceClass::MIC;
2590 }
2591
2592 // Determine whether the device is external or internal.
2593 if (device->isExternalDeviceLocked()) {
2594 device->classes |= InputDeviceClass::EXTERNAL;
2595 }
2596
2597 if (device->classes.any(InputDeviceClass::JOYSTICK | InputDeviceClass::DPAD) &&
2598 device->classes.test(InputDeviceClass::GAMEPAD)) {
2599 device->controllerNumber = getNextControllerNumberLocked(device->identifier.name);
2600 device->setLedForControllerLocked();
2601 }
2602
2603 if (registerDeviceForEpollLocked(*device) != OK) {
2604 return;
2605 }
2606
2607 device->configureFd();
2608
2609 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=%s, "
2610 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
2611 deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(),
2612 device->classes.string().c_str(), device->configurationFile.c_str(),
2613 device->keyMap.keyLayoutFile.c_str(), device->keyMap.keyCharacterMapFile.c_str(),
2614 toString(mBuiltInKeyboardId == deviceId));
2615
2616 addDeviceLocked(std::move(device));
2617 }
2618
openVideoDeviceLocked(const std::string & devicePath)2619 void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
2620 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
2621 if (!videoDevice) {
2622 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
2623 return;
2624 }
2625 // Transfer ownership of this video device to a matching input device
2626 for (const auto& [id, device] : mDevices) {
2627 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
2628 return; // 'device' now owns 'videoDevice'
2629 }
2630 }
2631
2632 // Couldn't find a matching input device, so just add it to a temporary holding queue.
2633 // A matching input device may appear later.
2634 ALOGI("Adding video device %s to list of unattached video devices",
2635 videoDevice->getName().c_str());
2636 mUnattachedVideoDevices.push_back(std::move(videoDevice));
2637 }
2638
tryAddVideoDeviceLocked(EventHub::Device & device,std::unique_ptr<TouchVideoDevice> & videoDevice)2639 bool EventHub::tryAddVideoDeviceLocked(EventHub::Device& device,
2640 std::unique_ptr<TouchVideoDevice>& videoDevice) {
2641 if (videoDevice->getName() != device.identifier.name) {
2642 return false;
2643 }
2644 device.videoDevice = std::move(videoDevice);
2645 if (device.enabled) {
2646 registerVideoDeviceForEpollLocked(*device.videoDevice);
2647 }
2648 return true;
2649 }
2650
isDeviceEnabled(int32_t deviceId) const2651 bool EventHub::isDeviceEnabled(int32_t deviceId) const {
2652 std::scoped_lock _l(mLock);
2653 Device* device = getDeviceLocked(deviceId);
2654 if (device == nullptr) {
2655 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2656 return false;
2657 }
2658 return device->enabled;
2659 }
2660
enableDevice(int32_t deviceId)2661 status_t EventHub::enableDevice(int32_t deviceId) {
2662 std::scoped_lock _l(mLock);
2663 Device* device = getDeviceLocked(deviceId);
2664 if (device == nullptr) {
2665 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2666 return BAD_VALUE;
2667 }
2668 if (device->enabled) {
2669 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
2670 return OK;
2671 }
2672 status_t result = device->enable();
2673 if (result != OK) {
2674 ALOGE("Failed to enable device %" PRId32, deviceId);
2675 return result;
2676 }
2677
2678 device->configureFd();
2679
2680 return registerDeviceForEpollLocked(*device);
2681 }
2682
disableDevice(int32_t deviceId)2683 status_t EventHub::disableDevice(int32_t deviceId) {
2684 std::scoped_lock _l(mLock);
2685 Device* device = getDeviceLocked(deviceId);
2686 if (device == nullptr) {
2687 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2688 return BAD_VALUE;
2689 }
2690 if (!device->enabled) {
2691 ALOGW("Duplicate call to %s, input device already disabled", __func__);
2692 return OK;
2693 }
2694 unregisterDeviceFromEpollLocked(*device);
2695 return device->disable();
2696 }
2697
getSysfsRootPath(int32_t deviceId) const2698 std::filesystem::path EventHub::getSysfsRootPath(int32_t deviceId) const {
2699 std::scoped_lock _l(mLock);
2700 Device* device = getDeviceLocked(deviceId);
2701 if (device == nullptr) {
2702 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2703 return {};
2704 }
2705
2706 return device->associatedDevice ? device->associatedDevice->sysfsRootPath
2707 : std::filesystem::path{};
2708 }
2709
2710 // TODO(b/274755573): Shift to uevent handling on native side and remove this method
2711 // Currently using Java UEventObserver to trigger this which uses UEvent infrastructure that uses a
2712 // NETLINK socket to observe UEvents. We can create similar infrastructure on Eventhub side to
2713 // directly observe UEvents instead of triggering from Java side.
sysfsNodeChanged(const std::string & sysfsNodePath)2714 void EventHub::sysfsNodeChanged(const std::string& sysfsNodePath) {
2715 mChangedSysfsNodeNotifications.emplace(sysfsNodePath);
2716 }
2717
handleSysfsNodeChangeNotificationsLocked()2718 void EventHub::handleSysfsNodeChangeNotificationsLocked() {
2719 // Use a set to de-dup any repeated notifications.
2720 std::set<std::string> changedNodes;
2721 while (true) {
2722 auto node = mChangedSysfsNodeNotifications.popWithTimeout(std::chrono::nanoseconds(0));
2723 if (!node.has_value()) break;
2724 changedNodes.emplace(*node);
2725 }
2726 if (changedNodes.empty()) {
2727 return;
2728 }
2729
2730 // Testing whether a sysfs node changed involves several syscalls, so use a cache to avoid
2731 // testing the same node multiple times.
2732 // TODO(b/281822656): Notify InputReader separately when an AssociatedDevice changes,
2733 // instead of needing to re-open all of Devices that are associated with it.
2734 std::map<std::shared_ptr<const AssociatedDevice>, bool /*changed*/> testedDevices;
2735 auto shouldReopenDevice = [&testedDevices, &changedNodes](const Device& dev) {
2736 if (!dev.associatedDevice) {
2737 return false;
2738 }
2739 if (auto testedIt = testedDevices.find(dev.associatedDevice);
2740 testedIt != testedDevices.end()) {
2741 return testedIt->second;
2742 }
2743 // Cache miss
2744 const bool anyNodesChanged =
2745 std::any_of(changedNodes.begin(), changedNodes.end(), [&](const std::string& node) {
2746 return node.find(dev.associatedDevice->sysfsRootPath.string()) !=
2747 std::string::npos;
2748 });
2749 if (!anyNodesChanged) {
2750 testedDevices.emplace(dev.associatedDevice, false);
2751 return false;
2752 }
2753 auto reloadedDevice = AssociatedDevice(dev.associatedDevice->sysfsRootPath,
2754 dev.associatedDevice->baseDevConfig);
2755 const bool changed = *dev.associatedDevice != reloadedDevice;
2756 if (changed) {
2757 ALOGI("sysfsNodeChanged: Identified change in sysfs nodes for device: %s",
2758 dev.identifier.name.c_str());
2759 }
2760 testedDevices.emplace(dev.associatedDevice, changed);
2761 return changed;
2762 };
2763
2764 // Check in opening devices. These can be re-opened directly because we have not yet notified
2765 // the Reader about these devices.
2766 for (const auto& dev : mOpeningDevices) {
2767 if (shouldReopenDevice(*dev)) {
2768 ALOGI("Reopening input device from mOpeningDevices: id=%d, name=%s", dev->id,
2769 dev->identifier.name.c_str());
2770 const auto path = dev->path;
2771 closeDeviceLocked(*dev); // The Device object is deleted by this function.
2772 openDeviceLocked(path);
2773 }
2774 }
2775
2776 // Check in already added devices. Add them to the re-opening list so they can be
2777 // re-opened serially.
2778 for (const auto& [id, dev] : mDevices) {
2779 if (shouldReopenDevice(*dev)) {
2780 mDeviceIdsToReopen.emplace_back(dev->id);
2781 }
2782 }
2783 }
2784
createVirtualKeyboardLocked()2785 void EventHub::createVirtualKeyboardLocked() {
2786 InputDeviceIdentifier identifier;
2787 identifier.name = "Virtual";
2788 identifier.uniqueId = "<virtual>";
2789 assignDescriptorLocked(identifier);
2790
2791 std::unique_ptr<Device> device =
2792 std::make_unique<Device>(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
2793 identifier, /*associatedDevice=*/nullptr);
2794 device->classes = InputDeviceClass::KEYBOARD | InputDeviceClass::ALPHAKEY |
2795 InputDeviceClass::DPAD | InputDeviceClass::VIRTUAL;
2796 device->loadKeyMapLocked();
2797 addDeviceLocked(std::move(device));
2798 }
2799
addDeviceLocked(std::unique_ptr<Device> device)2800 void EventHub::addDeviceLocked(std::unique_ptr<Device> device) {
2801 reportDeviceAddedForStatisticsLocked(device->identifier, device->classes);
2802 mOpeningDevices.push_back(std::move(device));
2803 }
2804
getNextControllerNumberLocked(const std::string & name)2805 int32_t EventHub::getNextControllerNumberLocked(const std::string& name) {
2806 if (mControllerNumbers.isFull()) {
2807 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
2808 name.c_str());
2809 return 0;
2810 }
2811 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
2812 // one
2813 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
2814 }
2815
releaseControllerNumberLocked(int32_t num)2816 void EventHub::releaseControllerNumberLocked(int32_t num) {
2817 if (num > 0) {
2818 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
2819 }
2820 }
2821
closeDeviceByPathLocked(const std::string & devicePath)2822 void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
2823 Device* device = getDeviceByPathLocked(devicePath);
2824 if (device != nullptr) {
2825 closeDeviceLocked(*device);
2826 return;
2827 }
2828 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
2829 }
2830
2831 /**
2832 * Find the video device by filename, and close it.
2833 * The video device is closed by path during an inotify event, where we don't have the
2834 * additional context about the video device fd, or the associated input device.
2835 */
closeVideoDeviceByPathLocked(const std::string & devicePath)2836 void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
2837 // A video device may be owned by an existing input device, or it may be stored in
2838 // the mUnattachedVideoDevices queue. Check both locations.
2839 for (const auto& [id, device] : mDevices) {
2840 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
2841 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
2842 device->videoDevice = nullptr;
2843 return;
2844 }
2845 }
2846 std::erase_if(mUnattachedVideoDevices,
2847 [&devicePath](const std::unique_ptr<TouchVideoDevice>& videoDevice) {
2848 return videoDevice->getPath() == devicePath;
2849 });
2850 }
2851
closeAllDevicesLocked()2852 void EventHub::closeAllDevicesLocked() {
2853 mUnattachedVideoDevices.clear();
2854 while (!mDevices.empty()) {
2855 closeDeviceLocked(*(mDevices.begin()->second));
2856 }
2857 }
2858
closeDeviceLocked(Device & device)2859 void EventHub::closeDeviceLocked(Device& device) {
2860 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=%s", device.path.c_str(),
2861 device.identifier.name.c_str(), device.id, device.fd, device.classes.string().c_str());
2862
2863 if (device.id == mBuiltInKeyboardId) {
2864 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
2865 device.path.c_str(), mBuiltInKeyboardId);
2866 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
2867 }
2868
2869 unregisterDeviceFromEpollLocked(device);
2870 if (device.videoDevice) {
2871 // This must be done after the video device is removed from epoll
2872 mUnattachedVideoDevices.push_back(std::move(device.videoDevice));
2873 }
2874
2875 releaseControllerNumberLocked(device.controllerNumber);
2876 device.controllerNumber = 0;
2877 device.close();
2878
2879 // Try to remove this device from mDevices.
2880 if (auto it = mDevices.find(device.id); it != mDevices.end()) {
2881 mClosingDevices.push_back(std::move(mDevices[device.id]));
2882 mDevices.erase(device.id);
2883 return;
2884 }
2885
2886 // Try to remove this device from mOpeningDevices.
2887 if (auto it = std::find_if(mOpeningDevices.begin(), mOpeningDevices.end(),
2888 [&device](auto& d) { return d->id == device.id; });
2889 it != mOpeningDevices.end()) {
2890 mOpeningDevices.erase(it);
2891 return;
2892 }
2893
2894 LOG_ALWAYS_FATAL("%s: Device with id %d was not found!", __func__, device.id);
2895 }
2896
readNotifyLocked()2897 base::Result<void> EventHub::readNotifyLocked() {
2898 static constexpr auto EVENT_SIZE = static_cast<ssize_t>(sizeof(inotify_event));
2899 uint8_t eventBuffer[512];
2900 ssize_t sizeRead;
2901
2902 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
2903 do {
2904 sizeRead = read(mINotifyFd, eventBuffer, sizeof(eventBuffer));
2905 } while (sizeRead < 0 && errno == EINTR);
2906
2907 if (sizeRead < EVENT_SIZE) return Errorf("could not get event, %s", strerror(errno));
2908
2909 for (ssize_t eventPos = 0; sizeRead >= EVENT_SIZE;) {
2910 const inotify_event* event;
2911 event = (const inotify_event*)(eventBuffer + eventPos);
2912 if (event->len == 0) continue;
2913
2914 handleNotifyEventLocked(*event);
2915
2916 const ssize_t eventSize = EVENT_SIZE + event->len;
2917 sizeRead -= eventSize;
2918 eventPos += eventSize;
2919 }
2920 return {};
2921 }
2922
handleNotifyEventLocked(const inotify_event & event)2923 void EventHub::handleNotifyEventLocked(const inotify_event& event) {
2924 if (event.wd == mDeviceInputWd) {
2925 std::string filename = std::string(DEVICE_INPUT_PATH) + "/" + event.name;
2926 if (event.mask & IN_CREATE) {
2927 openDeviceLocked(filename);
2928 } else {
2929 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
2930 closeDeviceByPathLocked(filename);
2931 }
2932 } else if (event.wd == mDeviceWd) {
2933 if (isV4lTouchNode(event.name)) {
2934 std::string filename = std::string(DEVICE_PATH) + "/" + event.name;
2935 if (event.mask & IN_CREATE) {
2936 openVideoDeviceLocked(filename);
2937 } else {
2938 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
2939 closeVideoDeviceByPathLocked(filename);
2940 }
2941 } else if (strcmp(event.name, "input") == 0 && event.mask & IN_CREATE) {
2942 addDeviceInputInotify();
2943 }
2944 } else {
2945 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event.wd);
2946 }
2947 }
2948
scanDirLocked(const std::string & dirname)2949 status_t EventHub::scanDirLocked(const std::string& dirname) {
2950 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2951 openDeviceLocked(entry.path());
2952 }
2953 return 0;
2954 }
2955
2956 /**
2957 * Look for all dirname/v4l-touch* devices, and open them.
2958 */
scanVideoDirLocked(const std::string & dirname)2959 status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
2960 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2961 if (isV4lTouchNode(entry.path())) {
2962 ALOGI("Found touch video device %s", entry.path().c_str());
2963 openVideoDeviceLocked(entry.path());
2964 }
2965 }
2966 return OK;
2967 }
2968
requestReopenDevices()2969 void EventHub::requestReopenDevices() {
2970 ALOGV("requestReopenDevices() called");
2971
2972 std::scoped_lock _l(mLock);
2973 mNeedToReopenDevices = true;
2974 }
2975
setKernelWakeEnabled(int32_t deviceId,bool enabled)2976 bool EventHub::setKernelWakeEnabled(int32_t deviceId, bool enabled) {
2977 std::scoped_lock _l(mLock);
2978 std::string enabledStr = enabled ? "enabled" : "disabled";
2979 Device* device = getDeviceLocked(deviceId);
2980 if (device == nullptr) {
2981 ALOGE("Device Id %d does not exist for setting power wakeup", deviceId);
2982 return false;
2983 }
2984 if (device->associatedDevice == nullptr) {
2985 return false;
2986 }
2987 std::filesystem::path currentPath = device->associatedDevice->sysfsRootPath;
2988 while (!currentPath.empty() && currentPath != "/") {
2989 std::string nodePath = currentPath / "power/wakeup";
2990 if (std::filesystem::exists(nodePath)) {
2991 if (base::WriteStringToFile(enabledStr, nodePath)) {
2992 return true;
2993
2994 }
2995 // No need to continue searching in parent directories as power/wakeup nodes
2996 // higher up may control other subdevices.
2997 ALOGW("Failed to set power/wakeup node at %s", nodePath.c_str());
2998 return false;
2999 }
3000 currentPath = currentPath.parent_path();
3001 }
3002 return false;
3003 }
3004
dump(std::string & dump) const3005 void EventHub::dump(std::string& dump) const {
3006 dump += "Event Hub State:\n";
3007
3008 { // acquire lock
3009 std::scoped_lock _l(mLock);
3010
3011 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
3012
3013 dump += INDENT "Devices:\n";
3014
3015 for (const auto& [id, device] : mDevices) {
3016 if (mBuiltInKeyboardId == device->id) {
3017 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
3018 device->id, device->identifier.name.c_str());
3019 } else {
3020 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
3021 device->identifier.name.c_str());
3022 }
3023 dump += StringPrintf(INDENT3 "Classes: %s\n", device->classes.string().c_str());
3024 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
3025 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
3026 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
3027 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
3028 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
3029 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
3030 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
3031 "product=0x%04x, version=0x%04x, bluetoothAddress=%s\n",
3032 device->identifier.bus, device->identifier.vendor,
3033 device->identifier.product, device->identifier.version,
3034 toString(device->identifier.bluetoothAddress).c_str());
3035 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
3036 device->keyMap.keyLayoutFile.c_str());
3037 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
3038 device->keyMap.keyCharacterMapFile.c_str());
3039 if (device->associatedDevice && device->associatedDevice->layoutInfo) {
3040 dump += StringPrintf(INDENT3 "LanguageTag: %s\n",
3041 device->associatedDevice->layoutInfo->languageTag.c_str());
3042 dump += StringPrintf(INDENT3 "LayoutType: %s\n",
3043 device->associatedDevice->layoutInfo->layoutType.c_str());
3044 }
3045 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
3046 device->configurationFile.c_str());
3047 dump += StringPrintf(INDENT3 "VideoDevice: %s\n",
3048 device->videoDevice ? device->videoDevice->dump().c_str()
3049 : "<none>");
3050 dump += StringPrintf(INDENT3 "SysfsDevicePath: %s\n",
3051 device->associatedDevice
3052 ? device->associatedDevice->sysfsRootPath.c_str()
3053 : "<none>");
3054 if (device->keyBitmask.any(0, KEY_MAX + 1)) {
3055 const auto pressedKeys = device->keyState.dumpSetIndices(", ", [](int i) {
3056 return InputEventLookup::getLinuxEvdevLabel(EV_KEY, i, 1).code;
3057 });
3058 dump += StringPrintf(INDENT3 "KeyState (pressed): %s\n", pressedKeys.c_str());
3059 }
3060 if (device->swBitmask.any(0, SW_MAX + 1)) {
3061 const auto pressedSwitches = device->swState.dumpSetIndices(", ", [](int i) {
3062 return InputEventLookup::getLinuxEvdevLabel(EV_SW, i, 1).code;
3063 });
3064 dump += StringPrintf(INDENT3 "SwState (pressed): %s\n", pressedSwitches.c_str());
3065 }
3066 if (!device->absState.empty()) {
3067 std::string axisValues;
3068 for (const auto& [axis, state] : device->absState) {
3069 if (!axisValues.empty()) {
3070 axisValues += ", ";
3071 }
3072 axisValues += StringPrintf("%s=%d",
3073 InputEventLookup::getLinuxEvdevLabel(EV_ABS, axis, 0)
3074 .code.c_str(),
3075 state.value);
3076 }
3077 dump += INDENT3 "AbsState: " + axisValues + "\n";
3078 }
3079 }
3080
3081 dump += INDENT "Unattached video devices:\n";
3082 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
3083 dump += INDENT2 + videoDevice->dump() + "\n";
3084 }
3085 if (mUnattachedVideoDevices.empty()) {
3086 dump += INDENT2 "<none>\n";
3087 }
3088 } // release lock
3089 }
3090
monitor() const3091 void EventHub::monitor() const {
3092 // Acquire and release the lock to ensure that the event hub has not deadlocked.
3093 std::unique_lock<std::mutex> lock(mLock);
3094 }
3095
3096 } // namespace android
3097