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