blob: 956746d7d277065570a970c0a92e79e75faaff47 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2005 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070017#include <assert.h>
18#include <dirent.h>
19#include <errno.h>
20#include <fcntl.h>
21#include <inttypes.h>
22#include <memory.h>
23#include <stdint.h>
24#include <stdio.h>
25#include <stdlib.h>
26#include <string.h>
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +010027#include <sys/capability.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070028#include <sys/epoll.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070029#include <sys/inotify.h>
30#include <sys/ioctl.h>
Kim Low03ea0352020-11-06 12:45:07 -080031#include <sys/stat.h>
32#include <sys/sysmacros.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070033#include <unistd.h>
34
Michael Wrightd02c5b62014-02-10 15:10:22 -080035#define LOG_TAG "EventHub"
36
37// #define LOG_NDEBUG 0
Kim Low03ea0352020-11-06 12:45:07 -080038#include <android-base/file.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080039#include <android-base/stringprintf.h>
Chris Yed3fef462021-03-07 17:10:08 -080040#include <android-base/strings.h>
Philip Quinn39b81682019-01-09 22:20:39 -080041#include <cutils/properties.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080042#include <ftl/enum.h>
Chris Ye8594e192020-07-14 10:34:06 -070043#include <input/KeyCharacterMap.h>
44#include <input/KeyLayoutMap.h>
45#include <input/VirtualKeyMap.h>
Dan Albert677d87e2014-06-16 17:31:28 -070046#include <openssl/sha.h>
Chris Yed3fef462021-03-07 17:10:08 -080047#include <statslog.h>
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070048#include <utils/Errors.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080049#include <utils/Log.h>
50#include <utils/Timers.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080051
Chris Ye8594e192020-07-14 10:34:06 -070052#include <filesystem>
Chris Ye3fdbfef2021-01-06 18:45:18 -080053#include <regex>
Prabir Pradhancb42b472022-08-23 16:01:19 +000054#include <utility>
Chris Ye8594e192020-07-14 10:34:06 -070055
56#include "EventHub.h"
Michael Wrightd02c5b62014-02-10 15:10:22 -080057
Michael Wrightd02c5b62014-02-10 15:10:22 -080058#define INDENT " "
59#define INDENT2 " "
60#define INDENT3 " "
61
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080062using android::base::StringPrintf;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +000063using android::hardware::input::InputDeviceCountryCode;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080064
Michael Wrightd02c5b62014-02-10 15:10:22 -080065namespace android {
66
Dominik Laskowski2f01d772022-03-23 16:01:29 -070067using namespace ftl::flag_operators;
68
Usama Arifb27c8e62021-06-03 16:44:09 +010069static const char* DEVICE_INPUT_PATH = "/dev/input";
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080070// v4l2 devices go directly into /dev
Usama Arifb27c8e62021-06-03 16:44:09 +010071static const char* DEVICE_PATH = "/dev";
Michael Wrightd02c5b62014-02-10 15:10:22 -080072
Chris Ye657c2f02021-05-25 16:24:37 -070073static constexpr size_t OBFUSCATED_LENGTH = 8;
74
Chris Ye87143712020-11-10 05:05:58 +000075static constexpr int32_t FF_STRONG_MAGNITUDE_CHANNEL_IDX = 0;
76static constexpr int32_t FF_WEAK_MAGNITUDE_CHANNEL_IDX = 1;
Chris Ye6393a262020-08-04 19:41:36 -070077
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -070078static constexpr size_t EVENT_BUFFER_SIZE = 256;
79
Chris Yee2b1e5c2021-03-10 22:45:12 -080080// Mapping for input battery class node IDs lookup.
81// https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
82static const std::unordered_map<std::string, InputBatteryClass> BATTERY_CLASSES =
83 {{"capacity", InputBatteryClass::CAPACITY},
84 {"capacity_level", InputBatteryClass::CAPACITY_LEVEL},
85 {"status", InputBatteryClass::STATUS}};
86
87// Mapping for input battery class node names lookup.
88// https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
89static const std::unordered_map<InputBatteryClass, std::string> BATTERY_NODES =
90 {{InputBatteryClass::CAPACITY, "capacity"},
91 {InputBatteryClass::CAPACITY_LEVEL, "capacity_level"},
92 {InputBatteryClass::STATUS, "status"}};
93
Kim Low03ea0352020-11-06 12:45:07 -080094// must be kept in sync with definitions in kernel /drivers/power/supply/power_supply_sysfs.c
95static const std::unordered_map<std::string, int32_t> BATTERY_STATUS =
96 {{"Unknown", BATTERY_STATUS_UNKNOWN},
97 {"Charging", BATTERY_STATUS_CHARGING},
98 {"Discharging", BATTERY_STATUS_DISCHARGING},
99 {"Not charging", BATTERY_STATUS_NOT_CHARGING},
100 {"Full", BATTERY_STATUS_FULL}};
101
102// Mapping taken from
103// https://gitlab.freedesktop.org/upower/upower/-/blob/master/src/linux/up-device-supply.c#L484
104static const std::unordered_map<std::string, int32_t> BATTERY_LEVEL = {{"Critical", 5},
105 {"Low", 10},
106 {"Normal", 55},
107 {"High", 70},
108 {"Full", 100},
109 {"Unknown", 50}};
110
Chris Ye3fdbfef2021-01-06 18:45:18 -0800111// Mapping for input led class node names lookup.
112// https://www.kernel.org/doc/html/latest/leds/leds-class.html
113static const std::unordered_map<std::string, InputLightClass> LIGHT_CLASSES =
114 {{"red", InputLightClass::RED},
115 {"green", InputLightClass::GREEN},
116 {"blue", InputLightClass::BLUE},
117 {"global", InputLightClass::GLOBAL},
118 {"brightness", InputLightClass::BRIGHTNESS},
119 {"multi_index", InputLightClass::MULTI_INDEX},
120 {"multi_intensity", InputLightClass::MULTI_INTENSITY},
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000121 {"max_brightness", InputLightClass::MAX_BRIGHTNESS},
122 {"kbd_backlight", InputLightClass::KEYBOARD_BACKLIGHT}};
Chris Ye3fdbfef2021-01-06 18:45:18 -0800123
124// Mapping for input multicolor led class node names.
125// https://www.kernel.org/doc/html/latest/leds/leds-class-multicolor.html
126static const std::unordered_map<InputLightClass, std::string> LIGHT_NODES =
127 {{InputLightClass::BRIGHTNESS, "brightness"},
128 {InputLightClass::MULTI_INDEX, "multi_index"},
129 {InputLightClass::MULTI_INTENSITY, "multi_intensity"}};
130
131// Mapping for light color name and the light color
132const std::unordered_map<std::string, LightColor> LIGHT_COLORS = {{"red", LightColor::RED},
133 {"green", LightColor::GREEN},
134 {"blue", LightColor::BLUE}};
135
Michael Wrightd02c5b62014-02-10 15:10:22 -0800136static inline const char* toString(bool value) {
137 return value ? "true" : "false";
138}
139
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100140static std::string sha1(const std::string& in) {
Dan Albert677d87e2014-06-16 17:31:28 -0700141 SHA_CTX ctx;
142 SHA1_Init(&ctx);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100143 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
Dan Albert677d87e2014-06-16 17:31:28 -0700144 u_char digest[SHA_DIGEST_LENGTH];
145 SHA1_Final(digest, &ctx);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800146
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100147 std::string out;
Dan Albert677d87e2014-06-16 17:31:28 -0700148 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100149 out += StringPrintf("%02x", digest[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800150 }
151 return out;
152}
153
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800154/**
155 * Return true if name matches "v4l-touch*"
156 */
Chris Ye8594e192020-07-14 10:34:06 -0700157static bool isV4lTouchNode(std::string name) {
158 return name.find("v4l-touch") != std::string::npos;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800159}
160
Philip Quinn39b81682019-01-09 22:20:39 -0800161/**
162 * Returns true if V4L devices should be scanned.
163 *
164 * The system property ro.input.video_enabled can be used to control whether
165 * EventHub scans and opens V4L devices. As V4L does not support multiple
166 * clients, EventHub effectively blocks access to these devices when it opens
Siarhei Vishniakou29f88492019-04-05 14:11:43 -0700167 * them.
168 *
169 * Setting this to "false" would prevent any video devices from being discovered and
170 * associated with input devices.
171 *
172 * This property can be used as follows:
173 * 1. To turn off features that are dependent on video device presence.
174 * 2. During testing and development, to allow other clients to read video devices
175 * directly from /dev.
Philip Quinn39b81682019-01-09 22:20:39 -0800176 */
177static bool isV4lScanningEnabled() {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700178 return property_get_bool("ro.input.video_enabled", true /* default_value */);
Philip Quinn39b81682019-01-09 22:20:39 -0800179}
180
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800181static nsecs_t processEventTimestamp(const struct input_event& event) {
182 // Use the time specified in the event instead of the current time
183 // so that downstream code can get more accurate estimates of
184 // event dispatch latency from the time the event is enqueued onto
185 // the evdev client buffer.
186 //
187 // The event's timestamp fortuitously uses the same monotonic clock
188 // time base as the rest of Android. The kernel event device driver
189 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
190 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
191 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
192 // system call that also queries ktime_get_ts().
193
194 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.time.tv_sec) +
195 microseconds_to_nanoseconds(event.time.tv_usec);
196 return inputEventTime;
197}
198
Kim Low03ea0352020-11-06 12:45:07 -0800199/**
Prabir Pradhancb42b472022-08-23 16:01:19 +0000200 * Returns the sysfs root path of the input device.
Kim Low03ea0352020-11-06 12:45:07 -0800201 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800202static std::optional<std::filesystem::path> getSysfsRootPath(const char* devicePath) {
Kim Low03ea0352020-11-06 12:45:07 -0800203 std::error_code errorCode;
204
205 // Stat the device path to get the major and minor number of the character file
206 struct stat statbuf;
207 if (stat(devicePath, &statbuf) == -1) {
208 ALOGE("Could not stat device %s due to error: %s.", devicePath, std::strerror(errno));
Chris Ye3fdbfef2021-01-06 18:45:18 -0800209 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800210 }
211
212 unsigned int major_num = major(statbuf.st_rdev);
213 unsigned int minor_num = minor(statbuf.st_rdev);
214
215 // Realpath "/sys/dev/char/{major}:{minor}" to get the sysfs path to the input event
216 auto sysfsPath = std::filesystem::path("/sys/dev/char/");
217 sysfsPath /= std::to_string(major_num) + ":" + std::to_string(minor_num);
218 sysfsPath = std::filesystem::canonical(sysfsPath, errorCode);
219
220 // Make sure nothing went wrong in call to canonical()
221 if (errorCode) {
222 ALOGW("Could not run filesystem::canonical() due to error %d : %s.", errorCode.value(),
223 errorCode.message().c_str());
Chris Ye3fdbfef2021-01-06 18:45:18 -0800224 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800225 }
226
227 // Continue to go up a directory until we reach a directory named "input"
228 while (sysfsPath != "/" && sysfsPath.filename() != "input") {
229 sysfsPath = sysfsPath.parent_path();
230 }
231
232 // Then go up one more and you will be at the sysfs root of the device
233 sysfsPath = sysfsPath.parent_path();
234
235 // Make sure we didn't reach root path and that directory actually exists
236 if (sysfsPath == "/" || !std::filesystem::exists(sysfsPath, errorCode)) {
237 if (errorCode) {
238 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
239 errorCode.message().c_str());
240 }
241
242 // Not found
Chris Ye3fdbfef2021-01-06 18:45:18 -0800243 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800244 }
245
246 return sysfsPath;
247}
248
249/**
Chris Ye3fdbfef2021-01-06 18:45:18 -0800250 * Returns the list of files under a specified path.
Kim Low03ea0352020-11-06 12:45:07 -0800251 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800252static std::vector<std::filesystem::path> allFilesInPath(const std::filesystem::path& path) {
253 std::vector<std::filesystem::path> nodes;
254 std::error_code errorCode;
255 auto iter = std::filesystem::directory_iterator(path, errorCode);
256 while (!errorCode && iter != std::filesystem::directory_iterator()) {
257 nodes.push_back(iter->path());
258 iter++;
259 }
260 return nodes;
261}
262
263/**
264 * Returns the list of files under a specified directory in a sysfs path.
265 * Example:
266 * findSysfsNodes(sysfsRootPath, SysfsClass::LEDS) will return all led nodes under "leds" directory
267 * in the sysfs path.
268 */
269static std::vector<std::filesystem::path> findSysfsNodes(const std::filesystem::path& sysfsRoot,
270 SysfsClass clazz) {
Dominik Laskowski75788452021-02-09 18:51:25 -0800271 std::string nodeStr = ftl::enum_string(clazz);
Chris Ye3fdbfef2021-01-06 18:45:18 -0800272 std::for_each(nodeStr.begin(), nodeStr.end(),
273 [](char& c) { c = std::tolower(static_cast<unsigned char>(c)); });
274 std::vector<std::filesystem::path> nodes;
275 for (auto path = sysfsRoot; path != "/" && nodes.empty(); path = path.parent_path()) {
276 nodes = allFilesInPath(path / nodeStr);
277 }
278 return nodes;
279}
280
281static std::optional<std::array<LightColor, COLOR_NUM>> getColorIndexArray(
282 std::filesystem::path path) {
283 std::string indexStr;
284 if (!base::ReadFileToString(path, &indexStr)) {
285 return std::nullopt;
286 }
287
288 // Parse the multi color LED index file, refer to kernel docs
289 // leds/leds-class-multicolor.html
290 std::regex indexPattern("(red|green|blue)\\s(red|green|blue)\\s(red|green|blue)[\\n]");
291 std::smatch results;
292 std::array<LightColor, COLOR_NUM> colors;
293 if (!std::regex_match(indexStr, results, indexPattern)) {
294 return std::nullopt;
295 }
296
297 for (size_t i = 1; i < results.size(); i++) {
298 const auto it = LIGHT_COLORS.find(results[i].str());
299 if (it != LIGHT_COLORS.end()) {
300 // intensities.emplace(it->second, 0);
301 colors[i - 1] = it->second;
Kim Low03ea0352020-11-06 12:45:07 -0800302 }
303 }
Chris Ye3fdbfef2021-01-06 18:45:18 -0800304 return colors;
Kim Low03ea0352020-11-06 12:45:07 -0800305}
306
Prabir Pradhancb42b472022-08-23 16:01:19 +0000307/**
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000308 * Read country code information exposed through the sysfs path.
309 */
310static InputDeviceCountryCode readCountryCodeLocked(const std::filesystem::path& sysfsRootPath) {
311 // Check the sysfs root path
312 int hidCountryCode = static_cast<int>(InputDeviceCountryCode::INVALID);
313 std::string str;
314 if (base::ReadFileToString(sysfsRootPath / "country", &str)) {
315 hidCountryCode = std::stoi(str, nullptr, 16);
316 LOG_ALWAYS_FATAL_IF(hidCountryCode > 35 || hidCountryCode < 0,
317 "HID country code should be in range [0, 35]. Found country code "
318 "to be %d",
319 hidCountryCode);
320 }
321
322 return static_cast<InputDeviceCountryCode>(hidCountryCode);
323}
324
325/**
Prabir Pradhancb42b472022-08-23 16:01:19 +0000326 * Read information about batteries exposed through the sysfs path.
327 */
328static std::unordered_map<int32_t /*batteryId*/, RawBatteryInfo> readBatteryConfiguration(
329 const std::filesystem::path& sysfsRootPath) {
330 std::unordered_map<int32_t, RawBatteryInfo> batteryInfos;
331 int32_t nextBatteryId = 0;
332 // Check if device has any battery.
333 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::POWER_SUPPLY);
334 for (const auto& nodePath : paths) {
335 RawBatteryInfo info;
336 info.id = ++nextBatteryId;
337 info.path = nodePath;
338 info.name = nodePath.filename();
339
340 // Scan the path for all the files
341 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
342 const auto& files = allFilesInPath(nodePath);
343 for (const auto& file : files) {
344 const auto it = BATTERY_CLASSES.find(file.filename().string());
345 if (it != BATTERY_CLASSES.end()) {
346 info.flags |= it->second;
347 }
348 }
349 batteryInfos.insert_or_assign(info.id, info);
350 ALOGD("configureBatteryLocked rawBatteryId %d name %s", info.id, info.name.c_str());
351 }
352 return batteryInfos;
353}
354
355/**
356 * Read information about lights exposed through the sysfs path.
357 */
358static std::unordered_map<int32_t /*lightId*/, RawLightInfo> readLightsConfiguration(
359 const std::filesystem::path& sysfsRootPath) {
360 std::unordered_map<int32_t, RawLightInfo> lightInfos;
361 int32_t nextLightId = 0;
362 // Check if device has any lights.
363 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::LEDS);
364 for (const auto& nodePath : paths) {
365 RawLightInfo info;
366 info.id = ++nextLightId;
367 info.path = nodePath;
368 info.name = nodePath.filename();
369 info.maxBrightness = std::nullopt;
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000370
371 // Light name should follow the naming pattern <name>:<color>:<function>
372 // Refer kernel docs /leds/leds-class.html for valid supported LED names.
373 std::regex indexPattern("([a-zA-Z0-9_.:]*:)?([a-zA-Z0-9_.]*):([a-zA-Z0-9_.]*)");
374 std::smatch results;
375
376 if (std::regex_match(info.name, results, indexPattern)) {
377 // regex_match will return full match at index 0 and <name> at index 1. For RawLightInfo
378 // we only care about sections <color> and <function> which will be at index 2 and 3.
379 for (int i = 2; i <= 3; i++) {
380 const auto it = LIGHT_CLASSES.find(results.str(i));
381 if (it != LIGHT_CLASSES.end()) {
382 info.flags |= it->second;
383 }
Prabir Pradhancb42b472022-08-23 16:01:19 +0000384 }
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000385
386 // Set name of the raw light to <function> which represents playerIDs for LEDs that
387 // turn on/off based on the current player ID (Refer to PeripheralController.cpp for
388 // player ID logic)
389 info.name = results.str(3);
Prabir Pradhancb42b472022-08-23 16:01:19 +0000390 }
391 // Scan the path for all the files
392 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
393 const auto& files = allFilesInPath(nodePath);
394 for (const auto& file : files) {
395 const auto it = LIGHT_CLASSES.find(file.filename().string());
396 if (it != LIGHT_CLASSES.end()) {
397 info.flags |= it->second;
398 // If the node has maximum brightness, read it
399 if (it->second == InputLightClass::MAX_BRIGHTNESS) {
400 std::string str;
401 if (base::ReadFileToString(file, &str)) {
402 info.maxBrightness = std::stoi(str);
403 }
404 }
405 }
406 }
407 lightInfos.insert_or_assign(info.id, info);
408 ALOGD("configureLightsLocked rawLightId %d name %s", info.id, info.name.c_str());
409 }
410 return lightInfos;
411}
412
Michael Wrightd02c5b62014-02-10 15:10:22 -0800413// --- Global Functions ---
414
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700415ftl::Flags<InputDeviceClass> getAbsAxisUsage(int32_t axis,
416 ftl::Flags<InputDeviceClass> deviceClasses) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800417 // Touch devices get dibs on touch-related axes.
Chris Ye1b0c7342020-07-28 21:57:03 -0700418 if (deviceClasses.test(InputDeviceClass::TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800419 switch (axis) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700420 case ABS_X:
421 case ABS_Y:
422 case ABS_PRESSURE:
423 case ABS_TOOL_WIDTH:
424 case ABS_DISTANCE:
425 case ABS_TILT_X:
426 case ABS_TILT_Y:
427 case ABS_MT_SLOT:
428 case ABS_MT_TOUCH_MAJOR:
429 case ABS_MT_TOUCH_MINOR:
430 case ABS_MT_WIDTH_MAJOR:
431 case ABS_MT_WIDTH_MINOR:
432 case ABS_MT_ORIENTATION:
433 case ABS_MT_POSITION_X:
434 case ABS_MT_POSITION_Y:
435 case ABS_MT_TOOL_TYPE:
436 case ABS_MT_BLOB_ID:
437 case ABS_MT_TRACKING_ID:
438 case ABS_MT_PRESSURE:
439 case ABS_MT_DISTANCE:
Chris Ye1b0c7342020-07-28 21:57:03 -0700440 return InputDeviceClass::TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800441 }
442 }
443
Chris Yef59a2f42020-10-16 12:55:26 -0700444 if (deviceClasses.test(InputDeviceClass::SENSOR)) {
445 switch (axis) {
446 case ABS_X:
447 case ABS_Y:
448 case ABS_Z:
449 case ABS_RX:
450 case ABS_RY:
451 case ABS_RZ:
452 return InputDeviceClass::SENSOR;
453 }
454 }
455
Michael Wright842500e2015-03-13 17:32:02 -0700456 // External stylus gets the pressure axis
Chris Ye1b0c7342020-07-28 21:57:03 -0700457 if (deviceClasses.test(InputDeviceClass::EXTERNAL_STYLUS)) {
Michael Wright842500e2015-03-13 17:32:02 -0700458 if (axis == ABS_PRESSURE) {
Chris Ye1b0c7342020-07-28 21:57:03 -0700459 return InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -0700460 }
461 }
462
Michael Wrightd02c5b62014-02-10 15:10:22 -0800463 // Joystick devices get the rest.
Chris Ye1b0c7342020-07-28 21:57:03 -0700464 return deviceClasses & InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800465}
466
467// --- EventHub::Device ---
468
Prabir Pradhancb42b472022-08-23 16:01:19 +0000469EventHub::Device::Device(int fd, int32_t id, std::string path, InputDeviceIdentifier identifier,
470 std::shared_ptr<const AssociatedDevice> assocDev)
Chris Ye989bb932020-07-04 16:18:59 -0700471 : fd(fd),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700472 id(id),
Prabir Pradhancb42b472022-08-23 16:01:19 +0000473 path(std::move(path)),
474 identifier(std::move(identifier)),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700475 classes(0),
476 configuration(nullptr),
477 virtualKeyMap(nullptr),
478 ffEffectPlaying(false),
479 ffEffectId(-1),
Prabir Pradhancb42b472022-08-23 16:01:19 +0000480 associatedDevice(std::move(assocDev)),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700481 controllerNumber(0),
482 enabled(true),
Chris Ye66fbac32020-07-06 20:36:43 -0700483 isVirtual(fd < 0) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800484
485EventHub::Device::~Device() {
486 close();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800487}
488
489void EventHub::Device::close() {
490 if (fd >= 0) {
491 ::close(fd);
492 fd = -1;
493 }
494}
495
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700496status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100497 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700498 if (fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100499 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700500 return -errno;
501 }
502 enabled = true;
503 return OK;
504}
505
506status_t EventHub::Device::disable() {
507 close();
508 enabled = false;
509 return OK;
510}
511
Chris Ye989bb932020-07-04 16:18:59 -0700512bool EventHub::Device::hasValidFd() const {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700513 return !isVirtual && enabled;
514}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800515
Chris Ye3a1e4462020-08-12 10:13:15 -0700516const std::shared_ptr<KeyCharacterMap> EventHub::Device::getKeyCharacterMap() const {
Chris Ye989bb932020-07-04 16:18:59 -0700517 return keyMap.keyCharacterMap;
518}
519
520template <std::size_t N>
521status_t EventHub::Device::readDeviceBitMask(unsigned long ioctlCode, BitArray<N>& bitArray) {
522 if (!hasValidFd()) {
523 return BAD_VALUE;
524 }
525 if ((_IOC_SIZE(ioctlCode) == 0)) {
526 ioctlCode |= _IOC(0, 0, 0, bitArray.bytes());
527 }
528
529 typename BitArray<N>::Buffer buffer;
530 status_t ret = ioctl(fd, ioctlCode, buffer.data());
531 bitArray.loadFromBuffer(buffer);
532 return ret;
533}
534
535void EventHub::Device::configureFd() {
536 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
537 if (classes.test(InputDeviceClass::KEYBOARD)) {
538 // Disable kernel key repeat since we handle it ourselves
539 unsigned int repeatRate[] = {0, 0};
540 if (ioctl(fd, EVIOCSREP, repeatRate)) {
541 ALOGW("Unable to disable kernel key repeat for %s: %s", path.c_str(), strerror(errno));
542 }
543 }
544
545 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
546 // associated with input events. This is important because the input system
547 // uses the timestamps extensively and assumes they were recorded using the monotonic
548 // clock.
549 int clockId = CLOCK_MONOTONIC;
Chris Yef59a2f42020-10-16 12:55:26 -0700550 if (classes.test(InputDeviceClass::SENSOR)) {
551 // Each new sensor event should use the same time base as
552 // SystemClock.elapsedRealtimeNanos().
553 clockId = CLOCK_BOOTTIME;
554 }
Chris Ye989bb932020-07-04 16:18:59 -0700555 bool usingClockIoctl = !ioctl(fd, EVIOCSCLOCKID, &clockId);
556 ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
557}
558
559bool EventHub::Device::hasKeycodeLocked(int keycode) const {
560 if (!keyMap.haveKeyLayout()) {
561 return false;
562 }
563
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700564 std::vector<int32_t> scanCodes = keyMap.keyLayoutMap->findScanCodesForKey(keycode);
Chris Ye989bb932020-07-04 16:18:59 -0700565 const size_t N = scanCodes.size();
566 for (size_t i = 0; i < N && i <= KEY_MAX; i++) {
567 int32_t sc = scanCodes[i];
568 if (sc >= 0 && sc <= KEY_MAX && keyBitmask.test(sc)) {
569 return true;
570 }
571 }
572
573 return false;
574}
575
576void EventHub::Device::loadConfigurationLocked() {
577 configurationFile =
578 getInputDeviceConfigurationFilePathByDeviceIdentifier(identifier,
579 InputDeviceConfigurationFileType::
580 CONFIGURATION);
581 if (configurationFile.empty()) {
582 ALOGD("No input device configuration file found for device '%s'.", identifier.name.c_str());
583 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500584 android::base::Result<std::unique_ptr<PropertyMap>> propertyMap =
585 PropertyMap::load(configurationFile.c_str());
586 if (!propertyMap.ok()) {
Chris Ye989bb932020-07-04 16:18:59 -0700587 ALOGE("Error loading input device configuration file for device '%s'. "
588 "Using default configuration.",
589 identifier.name.c_str());
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500590 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500591 configuration = std::move(*propertyMap);
Chris Ye989bb932020-07-04 16:18:59 -0700592 }
593 }
594}
595
596bool EventHub::Device::loadVirtualKeyMapLocked() {
597 // The virtual key map is supplied by the kernel as a system board property file.
598 std::string propPath = "/sys/board_properties/virtualkeys.";
599 propPath += identifier.getCanonicalName();
600 if (access(propPath.c_str(), R_OK)) {
601 return false;
602 }
603 virtualKeyMap = VirtualKeyMap::load(propPath);
604 return virtualKeyMap != nullptr;
605}
606
607status_t EventHub::Device::loadKeyMapLocked() {
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500608 return keyMap.load(identifier, configuration.get());
Chris Ye989bb932020-07-04 16:18:59 -0700609}
610
611bool EventHub::Device::isExternalDeviceLocked() {
612 if (configuration) {
613 bool value;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700614 if (configuration->tryGetProperty("device.internal", value)) {
Chris Ye989bb932020-07-04 16:18:59 -0700615 return !value;
616 }
617 }
618 return identifier.bus == BUS_USB || identifier.bus == BUS_BLUETOOTH;
619}
620
621bool EventHub::Device::deviceHasMicLocked() {
622 if (configuration) {
623 bool value;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700624 if (configuration->tryGetProperty("audio.mic", value)) {
Chris Ye989bb932020-07-04 16:18:59 -0700625 return value;
626 }
627 }
628 return false;
629}
630
631void EventHub::Device::setLedStateLocked(int32_t led, bool on) {
632 int32_t sc;
633 if (hasValidFd() && mapLed(led, &sc) != NAME_NOT_FOUND) {
634 struct input_event ev;
635 ev.time.tv_sec = 0;
636 ev.time.tv_usec = 0;
637 ev.type = EV_LED;
638 ev.code = sc;
639 ev.value = on ? 1 : 0;
640
641 ssize_t nWrite;
642 do {
643 nWrite = write(fd, &ev, sizeof(struct input_event));
644 } while (nWrite == -1 && errno == EINTR);
645 }
646}
647
648void EventHub::Device::setLedForControllerLocked() {
649 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
650 setLedStateLocked(ALED_CONTROLLER_1 + i, controllerNumber == i + 1);
651 }
652}
653
654status_t EventHub::Device::mapLed(int32_t led, int32_t* outScanCode) const {
655 if (!keyMap.haveKeyLayout()) {
656 return NAME_NOT_FOUND;
657 }
658
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700659 std::optional<int32_t> scanCode = keyMap.keyLayoutMap->findScanCodeForLed(led);
660 if (scanCode.has_value()) {
661 if (*scanCode >= 0 && *scanCode <= LED_MAX && ledBitmask.test(*scanCode)) {
662 *outScanCode = *scanCode;
Chris Ye989bb932020-07-04 16:18:59 -0700663 return NO_ERROR;
664 }
665 }
666 return NAME_NOT_FOUND;
667}
668
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100669/**
670 * Get the capabilities for the current process.
671 * Crashes the system if unable to create / check / destroy the capabilities object.
672 */
673class Capabilities final {
674public:
675 explicit Capabilities() {
676 mCaps = cap_get_proc();
677 LOG_ALWAYS_FATAL_IF(mCaps == nullptr, "Could not get capabilities of the current process");
678 }
679
680 /**
681 * Check whether the current process has a specific capability
682 * in the set of effective capabilities.
683 * Return CAP_SET if the process has the requested capability
684 * Return CAP_CLEAR otherwise.
685 */
686 cap_flag_value_t checkEffectiveCapability(cap_value_t capability) {
687 cap_flag_value_t value;
688 const int result = cap_get_flag(mCaps, capability, CAP_EFFECTIVE, &value);
689 LOG_ALWAYS_FATAL_IF(result == -1, "Could not obtain the requested capability");
690 return value;
691 }
692
693 ~Capabilities() {
694 const int result = cap_free(mCaps);
695 LOG_ALWAYS_FATAL_IF(result == -1, "Could not release the capabilities structure");
696 }
697
698private:
699 cap_t mCaps;
700};
701
702static void ensureProcessCanBlockSuspend() {
703 Capabilities capabilities;
704 const bool canBlockSuspend =
705 capabilities.checkEffectiveCapability(CAP_BLOCK_SUSPEND) == CAP_SET;
706 LOG_ALWAYS_FATAL_IF(!canBlockSuspend,
707 "Input must be able to block suspend to properly process events");
708}
709
Michael Wrightd02c5b62014-02-10 15:10:22 -0800710// --- EventHub ---
711
Michael Wrightd02c5b62014-02-10 15:10:22 -0800712const int EventHub::EPOLL_MAX_EVENTS;
713
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700714EventHub::EventHub(void)
715 : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
716 mNextDeviceId(1),
717 mControllerNumbers(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800718 mNeedToSendFinishedDeviceScan(false),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700719 mNeedToReopenDevices(false),
720 mNeedToScanDevices(true),
721 mPendingEventCount(0),
722 mPendingEventIndex(0),
723 mPendingINotify(false) {
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100724 ensureProcessCanBlockSuspend();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800725
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800726 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800727 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800728
Michael Wright8e9a8562022-02-09 13:44:29 +0000729 mINotifyFd = inotify_init1(IN_CLOEXEC);
Prabir Pradhan952e65b2022-06-23 17:49:55 +0000730 LOG_ALWAYS_FATAL_IF(mINotifyFd < 0, "Could not create inotify instance: %s", strerror(errno));
Usama Arifb27c8e62021-06-03 16:44:09 +0100731
732 std::error_code errorCode;
733 bool isDeviceInotifyAdded = false;
734 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
735 addDeviceInputInotify();
Philip Quinn39b81682019-01-09 22:20:39 -0800736 } else {
Usama Arifb27c8e62021-06-03 16:44:09 +0100737 addDeviceInotify();
738 isDeviceInotifyAdded = true;
739 if (errorCode) {
740 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
741 errorCode.message().c_str());
742 }
743 }
744
745 if (isV4lScanningEnabled() && !isDeviceInotifyAdded) {
746 addDeviceInotify();
747 } else {
Philip Quinn39b81682019-01-09 22:20:39 -0800748 ALOGI("Video device scanning disabled");
749 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800750
Siarhei Vishniakou2d0e9482019-09-24 12:52:47 +0100751 struct epoll_event eventItem = {};
752 eventItem.events = EPOLLIN | EPOLLWAKEUP;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700753 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800754 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800755 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
756
757 int wakeFds[2];
Michael Wright8e9a8562022-02-09 13:44:29 +0000758 result = pipe2(wakeFds, O_CLOEXEC);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800759 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
760
761 mWakeReadPipeFd = wakeFds[0];
762 mWakeWritePipeFd = wakeFds[1];
763
764 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
765 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700766 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800767
768 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
769 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700770 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800771
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700772 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800773 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
774 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700775 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800776}
777
778EventHub::~EventHub(void) {
779 closeAllDevicesLocked();
780
Michael Wrightd02c5b62014-02-10 15:10:22 -0800781 ::close(mEpollFd);
782 ::close(mINotifyFd);
783 ::close(mWakeReadPipeFd);
784 ::close(mWakeWritePipeFd);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800785}
786
Usama Arifb27c8e62021-06-03 16:44:09 +0100787/**
788 * On devices that don't have any input devices (like some development boards), the /dev/input
789 * directory will be absent. However, the user may still plug in an input device at a later time.
790 * Add watch for contents of /dev/input only when /dev/input appears.
791 */
792void EventHub::addDeviceInputInotify() {
793 mDeviceInputWd = inotify_add_watch(mINotifyFd, DEVICE_INPUT_PATH, IN_DELETE | IN_CREATE);
794 LOG_ALWAYS_FATAL_IF(mDeviceInputWd < 0, "Could not register INotify for %s: %s",
795 DEVICE_INPUT_PATH, strerror(errno));
796}
797
798void EventHub::addDeviceInotify() {
799 mDeviceWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
800 LOG_ALWAYS_FATAL_IF(mDeviceWd < 0, "Could not register INotify for %s: %s", DEVICE_PATH,
801 strerror(errno));
802}
803
Michael Wrightd02c5b62014-02-10 15:10:22 -0800804InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000805 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800806 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700807 return device != nullptr ? device->identifier : InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800808}
809
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700810ftl::Flags<InputDeviceClass> EventHub::getDeviceClasses(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000811 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800812 Device* device = getDeviceLocked(deviceId);
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700813 return device != nullptr ? device->classes : ftl::Flags<InputDeviceClass>(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800814}
815
816int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000817 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800818 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700819 return device != nullptr ? device->controllerNumber : 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800820}
821
822void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
Chris Ye87143712020-11-10 05:05:58 +0000823 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800824 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700825 if (device != nullptr && device->configuration) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800826 *outConfiguration = *device->configuration;
827 } else {
828 outConfiguration->clear();
829 }
830}
831
832status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700833 RawAbsoluteAxisInfo* outAxisInfo) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800834 outAxisInfo->clear();
835
836 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000837 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800838
839 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700840 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800841 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700842 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
843 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
844 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800845 return -errno;
846 }
847
848 if (info.minimum != info.maximum) {
849 outAxisInfo->valid = true;
850 outAxisInfo->minValue = info.minimum;
851 outAxisInfo->maxValue = info.maximum;
852 outAxisInfo->flat = info.flat;
853 outAxisInfo->fuzz = info.fuzz;
854 outAxisInfo->resolution = info.resolution;
855 }
856 return OK;
857 }
858 }
859 return -1;
860}
861
862bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
863 if (axis >= 0 && axis <= REL_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000864 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800865 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700866 return device != nullptr ? device->relBitmask.test(axis) : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800867 }
868 return false;
869}
870
871bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
Chris Ye87143712020-11-10 05:05:58 +0000872 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800873
Chris Ye989bb932020-07-04 16:18:59 -0700874 Device* device = getDeviceLocked(deviceId);
875 return property >= 0 && property <= INPUT_PROP_MAX && device != nullptr
876 ? device->propBitmask.test(property)
877 : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800878}
879
Chris Yef59a2f42020-10-16 12:55:26 -0700880bool EventHub::hasMscEvent(int32_t deviceId, int mscEvent) const {
881 std::scoped_lock _l(mLock);
882
883 Device* device = getDeviceLocked(deviceId);
884 return mscEvent >= 0 && mscEvent <= MSC_MAX && device != nullptr
885 ? device->mscBitmask.test(mscEvent)
886 : false;
887}
888
Michael Wrightd02c5b62014-02-10 15:10:22 -0800889int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
890 if (scanCode >= 0 && scanCode <= KEY_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000891 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800892
893 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700894 if (device != nullptr && device->hasValidFd() && device->keyBitmask.test(scanCode)) {
895 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
896 return device->keyState.test(scanCode) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800897 }
898 }
899 }
900 return AKEY_STATE_UNKNOWN;
901}
902
903int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
Chris Ye87143712020-11-10 05:05:58 +0000904 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800905
906 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700907 if (device != nullptr && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700908 std::vector<int32_t> scanCodes = device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800909 if (scanCodes.size() != 0) {
Chris Ye66fbac32020-07-06 20:36:43 -0700910 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800911 for (size_t i = 0; i < scanCodes.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800912 int32_t sc = scanCodes[i];
Chris Ye66fbac32020-07-06 20:36:43 -0700913 if (sc >= 0 && sc <= KEY_MAX && device->keyState.test(sc)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800914 return AKEY_STATE_DOWN;
915 }
916 }
917 return AKEY_STATE_UP;
918 }
919 }
920 }
921 return AKEY_STATE_UNKNOWN;
922}
923
Philip Junker4af3b3d2021-12-14 10:36:55 +0100924int32_t EventHub::getKeyCodeForKeyLocation(int32_t deviceId, int32_t locationKeyCode) const {
925 std::scoped_lock _l(mLock);
926
927 Device* device = getDeviceLocked(deviceId);
928 if (device == nullptr || !device->hasValidFd() || device->keyMap.keyCharacterMap == nullptr ||
929 device->keyMap.keyLayoutMap == nullptr) {
930 return AKEYCODE_UNKNOWN;
931 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700932 std::vector<int32_t> scanCodes =
933 device->keyMap.keyLayoutMap->findScanCodesForKey(locationKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +0100934 if (scanCodes.empty()) {
935 ALOGW("Failed to get key code for key location: no scan code maps to key code %d for input"
936 "device %d",
937 locationKeyCode, deviceId);
938 return AKEYCODE_UNKNOWN;
939 }
940 if (scanCodes.size() > 1) {
941 ALOGW("Multiple scan codes map to the same key code %d, returning only the first match",
942 locationKeyCode);
943 }
944 int32_t outKeyCode;
945 status_t mapKeyRes =
946 device->getKeyCharacterMap()->mapKey(scanCodes[0], 0 /*usageCode*/, &outKeyCode);
947 switch (mapKeyRes) {
948 case OK:
949 return outKeyCode;
950 case NAME_NOT_FOUND:
951 // key character map doesn't re-map this scanCode, hence the keyCode remains the same
952 return locationKeyCode;
953 default:
954 ALOGW("Failed to get key code for key location: Key character map returned error %s",
955 statusToString(mapKeyRes).c_str());
956 return AKEYCODE_UNKNOWN;
957 }
958}
959
Michael Wrightd02c5b62014-02-10 15:10:22 -0800960int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
961 if (sw >= 0 && sw <= SW_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000962 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800963
964 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700965 if (device != nullptr && device->hasValidFd() && device->swBitmask.test(sw)) {
966 if (device->readDeviceBitMask(EVIOCGSW(0), device->swState) >= 0) {
967 return device->swState.test(sw) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800968 }
969 }
970 }
971 return AKEY_STATE_UNKNOWN;
972}
973
974status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
975 *outValue = 0;
976
977 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000978 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800979
980 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700981 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800982 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700983 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
984 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
985 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800986 return -errno;
987 }
988
989 *outValue = info.value;
990 return OK;
991 }
992 }
993 return -1;
994}
995
Siarhei Vishniakou74007942022-06-13 13:57:47 -0700996bool EventHub::markSupportedKeyCodes(int32_t deviceId, const std::vector<int32_t>& keyCodes,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700997 uint8_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +0000998 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800999
1000 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001001 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001002 for (size_t codeIndex = 0; codeIndex < keyCodes.size(); codeIndex++) {
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001003 std::vector<int32_t> scanCodes =
1004 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCodes[codeIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001005
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001006 // check the possible scan codes identified by the layout map against the
1007 // map of codes actually emitted by the driver
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001008 for (const int32_t scanCode : scanCodes) {
1009 if (device->keyBitmask.test(scanCode)) {
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001010 outFlags[codeIndex] = 1;
1011 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001012 }
1013 }
1014 }
1015 return true;
1016 }
1017 return false;
1018}
1019
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001020status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
1021 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +00001022 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001023 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001024 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001025
Chris Ye66fbac32020-07-06 20:36:43 -07001026 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001027 // Check the key character map first.
Chris Ye3a1e4462020-08-12 10:13:15 -07001028 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
1029 if (kcm) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001030 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
1031 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001032 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001033 }
1034 }
1035
1036 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001037 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -08001038 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001039 status = NO_ERROR;
1040 }
1041 }
1042
1043 if (status == NO_ERROR) {
Chris Ye3a1e4462020-08-12 10:13:15 -07001044 if (kcm) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001045 kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState);
1046 } else {
1047 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001048 }
1049 }
1050 }
1051
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001052 if (status != NO_ERROR) {
1053 *outKeycode = 0;
1054 *outFlags = 0;
1055 *outMetaState = metaState;
1056 }
1057
1058 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001059}
1060
1061status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
Chris Ye87143712020-11-10 05:05:58 +00001062 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001063 Device* device = getDeviceLocked(deviceId);
1064
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001065 if (device == nullptr || !device->keyMap.haveKeyLayout()) {
1066 return NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001067 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001068 std::optional<AxisInfo> info = device->keyMap.keyLayoutMap->mapAxis(scanCode);
1069 if (!info.has_value()) {
1070 return NAME_NOT_FOUND;
1071 }
1072 *outAxisInfo = *info;
1073 return NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001074}
1075
Chris Yef59a2f42020-10-16 12:55:26 -07001076base::Result<std::pair<InputDeviceSensorType, int32_t>> EventHub::mapSensor(int32_t deviceId,
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001077 int32_t absCode) const {
Chris Yef59a2f42020-10-16 12:55:26 -07001078 std::scoped_lock _l(mLock);
1079 Device* device = getDeviceLocked(deviceId);
1080
1081 if (device != nullptr && device->keyMap.haveKeyLayout()) {
1082 return device->keyMap.keyLayoutMap->mapSensor(absCode);
1083 }
1084 return Errorf("Device not found or device has no key layout.");
1085}
1086
Chris Yee2b1e5c2021-03-10 22:45:12 -08001087// Gets the battery info map from battery ID to RawBatteryInfo of the miscellaneous device
1088// associated with the device ID. Returns an empty map if no miscellaneous device found.
1089const std::unordered_map<int32_t, RawBatteryInfo>& EventHub::getBatteryInfoLocked(
1090 int32_t deviceId) const {
1091 static const std::unordered_map<int32_t, RawBatteryInfo> EMPTY_BATTERY_INFO = {};
1092 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001093 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001094 return EMPTY_BATTERY_INFO;
1095 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001096 return device->associatedDevice->batteryInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001097}
1098
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001099std::vector<int32_t> EventHub::getRawBatteryIds(int32_t deviceId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001100 std::scoped_lock _l(mLock);
1101 std::vector<int32_t> batteryIds;
1102
Prabir Pradhan51894782022-08-23 16:29:10 +00001103 for (const auto& [id, info] : getBatteryInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001104 batteryIds.push_back(id);
1105 }
1106
1107 return batteryIds;
1108}
1109
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001110std::optional<RawBatteryInfo> EventHub::getRawBatteryInfo(int32_t deviceId,
1111 int32_t batteryId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001112 std::scoped_lock _l(mLock);
1113
1114 const auto infos = getBatteryInfoLocked(deviceId);
1115
1116 auto it = infos.find(batteryId);
1117 if (it != infos.end()) {
1118 return it->second;
1119 }
1120
1121 return std::nullopt;
1122}
1123
1124// Gets the light info map from light ID to RawLightInfo of the miscellaneous device associated
Prabir Pradhan51894782022-08-23 16:29:10 +00001125// with the device ID. Returns an empty map if no miscellaneous device found.
Chris Yee2b1e5c2021-03-10 22:45:12 -08001126const std::unordered_map<int32_t, RawLightInfo>& EventHub::getLightInfoLocked(
1127 int32_t deviceId) const {
1128 static const std::unordered_map<int32_t, RawLightInfo> EMPTY_LIGHT_INFO = {};
1129 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001130 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001131 return EMPTY_LIGHT_INFO;
1132 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001133 return device->associatedDevice->lightInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001134}
1135
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001136std::vector<int32_t> EventHub::getRawLightIds(int32_t deviceId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001137 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001138 std::vector<int32_t> lightIds;
1139
Prabir Pradhan51894782022-08-23 16:29:10 +00001140 for (const auto& [id, info] : getLightInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001141 lightIds.push_back(id);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001142 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001143
Chris Ye3fdbfef2021-01-06 18:45:18 -08001144 return lightIds;
1145}
1146
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001147std::optional<RawLightInfo> EventHub::getRawLightInfo(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001148 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001149
Chris Yee2b1e5c2021-03-10 22:45:12 -08001150 const auto infos = getLightInfoLocked(deviceId);
1151
1152 auto it = infos.find(lightId);
1153 if (it != infos.end()) {
1154 return it->second;
Chris Ye3fdbfef2021-01-06 18:45:18 -08001155 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001156
Chris Ye3fdbfef2021-01-06 18:45:18 -08001157 return std::nullopt;
1158}
1159
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001160std::optional<int32_t> EventHub::getLightBrightness(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001161 std::scoped_lock _l(mLock);
1162
Chris Yee2b1e5c2021-03-10 22:45:12 -08001163 const auto infos = getLightInfoLocked(deviceId);
1164 auto it = infos.find(lightId);
1165 if (it == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001166 return std::nullopt;
1167 }
1168 std::string buffer;
1169 if (!base::ReadFileToString(it->second.path / LIGHT_NODES.at(InputLightClass::BRIGHTNESS),
1170 &buffer)) {
1171 return std::nullopt;
1172 }
1173 return std::stoi(buffer);
1174}
1175
1176std::optional<std::unordered_map<LightColor, int32_t>> EventHub::getLightIntensities(
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001177 int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001178 std::scoped_lock _l(mLock);
1179
Chris Yee2b1e5c2021-03-10 22:45:12 -08001180 const auto infos = getLightInfoLocked(deviceId);
1181 auto lightIt = infos.find(lightId);
1182 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001183 return std::nullopt;
1184 }
1185
1186 auto ret =
1187 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1188
1189 if (!ret.has_value()) {
1190 return std::nullopt;
1191 }
1192 std::array<LightColor, COLOR_NUM> colors = ret.value();
1193
1194 std::string intensityStr;
1195 if (!base::ReadFileToString(lightIt->second.path /
1196 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY),
1197 &intensityStr)) {
1198 return std::nullopt;
1199 }
1200
1201 // Intensity node outputs 3 color values
1202 std::regex intensityPattern("([0-9]+)\\s([0-9]+)\\s([0-9]+)[\\n]");
1203 std::smatch results;
1204
1205 if (!std::regex_match(intensityStr, results, intensityPattern)) {
1206 return std::nullopt;
1207 }
1208 std::unordered_map<LightColor, int32_t> intensities;
1209 for (size_t i = 1; i < results.size(); i++) {
1210 int value = std::stoi(results[i].str());
1211 intensities.emplace(colors[i - 1], value);
1212 }
1213 return intensities;
1214}
1215
1216void EventHub::setLightBrightness(int32_t deviceId, int32_t lightId, int32_t brightness) {
1217 std::scoped_lock _l(mLock);
1218
Chris Yee2b1e5c2021-03-10 22:45:12 -08001219 const auto infos = getLightInfoLocked(deviceId);
1220 auto lightIt = infos.find(lightId);
1221 if (lightIt == infos.end()) {
1222 ALOGE("%s lightId %d not found ", __func__, lightId);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001223 return;
1224 }
1225
1226 if (!base::WriteStringToFile(std::to_string(brightness),
1227 lightIt->second.path /
1228 LIGHT_NODES.at(InputLightClass::BRIGHTNESS))) {
1229 ALOGE("Can not write to file, error: %s", strerror(errno));
1230 }
1231}
1232
1233void EventHub::setLightIntensities(int32_t deviceId, int32_t lightId,
1234 std::unordered_map<LightColor, int32_t> intensities) {
1235 std::scoped_lock _l(mLock);
1236
Chris Yee2b1e5c2021-03-10 22:45:12 -08001237 const auto infos = getLightInfoLocked(deviceId);
1238 auto lightIt = infos.find(lightId);
1239 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001240 ALOGE("Light Id %d does not exist.", lightId);
1241 return;
1242 }
1243
1244 auto ret =
1245 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1246
1247 if (!ret.has_value()) {
1248 return;
1249 }
1250 std::array<LightColor, COLOR_NUM> colors = ret.value();
1251
1252 std::string rgbStr;
1253 for (size_t i = 0; i < COLOR_NUM; i++) {
1254 auto it = intensities.find(colors[i]);
1255 if (it != intensities.end()) {
1256 rgbStr += std::to_string(it->second);
1257 // Insert space between colors
1258 if (i < COLOR_NUM - 1) {
1259 rgbStr += " ";
1260 }
1261 }
1262 }
1263 // Append new line
1264 rgbStr += "\n";
1265
1266 if (!base::WriteStringToFile(rgbStr,
1267 lightIt->second.path /
1268 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY))) {
1269 ALOGE("Can not write to file, error: %s", strerror(errno));
1270 }
1271}
1272
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001273InputDeviceCountryCode EventHub::getCountryCode(int32_t deviceId) const {
1274 std::scoped_lock _l(mLock);
1275 Device* device = getDeviceLocked(deviceId);
1276 if (device == nullptr || !device->associatedDevice) {
1277 return InputDeviceCountryCode::INVALID;
1278 }
1279 return device->associatedDevice->countryCode;
1280}
1281
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001282void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Chris Ye87143712020-11-10 05:05:58 +00001283 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001284
1285 mExcludedDevices = devices;
1286}
1287
1288bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
Chris Ye87143712020-11-10 05:05:58 +00001289 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001290 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001291 if (device != nullptr && scanCode >= 0 && scanCode <= KEY_MAX) {
1292 return device->keyBitmask.test(scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001293 }
1294 return false;
1295}
1296
Arthur Hungcb40a002021-08-03 14:31:01 +00001297bool EventHub::hasKeyCode(int32_t deviceId, int32_t keyCode) const {
1298 std::scoped_lock _l(mLock);
1299 Device* device = getDeviceLocked(deviceId);
1300 if (device != nullptr) {
1301 return device->hasKeycodeLocked(keyCode);
1302 }
1303 return false;
1304}
1305
Michael Wrightd02c5b62014-02-10 15:10:22 -08001306bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
Chris Ye87143712020-11-10 05:05:58 +00001307 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001308 Device* device = getDeviceLocked(deviceId);
1309 int32_t sc;
Chris Ye989bb932020-07-04 16:18:59 -07001310 if (device != nullptr && device->mapLed(led, &sc) == NO_ERROR) {
Chris Ye66fbac32020-07-06 20:36:43 -07001311 return device->ledBitmask.test(sc);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001312 }
1313 return false;
1314}
1315
1316void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
Chris Ye87143712020-11-10 05:05:58 +00001317 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001318 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -07001319 if (device != nullptr && device->hasValidFd()) {
1320 device->setLedStateLocked(led, on);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001321 }
1322}
1323
1324void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001325 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001326 outVirtualKeys.clear();
1327
Chris Ye87143712020-11-10 05:05:58 +00001328 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001329 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001330 if (device != nullptr && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001331 const std::vector<VirtualKeyDefinition> virtualKeys =
1332 device->virtualKeyMap->getVirtualKeys();
1333 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001334 }
1335}
1336
Chris Ye3a1e4462020-08-12 10:13:15 -07001337const std::shared_ptr<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001338 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001339 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001340 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001341 return device->getKeyCharacterMap();
1342 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001343 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001344}
1345
Chris Ye3a1e4462020-08-12 10:13:15 -07001346bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, std::shared_ptr<KeyCharacterMap> map) {
Chris Ye87143712020-11-10 05:05:58 +00001347 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001348 Device* device = getDeviceLocked(deviceId);
Philip Junker90bc9492021-12-10 18:39:42 +01001349 if (device == nullptr || map == nullptr || device->keyMap.keyCharacterMap == nullptr) {
1350 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001351 }
Philip Junker90bc9492021-12-10 18:39:42 +01001352 device->keyMap.keyCharacterMap->combine(*map);
1353 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001354}
1355
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001356static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
1357 std::string rawDescriptor;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001358 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001359 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001360 if (!identifier.uniqueId.empty()) {
1361 rawDescriptor += "uniqueId:";
1362 rawDescriptor += identifier.uniqueId;
Josh Bartel938632f2022-07-19 15:34:22 -05001363 }
1364 if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001365 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001366 }
1367
1368 if (identifier.vendor == 0 && identifier.product == 0) {
1369 // If we don't know the vendor and product id, then the device is probably
1370 // built-in so we need to rely on other information to uniquely identify
1371 // the input device. Usually we try to avoid relying on the device name or
1372 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001373 if (!identifier.name.empty()) {
1374 rawDescriptor += "name:";
1375 rawDescriptor += identifier.name;
1376 } else if (!identifier.location.empty()) {
1377 rawDescriptor += "location:";
1378 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001379 }
1380 }
1381 identifier.descriptor = sha1(rawDescriptor);
1382 return rawDescriptor;
1383}
1384
1385void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
1386 // Compute a device descriptor that uniquely identifies the device.
1387 // The descriptor is assumed to be a stable identifier. Its value should not
1388 // change between reboots, reconnections, firmware updates or new releases
1389 // of Android. In practice we sometimes get devices that cannot be uniquely
1390 // identified. In this case we enforce uniqueness between connected devices.
1391 // Ideally, we also want the descriptor to be short and relatively opaque.
Josh Bartel938632f2022-07-19 15:34:22 -05001392 // Note that we explicitly do not use the path or location for external devices
1393 // as their path or location will change as they are plugged/unplugged or moved
1394 // to different ports. We do fallback to using name and location in the case of
1395 // internal devices which are detected by the vendor and product being 0 in
1396 // generateDescriptor. If two identical descriptors are detected we will fallback
1397 // to using a 'nonce' and incrementing it until the new descriptor no longer has
1398 // a match with any existing descriptors.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001399
1400 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001401 std::string rawDescriptor = generateDescriptor(identifier);
Josh Bartel938632f2022-07-19 15:34:22 -05001402 // Enforce that the generated descriptor is unique.
1403 while (hasDeviceWithDescriptorLocked(identifier.descriptor)) {
1404 identifier.nonce++;
1405 rawDescriptor = generateDescriptor(identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001406 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001407 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001408 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001409}
1410
Prabir Pradhancb42b472022-08-23 16:01:19 +00001411std::shared_ptr<const EventHub::AssociatedDevice> EventHub::obtainAssociatedDeviceLocked(
1412 const std::filesystem::path& devicePath) const {
1413 const std::optional<std::filesystem::path> sysfsRootPathOpt =
1414 getSysfsRootPath(devicePath.c_str());
1415 if (!sysfsRootPathOpt) {
1416 return nullptr;
1417 }
1418
1419 const auto& path = *sysfsRootPathOpt;
Prabir Pradhancb42b472022-08-23 16:01:19 +00001420
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00001421 std::shared_ptr<const AssociatedDevice> associatedDevice = std::make_shared<AssociatedDevice>(
Prabir Pradhancb42b472022-08-23 16:01:19 +00001422 AssociatedDevice{.sysfsRootPath = path,
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001423 .countryCode = readCountryCodeLocked(path),
Prabir Pradhancb42b472022-08-23 16:01:19 +00001424 .batteryInfos = readBatteryConfiguration(path),
1425 .lightInfos = readLightsConfiguration(path)});
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00001426
1427 bool associatedDeviceChanged = false;
1428 for (const auto& [id, dev] : mDevices) {
1429 if (dev->associatedDevice && dev->associatedDevice->sysfsRootPath == path) {
1430 if (*associatedDevice != *dev->associatedDevice) {
1431 associatedDeviceChanged = true;
1432 dev->associatedDevice = associatedDevice;
1433 }
1434 associatedDevice = dev->associatedDevice;
1435 }
1436 }
1437 ALOGI_IF(associatedDeviceChanged,
1438 "The AssociatedDevice changed for path '%s'. Using new AssociatedDevice: %s",
1439 path.c_str(), associatedDevice->dump().c_str());
1440
1441 return associatedDevice;
Prabir Pradhancb42b472022-08-23 16:01:19 +00001442}
1443
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001444void EventHub::vibrate(int32_t deviceId, const VibrationElement& element) {
Chris Ye87143712020-11-10 05:05:58 +00001445 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001446 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001447 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001448 ff_effect effect;
1449 memset(&effect, 0, sizeof(effect));
1450 effect.type = FF_RUMBLE;
1451 effect.id = device->ffEffectId;
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001452 // evdev FF_RUMBLE effect only supports two channels of vibration.
Chris Ye6393a262020-08-04 19:41:36 -07001453 effect.u.rumble.strong_magnitude = element.getMagnitude(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1454 effect.u.rumble.weak_magnitude = element.getMagnitude(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001455 effect.replay.length = element.duration.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001456 effect.replay.delay = 0;
1457 if (ioctl(device->fd, EVIOCSFF, &effect)) {
1458 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001459 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001460 return;
1461 }
1462 device->ffEffectId = effect.id;
1463
1464 struct input_event ev;
1465 ev.time.tv_sec = 0;
1466 ev.time.tv_usec = 0;
1467 ev.type = EV_FF;
1468 ev.code = device->ffEffectId;
1469 ev.value = 1;
1470 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1471 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001472 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001473 return;
1474 }
1475 device->ffEffectPlaying = true;
1476 }
1477}
1478
1479void EventHub::cancelVibrate(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001480 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001481 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001482 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001483 if (device->ffEffectPlaying) {
1484 device->ffEffectPlaying = false;
1485
1486 struct input_event ev;
1487 ev.time.tv_sec = 0;
1488 ev.time.tv_usec = 0;
1489 ev.type = EV_FF;
1490 ev.code = device->ffEffectId;
1491 ev.value = 0;
1492 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1493 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001494 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001495 return;
1496 }
1497 }
1498 }
1499}
1500
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001501std::vector<int32_t> EventHub::getVibratorIds(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001502 std::scoped_lock _l(mLock);
1503 std::vector<int32_t> vibrators;
1504 Device* device = getDeviceLocked(deviceId);
1505 if (device != nullptr && device->hasValidFd() &&
1506 device->classes.test(InputDeviceClass::VIBRATOR)) {
1507 vibrators.push_back(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1508 vibrators.push_back(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
1509 }
1510 return vibrators;
1511}
1512
Josh Bartel938632f2022-07-19 15:34:22 -05001513/**
1514 * Checks both mDevices and mOpeningDevices for a device with the descriptor passed.
1515 */
1516bool EventHub::hasDeviceWithDescriptorLocked(const std::string& descriptor) const {
1517 for (const auto& device : mOpeningDevices) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001518 if (descriptor == device->identifier.descriptor) {
Josh Bartel938632f2022-07-19 15:34:22 -05001519 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001520 }
1521 }
Josh Bartel938632f2022-07-19 15:34:22 -05001522
1523 for (const auto& [id, device] : mDevices) {
1524 if (descriptor == device->identifier.descriptor) {
1525 return true;
1526 }
1527 }
1528 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001529}
1530
1531EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001532 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001533 deviceId = mBuiltInKeyboardId;
1534 }
Chris Ye989bb932020-07-04 16:18:59 -07001535 const auto& it = mDevices.find(deviceId);
1536 return it != mDevices.end() ? it->second.get() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001537}
1538
Chris Ye8594e192020-07-14 10:34:06 -07001539EventHub::Device* EventHub::getDeviceByPathLocked(const std::string& devicePath) const {
Chris Ye989bb932020-07-04 16:18:59 -07001540 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001541 if (device->path == devicePath) {
Chris Ye989bb932020-07-04 16:18:59 -07001542 return device.get();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001543 }
1544 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001545 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001546}
1547
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001548/**
1549 * The file descriptor could be either input device, or a video device (associated with a
1550 * specific input device). Check both cases here, and return the device that this event
1551 * belongs to. Caller can compare the fd's once more to determine event type.
1552 * Looks through all input devices, and only attached video devices. Unattached video
1553 * devices are ignored.
1554 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001555EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
Chris Ye989bb932020-07-04 16:18:59 -07001556 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001557 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001558 // This is an input device event
Chris Ye989bb932020-07-04 16:18:59 -07001559 return device.get();
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001560 }
1561 if (device->videoDevice && device->videoDevice->getFd() == fd) {
1562 // This is a video device event
Chris Ye989bb932020-07-04 16:18:59 -07001563 return device.get();
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001564 }
1565 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001566 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
1567 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001568 return nullptr;
1569}
1570
Chris Yee2b1e5c2021-03-10 22:45:12 -08001571std::optional<int32_t> EventHub::getBatteryCapacity(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001572 std::filesystem::path batteryPath;
1573 {
1574 // Do not read the sysfs node to get the battery state while holding
1575 // the EventHub lock. For some peripheral devices, reading battery state
1576 // can be broken and take 5+ seconds. Holding the lock in this case would
1577 // block all other event processing during this time. For now, we assume this
1578 // call never happens on the InputReader thread and read the sysfs node outside
1579 // the lock to prevent event processing from being blocked by this call.
1580 std::scoped_lock _l(mLock);
Kim Low03ea0352020-11-06 12:45:07 -08001581
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001582 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001583 auto it = infos.find(batteryId);
1584 if (it == infos.end()) {
1585 return std::nullopt;
1586 }
1587 batteryPath = it->second.path;
1588 } // release lock
1589
Chris Yee2b1e5c2021-03-10 22:45:12 -08001590 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001591
1592 // Some devices report battery capacity as an integer through the "capacity" file
Andy Chenf9f1a022022-08-29 20:07:10 -04001593 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001594 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001595 return std::stoi(base::Trim(buffer));
Kim Low03ea0352020-11-06 12:45:07 -08001596 }
1597
1598 // Other devices report capacity as an enum value POWER_SUPPLY_CAPACITY_LEVEL_XXX
1599 // These values are taken from kernel source code include/linux/power_supply.h
Andy Chenf9f1a022022-08-29 20:07:10 -04001600 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY_LEVEL),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001601 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001602 // Remove any white space such as trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001603 const auto levelIt = BATTERY_LEVEL.find(base::Trim(buffer));
1604 if (levelIt != BATTERY_LEVEL.end()) {
1605 return levelIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001606 }
1607 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001608
Kim Low03ea0352020-11-06 12:45:07 -08001609 return std::nullopt;
1610}
1611
Chris Yee2b1e5c2021-03-10 22:45:12 -08001612std::optional<int32_t> EventHub::getBatteryStatus(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001613 std::filesystem::path batteryPath;
1614 {
1615 // Do not read the sysfs node to get the battery state while holding
1616 // the EventHub lock. For some peripheral devices, reading battery state
1617 // can be broken and take 5+ seconds. Holding the lock in this case would
1618 // block all other event processing during this time. For now, we assume this
1619 // call never happens on the InputReader thread and read the sysfs node outside
1620 // the lock to prevent event processing from being blocked by this call.
1621 std::scoped_lock _l(mLock);
1622
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001623 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001624 auto it = infos.find(batteryId);
1625 if (it == infos.end()) {
1626 return std::nullopt;
1627 }
1628 batteryPath = it->second.path;
1629 } // release lock
1630
Chris Yee2b1e5c2021-03-10 22:45:12 -08001631 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001632
Andy Chenf9f1a022022-08-29 20:07:10 -04001633 if (!base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::STATUS),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001634 &buffer)) {
Kim Low03ea0352020-11-06 12:45:07 -08001635 ALOGE("Failed to read sysfs battery info: %s", strerror(errno));
1636 return std::nullopt;
1637 }
1638
Chris Yed1936772021-02-22 10:30:40 -08001639 // Remove white space like trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001640 const auto statusIt = BATTERY_STATUS.find(base::Trim(buffer));
1641 if (statusIt != BATTERY_STATUS.end()) {
1642 return statusIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001643 }
1644
1645 return std::nullopt;
1646}
1647
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001648std::vector<RawEvent> EventHub::getEvents(int timeoutMillis) {
Chris Ye87143712020-11-10 05:05:58 +00001649 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001650
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001651 std::array<input_event, EVENT_BUFFER_SIZE> readBuffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001652
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001653 std::vector<RawEvent> events;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001654 bool awoken = false;
1655 for (;;) {
1656 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
1657
1658 // Reopen input devices if needed.
1659 if (mNeedToReopenDevices) {
1660 mNeedToReopenDevices = false;
1661
1662 ALOGI("Reopening all input devices due to a configuration change.");
1663
1664 closeAllDevicesLocked();
1665 mNeedToScanDevices = true;
1666 break; // return to the caller before we actually rescan
1667 }
1668
1669 // Report any devices that had last been added/removed.
Chris Ye989bb932020-07-04 16:18:59 -07001670 for (auto it = mClosingDevices.begin(); it != mClosingDevices.end();) {
1671 std::unique_ptr<Device> device = std::move(*it);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001672 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001673 const int32_t deviceId = (device->id == mBuiltInKeyboardId)
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001674 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
1675 : device->id;
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001676 events.push_back({
1677 .when = now,
1678 .deviceId = deviceId,
1679 .type = DEVICE_REMOVED,
1680 });
Chris Ye989bb932020-07-04 16:18:59 -07001681 it = mClosingDevices.erase(it);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001682 mNeedToSendFinishedDeviceScan = true;
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001683 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001684 break;
1685 }
1686 }
1687
1688 if (mNeedToScanDevices) {
1689 mNeedToScanDevices = false;
1690 scanDevicesLocked();
1691 mNeedToSendFinishedDeviceScan = true;
1692 }
1693
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001694 while (!mOpeningDevices.empty()) {
1695 std::unique_ptr<Device> device = std::move(*mOpeningDevices.rbegin());
1696 mOpeningDevices.pop_back();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001697 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001698 const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1699 events.push_back({
1700 .when = now,
1701 .deviceId = deviceId,
1702 .type = DEVICE_ADDED,
1703 });
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001704
1705 // Try to find a matching video device by comparing device names
1706 for (auto it = mUnattachedVideoDevices.begin(); it != mUnattachedVideoDevices.end();
1707 it++) {
1708 std::unique_ptr<TouchVideoDevice>& videoDevice = *it;
Chris Yed3fef462021-03-07 17:10:08 -08001709 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001710 // videoDevice was transferred to 'device'
1711 it = mUnattachedVideoDevices.erase(it);
1712 break;
1713 }
1714 }
1715
1716 auto [dev_it, inserted] = mDevices.insert_or_assign(device->id, std::move(device));
1717 if (!inserted) {
Chris Ye989bb932020-07-04 16:18:59 -07001718 ALOGW("Device id %d exists, replaced.", device->id);
1719 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001720 mNeedToSendFinishedDeviceScan = true;
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001721 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001722 break;
1723 }
1724 }
1725
1726 if (mNeedToSendFinishedDeviceScan) {
1727 mNeedToSendFinishedDeviceScan = false;
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001728 events.push_back({
1729 .when = now,
1730 .type = FINISHED_DEVICE_SCAN,
1731 });
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001732 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001733 break;
1734 }
1735 }
1736
1737 // Grab the next input event.
1738 bool deviceChanged = false;
1739 while (mPendingEventIndex < mPendingEventCount) {
1740 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001741 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001742 if (eventItem.events & EPOLLIN) {
1743 mPendingINotify = true;
1744 } else {
1745 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
1746 }
1747 continue;
1748 }
1749
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001750 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001751 if (eventItem.events & EPOLLIN) {
1752 ALOGV("awoken after wake()");
1753 awoken = true;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001754 char wakeReadBuffer[16];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001755 ssize_t nRead;
1756 do {
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001757 nRead = read(mWakeReadPipeFd, wakeReadBuffer, sizeof(wakeReadBuffer));
1758 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(wakeReadBuffer));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001759 } else {
1760 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001761 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001762 }
1763 continue;
1764 }
1765
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001766 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Chris Ye989bb932020-07-04 16:18:59 -07001767 if (device == nullptr) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001768 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
1769 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001770 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001771 continue;
1772 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001773 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
1774 if (eventItem.events & EPOLLIN) {
1775 size_t numFrames = device->videoDevice->readAndQueueFrames();
1776 if (numFrames == 0) {
1777 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001778 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001779 }
1780 } else if (eventItem.events & EPOLLHUP) {
1781 // TODO(b/121395353) - consider adding EPOLLRDHUP
1782 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001783 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001784 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1785 device->videoDevice = nullptr;
1786 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001787 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1788 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001789 ALOG_ASSERT(!DEBUG);
1790 }
1791 continue;
1792 }
1793 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -08001794 if (eventItem.events & EPOLLIN) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001795 int32_t readSize =
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001796 read(device->fd, readBuffer.data(),
1797 sizeof(decltype(readBuffer)::value_type) * readBuffer.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001798 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
1799 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -07001800 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001801 " capacity: %zu errno: %d)\n",
1802 device->fd, readSize, readBuffer.size(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001803 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001804 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001805 } else if (readSize < 0) {
1806 if (errno != EAGAIN && errno != EINTR) {
1807 ALOGW("could not get event (errno=%d)", errno);
1808 }
1809 } else if ((readSize % sizeof(struct input_event)) != 0) {
1810 ALOGE("could not get event (wrong size: %d)", readSize);
1811 } else {
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001812 const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001813
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001814 const size_t count = size_t(readSize) / sizeof(struct input_event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001815 for (size_t i = 0; i < count; i++) {
1816 struct input_event& iev = readBuffer[i];
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001817 events.push_back({
1818 .when = processEventTimestamp(iev),
1819 .readTime = systemTime(SYSTEM_TIME_MONOTONIC),
1820 .deviceId = deviceId,
1821 .type = iev.type,
1822 .code = iev.code,
1823 .value = iev.value,
1824 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08001825 }
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001826 if (events.size() >= EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001827 // The result buffer is full. Reset the pending event index
1828 // so we will try to read the device again on the next iteration.
1829 mPendingEventIndex -= 1;
1830 break;
1831 }
1832 }
1833 } else if (eventItem.events & EPOLLHUP) {
1834 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001835 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001836 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001837 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001838 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001839 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1840 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001841 }
1842 }
1843
1844 // readNotify() will modify the list of devices so this must be done after
1845 // processing all other events to ensure that we read all remaining events
1846 // before closing the devices.
1847 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
1848 mPendingINotify = false;
Prabir Pradhan952e65b2022-06-23 17:49:55 +00001849 const auto res = readNotifyLocked();
1850 if (!res.ok()) {
1851 ALOGW("Failed to read from inotify: %s", res.error().message().c_str());
1852 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001853 deviceChanged = true;
1854 }
1855
1856 // Report added or removed devices immediately.
1857 if (deviceChanged) {
1858 continue;
1859 }
1860
1861 // Return now if we have collected any events or if we were explicitly awoken.
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001862 if (!events.empty() || awoken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001863 break;
1864 }
1865
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001866 // Poll for events.
1867 // When a device driver has pending (unread) events, it acquires
1868 // a kernel wake lock. Once the last pending event has been read, the device
1869 // driver will release the kernel wake lock, but the epoll will hold the wakelock,
1870 // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
1871 // is called again for the same fd that produced the event.
1872 // Thus the system can only sleep if there are no events pending or
1873 // currently being processed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001874 //
1875 // The timeout is advisory only. If the device is asleep, it will not wake just to
1876 // service the timeout.
1877 mPendingEventIndex = 0;
1878
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001879 mLock.unlock(); // release lock before poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001880
1881 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1882
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001883 mLock.lock(); // reacquire lock after poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001884
1885 if (pollResult == 0) {
1886 // Timed out.
1887 mPendingEventCount = 0;
1888 break;
1889 }
1890
1891 if (pollResult < 0) {
1892 // An error occurred.
1893 mPendingEventCount = 0;
1894
1895 // Sleep after errors to avoid locking up the system.
1896 // Hopefully the error is transient.
1897 if (errno != EINTR) {
1898 ALOGW("poll failed (errno=%d)\n", errno);
1899 usleep(100000);
1900 }
1901 } else {
1902 // Some events occurred.
1903 mPendingEventCount = size_t(pollResult);
1904 }
1905 }
1906
1907 // All done, return the number of events we read.
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001908 return events;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001909}
1910
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001911std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001912 std::scoped_lock _l(mLock);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001913
1914 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001915 if (device == nullptr || !device->videoDevice) {
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001916 return {};
1917 }
1918 return device->videoDevice->consumeFrames();
1919}
1920
Michael Wrightd02c5b62014-02-10 15:10:22 -08001921void EventHub::wake() {
1922 ALOGV("wake() called");
1923
1924 ssize_t nWrite;
1925 do {
1926 nWrite = write(mWakeWritePipeFd, "W", 1);
1927 } while (nWrite == -1 && errno == EINTR);
1928
1929 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001930 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001931 }
1932}
1933
1934void EventHub::scanDevicesLocked() {
Usama Arifb27c8e62021-06-03 16:44:09 +01001935 status_t result;
1936 std::error_code errorCode;
1937
1938 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
1939 result = scanDirLocked(DEVICE_INPUT_PATH);
1940 if (result < 0) {
1941 ALOGE("scan dir failed for %s", DEVICE_INPUT_PATH);
1942 }
1943 } else {
1944 if (errorCode) {
1945 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
1946 errorCode.message().c_str());
1947 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001948 }
Philip Quinn39b81682019-01-09 22:20:39 -08001949 if (isV4lScanningEnabled()) {
Usama Arifb27c8e62021-06-03 16:44:09 +01001950 result = scanVideoDirLocked(DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08001951 if (result != OK) {
Usama Arifb27c8e62021-06-03 16:44:09 +01001952 ALOGE("scan video dir failed for %s", DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08001953 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001954 }
Chris Ye989bb932020-07-04 16:18:59 -07001955 if (mDevices.find(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) == mDevices.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001956 createVirtualKeyboardLocked();
1957 }
1958}
1959
1960// ----------------------------------------------------------------------------
1961
Michael Wrightd02c5b62014-02-10 15:10:22 -08001962static const int32_t GAMEPAD_KEYCODES[] = {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001963 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C, //
1964 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z, //
1965 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1, //
1966 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2, //
1967 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR, //
1968 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE, //
Michael Wrightd02c5b62014-02-10 15:10:22 -08001969};
1970
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001971status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001972 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001973 struct epoll_event eventItem = {};
1974 eventItem.events = EPOLLIN | EPOLLWAKEUP;
1975 eventItem.data.fd = fd;
1976 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1977 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001978 return -errno;
1979 }
1980 return OK;
1981}
1982
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001983status_t EventHub::unregisterFdFromEpoll(int fd) {
1984 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
1985 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
1986 return -errno;
1987 }
1988 return OK;
1989}
1990
Chris Ye989bb932020-07-04 16:18:59 -07001991status_t EventHub::registerDeviceForEpollLocked(Device& device) {
1992 status_t result = registerFdForEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001993 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07001994 ALOGE("Could not add input device fd to epoll for device %" PRId32, device.id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001995 return result;
1996 }
Chris Ye989bb932020-07-04 16:18:59 -07001997 if (device.videoDevice) {
1998 registerVideoDeviceForEpollLocked(*device.videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001999 }
2000 return result;
2001}
2002
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002003void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
2004 status_t result = registerFdForEpoll(videoDevice.getFd());
2005 if (result != OK) {
2006 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
2007 }
2008}
2009
Chris Ye989bb932020-07-04 16:18:59 -07002010status_t EventHub::unregisterDeviceFromEpollLocked(Device& device) {
2011 if (device.hasValidFd()) {
2012 status_t result = unregisterFdFromEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002013 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07002014 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device.id);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002015 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002016 }
2017 }
Chris Ye989bb932020-07-04 16:18:59 -07002018 if (device.videoDevice) {
2019 unregisterVideoDeviceFromEpollLocked(*device.videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002020 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002021 return OK;
2022}
2023
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002024void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
2025 if (videoDevice.hasValidFd()) {
2026 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
2027 if (result != OK) {
2028 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002029 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002030 }
2031 }
2032}
2033
Chris Yed3fef462021-03-07 17:10:08 -08002034void EventHub::reportDeviceAddedForStatisticsLocked(const InputDeviceIdentifier& identifier,
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002035 ftl::Flags<InputDeviceClass> classes) {
Chris Ye657c2f02021-05-25 16:24:37 -07002036 SHA256_CTX ctx;
2037 SHA256_Init(&ctx);
2038 SHA256_Update(&ctx, reinterpret_cast<const uint8_t*>(identifier.uniqueId.c_str()),
2039 identifier.uniqueId.size());
2040 std::array<uint8_t, SHA256_DIGEST_LENGTH> digest;
2041 SHA256_Final(digest.data(), &ctx);
2042
2043 std::string obfuscatedId;
2044 for (size_t i = 0; i < OBFUSCATED_LENGTH; i++) {
2045 obfuscatedId += StringPrintf("%02x", digest[i]);
2046 }
2047
Chris Yed3fef462021-03-07 17:10:08 -08002048 android::util::stats_write(android::util::INPUTDEVICE_REGISTERED, identifier.name.c_str(),
2049 identifier.vendor, identifier.product, identifier.version,
Chris Ye657c2f02021-05-25 16:24:37 -07002050 identifier.bus, obfuscatedId.c_str(), classes.get());
Chris Yed3fef462021-03-07 17:10:08 -08002051}
2052
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002053void EventHub::openDeviceLocked(const std::string& devicePath) {
2054 // If an input device happens to register around the time when EventHub's constructor runs, it
2055 // is possible that the same input event node (for example, /dev/input/event3) will be noticed
2056 // in both 'inotify' callback and also in the 'scanDirLocked' pass. To prevent duplicate devices
2057 // from getting registered, ensure that this path is not already covered by an existing device.
2058 for (const auto& [deviceId, device] : mDevices) {
2059 if (device->path == devicePath) {
2060 return; // device was already registered
2061 }
2062 }
2063
Michael Wrightd02c5b62014-02-10 15:10:22 -08002064 char buffer[80];
2065
Chris Ye8594e192020-07-14 10:34:06 -07002066 ALOGV("Opening device: %s", devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002067
Chris Ye8594e192020-07-14 10:34:06 -07002068 int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002069 if (fd < 0) {
Chris Ye8594e192020-07-14 10:34:06 -07002070 ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002071 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002072 }
2073
2074 InputDeviceIdentifier identifier;
2075
2076 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002077 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Chris Ye8594e192020-07-14 10:34:06 -07002078 ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002079 } else {
2080 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002081 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002082 }
2083
2084 // Check to see if the device is on our excluded list
2085 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002086 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002087 if (identifier.name == item) {
Chris Ye8594e192020-07-14 10:34:06 -07002088 ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002089 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002090 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002091 }
2092 }
2093
2094 // Get device driver version.
2095 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002096 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Chris Ye8594e192020-07-14 10:34:06 -07002097 ALOGE("could not get driver version for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002098 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002099 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002100 }
2101
2102 // Get device identifier.
2103 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002104 if (ioctl(fd, EVIOCGID, &inputId)) {
Chris Ye8594e192020-07-14 10:34:06 -07002105 ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002106 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002107 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002108 }
2109 identifier.bus = inputId.bustype;
2110 identifier.product = inputId.product;
2111 identifier.vendor = inputId.vendor;
2112 identifier.version = inputId.version;
2113
2114 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002115 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
2116 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002117 } else {
2118 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002119 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002120 }
2121
2122 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002123 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
2124 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002125 } else {
2126 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002127 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002128 }
2129
2130 // Fill in the descriptor.
2131 assignDescriptorLocked(identifier);
2132
Michael Wrightd02c5b62014-02-10 15:10:22 -08002133 // Allocate device. (The device object takes ownership of the fd at this point.)
2134 int32_t deviceId = mNextDeviceId++;
Prabir Pradhancb42b472022-08-23 16:01:19 +00002135 std::unique_ptr<Device> device =
2136 std::make_unique<Device>(fd, deviceId, devicePath, identifier,
2137 obtainAssociatedDeviceLocked(devicePath));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002138
Chris Ye8594e192020-07-14 10:34:06 -07002139 ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002140 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002141 " vendor %04x\n"
2142 " product %04x\n"
2143 " version %04x\n",
2144 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002145 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
2146 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
2147 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
2148 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002149 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
2150 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002151
2152 // Load the configuration file for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002153 device->loadConfigurationLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002154
2155 // Figure out the kinds of events the device reports.
Chris Ye66fbac32020-07-06 20:36:43 -07002156 device->readDeviceBitMask(EVIOCGBIT(EV_KEY, 0), device->keyBitmask);
2157 device->readDeviceBitMask(EVIOCGBIT(EV_ABS, 0), device->absBitmask);
2158 device->readDeviceBitMask(EVIOCGBIT(EV_REL, 0), device->relBitmask);
2159 device->readDeviceBitMask(EVIOCGBIT(EV_SW, 0), device->swBitmask);
2160 device->readDeviceBitMask(EVIOCGBIT(EV_LED, 0), device->ledBitmask);
2161 device->readDeviceBitMask(EVIOCGBIT(EV_FF, 0), device->ffBitmask);
Chris Yef59a2f42020-10-16 12:55:26 -07002162 device->readDeviceBitMask(EVIOCGBIT(EV_MSC, 0), device->mscBitmask);
Chris Ye66fbac32020-07-06 20:36:43 -07002163 device->readDeviceBitMask(EVIOCGPROP(0), device->propBitmask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002164
2165 // See if this is a keyboard. Ignore everything in the button range except for
2166 // joystick and gamepad buttons which are handled like keyboards for the most part.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002167 bool haveKeyboardKeys =
Chris Ye66fbac32020-07-06 20:36:43 -07002168 device->keyBitmask.any(0, BTN_MISC) || device->keyBitmask.any(BTN_WHEEL, KEY_MAX + 1);
2169 bool haveGamepadButtons = device->keyBitmask.any(BTN_MISC, BTN_MOUSE) ||
2170 device->keyBitmask.any(BTN_JOYSTICK, BTN_DIGI);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002171 if (haveKeyboardKeys || haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002172 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002173 }
2174
2175 // See if this is a cursor device such as a trackball or mouse.
Chris Ye66fbac32020-07-06 20:36:43 -07002176 if (device->keyBitmask.test(BTN_MOUSE) && device->relBitmask.test(REL_X) &&
2177 device->relBitmask.test(REL_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002178 device->classes |= InputDeviceClass::CURSOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002179 }
2180
Prashant Malani1941ff52015-08-11 18:29:28 -07002181 // See if this is a rotary encoder type device.
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07002182 std::string deviceType;
2183 if (device->configuration && device->configuration->tryGetProperty("device.type", deviceType)) {
2184 if (deviceType == "rotaryEncoder") {
Chris Ye1b0c7342020-07-28 21:57:03 -07002185 device->classes |= InputDeviceClass::ROTARY_ENCODER;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002186 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002187 }
2188
Michael Wrightd02c5b62014-02-10 15:10:22 -08002189 // See if this is a touch pad.
2190 // Is this a new modern multi-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002191 if (device->absBitmask.test(ABS_MT_POSITION_X) && device->absBitmask.test(ABS_MT_POSITION_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002192 // Some joysticks such as the PS3 controller report axes that conflict
2193 // with the ABS_MT range. Try to confirm that the device really is
2194 // a touch screen.
Chris Ye66fbac32020-07-06 20:36:43 -07002195 if (device->keyBitmask.test(BTN_TOUCH) || !haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002196 device->classes |= (InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002197 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002198 // Is this an old style single-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002199 } else if (device->keyBitmask.test(BTN_TOUCH) && device->absBitmask.test(ABS_X) &&
2200 device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002201 device->classes |= InputDeviceClass::TOUCH;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002202 // Is this a BT stylus?
Chris Ye66fbac32020-07-06 20:36:43 -07002203 } else if ((device->absBitmask.test(ABS_PRESSURE) || device->keyBitmask.test(BTN_TOUCH)) &&
2204 !device->absBitmask.test(ABS_X) && !device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002205 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -07002206 // Keyboard will try to claim some of the buttons but we really want to reserve those so we
2207 // can fuse it with the touch screen data, so just take them back. Note this means an
2208 // external stylus cannot also be a keyboard device.
Chris Ye1b0c7342020-07-28 21:57:03 -07002209 device->classes &= ~InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002210 }
2211
2212 // See if this device is a joystick.
2213 // Assumes that joysticks always have gamepad buttons in order to distinguish them
2214 // from other devices such as accelerometers that also have absolute axes.
2215 if (haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002216 auto assumedClasses = device->classes | InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002217 for (int i = 0; i <= ABS_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002218 if (device->absBitmask.test(i) &&
Chris Ye1b0c7342020-07-28 21:57:03 -07002219 (getAbsAxisUsage(i, assumedClasses).test(InputDeviceClass::JOYSTICK))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002220 device->classes = assumedClasses;
2221 break;
2222 }
2223 }
2224 }
2225
Chris Yef59a2f42020-10-16 12:55:26 -07002226 // Check whether this device is an accelerometer.
2227 if (device->propBitmask.test(INPUT_PROP_ACCELEROMETER)) {
2228 device->classes |= InputDeviceClass::SENSOR;
2229 }
2230
Michael Wrightd02c5b62014-02-10 15:10:22 -08002231 // Check whether this device has switches.
2232 for (int i = 0; i <= SW_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002233 if (device->swBitmask.test(i)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002234 device->classes |= InputDeviceClass::SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002235 break;
2236 }
2237 }
2238
2239 // Check whether this device supports the vibrator.
Chris Ye66fbac32020-07-06 20:36:43 -07002240 if (device->ffBitmask.test(FF_RUMBLE)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002241 device->classes |= InputDeviceClass::VIBRATOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242 }
2243
2244 // Configure virtual keys.
Chris Ye1b0c7342020-07-28 21:57:03 -07002245 if ((device->classes.test(InputDeviceClass::TOUCH))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002246 // Load the virtual keys for the touch screen, if any.
2247 // We do this now so that we can make sure to load the keymap if necessary.
Chris Ye989bb932020-07-04 16:18:59 -07002248 bool success = device->loadVirtualKeyMapLocked();
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06002249 if (success) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002250 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002251 }
2252 }
2253
2254 // Load the key map.
Chris Yef59a2f42020-10-16 12:55:26 -07002255 // We need to do this for joysticks too because the key layout may specify axes, and for
2256 // sensor as well because the key layout may specify the axes to sensor data mapping.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002257 status_t keyMapStatus = NAME_NOT_FOUND;
Chris Yef59a2f42020-10-16 12:55:26 -07002258 if (device->classes.any(InputDeviceClass::KEYBOARD | InputDeviceClass::JOYSTICK |
2259 InputDeviceClass::SENSOR)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002260 // Load the keymap for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002261 keyMapStatus = device->loadKeyMapLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002262 }
2263
2264 // Configure the keyboard, gamepad or virtual keyboard.
Chris Ye1b0c7342020-07-28 21:57:03 -07002265 if (device->classes.test(InputDeviceClass::KEYBOARD)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002266 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002267 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002268 isEligibleBuiltInKeyboard(device->identifier, device->configuration.get(),
2269 &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002270 mBuiltInKeyboardId = device->id;
2271 }
2272
2273 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
Chris Ye989bb932020-07-04 16:18:59 -07002274 if (device->hasKeycodeLocked(AKEYCODE_Q)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002275 device->classes |= InputDeviceClass::ALPHAKEY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002276 }
2277
2278 // See if this device has a DPAD.
Chris Ye989bb932020-07-04 16:18:59 -07002279 if (device->hasKeycodeLocked(AKEYCODE_DPAD_UP) &&
2280 device->hasKeycodeLocked(AKEYCODE_DPAD_DOWN) &&
2281 device->hasKeycodeLocked(AKEYCODE_DPAD_LEFT) &&
2282 device->hasKeycodeLocked(AKEYCODE_DPAD_RIGHT) &&
2283 device->hasKeycodeLocked(AKEYCODE_DPAD_CENTER)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002284 device->classes |= InputDeviceClass::DPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002285 }
2286
2287 // See if this device has a gamepad.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002288 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES) / sizeof(GAMEPAD_KEYCODES[0]); i++) {
Chris Ye989bb932020-07-04 16:18:59 -07002289 if (device->hasKeycodeLocked(GAMEPAD_KEYCODES[i])) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002290 device->classes |= InputDeviceClass::GAMEPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002291 break;
2292 }
2293 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002294 }
2295
2296 // If the device isn't recognized as something we handle, don't monitor it.
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002297 if (device->classes == ftl::Flags<InputDeviceClass>(0)) {
Chris Ye8594e192020-07-14 10:34:06 -07002298 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002299 device->identifier.name.c_str());
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002300 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002301 }
2302
Chris Ye3fdbfef2021-01-06 18:45:18 -08002303 // Classify InputDeviceClass::BATTERY.
Prabir Pradhan51894782022-08-23 16:29:10 +00002304 if (device->associatedDevice && !device->associatedDevice->batteryInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002305 device->classes |= InputDeviceClass::BATTERY;
2306 }
Kim Low03ea0352020-11-06 12:45:07 -08002307
Chris Ye3fdbfef2021-01-06 18:45:18 -08002308 // Classify InputDeviceClass::LIGHT.
Prabir Pradhan51894782022-08-23 16:29:10 +00002309 if (device->associatedDevice && !device->associatedDevice->lightInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002310 device->classes |= InputDeviceClass::LIGHT;
Kim Low03ea0352020-11-06 12:45:07 -08002311 }
2312
Tim Kilbourn063ff532015-04-08 10:26:18 -07002313 // Determine whether the device has a mic.
Chris Ye989bb932020-07-04 16:18:59 -07002314 if (device->deviceHasMicLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002315 device->classes |= InputDeviceClass::MIC;
Tim Kilbourn063ff532015-04-08 10:26:18 -07002316 }
2317
Michael Wrightd02c5b62014-02-10 15:10:22 -08002318 // Determine whether the device is external or internal.
Chris Ye989bb932020-07-04 16:18:59 -07002319 if (device->isExternalDeviceLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002320 device->classes |= InputDeviceClass::EXTERNAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002321 }
2322
Chris Ye1b0c7342020-07-28 21:57:03 -07002323 if (device->classes.any(InputDeviceClass::JOYSTICK | InputDeviceClass::DPAD) &&
2324 device->classes.test(InputDeviceClass::GAMEPAD)) {
Chris Ye989bb932020-07-04 16:18:59 -07002325 device->controllerNumber = getNextControllerNumberLocked(device->identifier.name);
2326 device->setLedForControllerLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002327 }
2328
Chris Ye989bb932020-07-04 16:18:59 -07002329 if (registerDeviceForEpollLocked(*device) != OK) {
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002330 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002331 }
2332
Chris Ye989bb932020-07-04 16:18:59 -07002333 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002334
Chris Ye1b0c7342020-07-28 21:57:03 -07002335 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=%s, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002336 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Chris Ye1b0c7342020-07-28 21:57:03 -07002337 deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(),
2338 device->classes.string().c_str(), device->configurationFile.c_str(),
2339 device->keyMap.keyLayoutFile.c_str(), device->keyMap.keyCharacterMapFile.c_str(),
2340 toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002341
Chris Ye989bb932020-07-04 16:18:59 -07002342 addDeviceLocked(std::move(device));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002343}
2344
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002345void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
2346 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
2347 if (!videoDevice) {
2348 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
2349 return;
2350 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002351 // Transfer ownership of this video device to a matching input device
Chris Ye989bb932020-07-04 16:18:59 -07002352 for (const auto& [id, device] : mDevices) {
Chris Yed3fef462021-03-07 17:10:08 -08002353 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002354 return; // 'device' now owns 'videoDevice'
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002355 }
2356 }
2357
2358 // Couldn't find a matching input device, so just add it to a temporary holding queue.
2359 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002360 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002361 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002362 mUnattachedVideoDevices.push_back(std::move(videoDevice));
2363}
2364
Chris Yed3fef462021-03-07 17:10:08 -08002365bool EventHub::tryAddVideoDeviceLocked(EventHub::Device& device,
2366 std::unique_ptr<TouchVideoDevice>& videoDevice) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002367 if (videoDevice->getName() != device.identifier.name) {
2368 return false;
2369 }
2370 device.videoDevice = std::move(videoDevice);
2371 if (device.enabled) {
2372 registerVideoDeviceForEpollLocked(*device.videoDevice);
2373 }
2374 return true;
2375}
2376
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002377bool EventHub::isDeviceEnabled(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00002378 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002379 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002380 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002381 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2382 return false;
2383 }
2384 return device->enabled;
2385}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002386
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002387status_t EventHub::enableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002388 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002389 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002390 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002391 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2392 return BAD_VALUE;
2393 }
2394 if (device->enabled) {
2395 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
2396 return OK;
2397 }
2398 status_t result = device->enable();
2399 if (result != OK) {
2400 ALOGE("Failed to enable device %" PRId32, deviceId);
2401 return result;
2402 }
2403
Chris Ye989bb932020-07-04 16:18:59 -07002404 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002405
Chris Ye989bb932020-07-04 16:18:59 -07002406 return registerDeviceForEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002407}
2408
2409status_t EventHub::disableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002410 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002411 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002412 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002413 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2414 return BAD_VALUE;
2415 }
2416 if (!device->enabled) {
2417 ALOGW("Duplicate call to %s, input device already disabled", __func__);
2418 return OK;
2419 }
Chris Ye989bb932020-07-04 16:18:59 -07002420 unregisterDeviceFromEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002421 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002422}
2423
2424void EventHub::createVirtualKeyboardLocked() {
2425 InputDeviceIdentifier identifier;
2426 identifier.name = "Virtual";
2427 identifier.uniqueId = "<virtual>";
2428 assignDescriptorLocked(identifier);
2429
Chris Ye989bb932020-07-04 16:18:59 -07002430 std::unique_ptr<Device> device =
2431 std::make_unique<Device>(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
Prabir Pradhancb42b472022-08-23 16:01:19 +00002432 identifier, nullptr /*associatedDevice*/);
Chris Ye1b0c7342020-07-28 21:57:03 -07002433 device->classes = InputDeviceClass::KEYBOARD | InputDeviceClass::ALPHAKEY |
2434 InputDeviceClass::DPAD | InputDeviceClass::VIRTUAL;
Chris Ye989bb932020-07-04 16:18:59 -07002435 device->loadKeyMapLocked();
2436 addDeviceLocked(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002437}
2438
Chris Ye989bb932020-07-04 16:18:59 -07002439void EventHub::addDeviceLocked(std::unique_ptr<Device> device) {
Chris Yed3fef462021-03-07 17:10:08 -08002440 reportDeviceAddedForStatisticsLocked(device->identifier, device->classes);
Chris Ye989bb932020-07-04 16:18:59 -07002441 mOpeningDevices.push_back(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002442}
2443
Chris Ye989bb932020-07-04 16:18:59 -07002444int32_t EventHub::getNextControllerNumberLocked(const std::string& name) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002445 if (mControllerNumbers.isFull()) {
2446 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Chris Ye989bb932020-07-04 16:18:59 -07002447 name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002448 return 0;
2449 }
2450 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
2451 // one
2452 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
2453}
2454
Chris Ye989bb932020-07-04 16:18:59 -07002455void EventHub::releaseControllerNumberLocked(int32_t num) {
2456 if (num > 0) {
2457 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002458 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002459}
2460
Chris Ye8594e192020-07-14 10:34:06 -07002461void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002462 Device* device = getDeviceByPathLocked(devicePath);
Chris Ye989bb932020-07-04 16:18:59 -07002463 if (device != nullptr) {
2464 closeDeviceLocked(*device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002465 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002466 }
Chris Ye8594e192020-07-14 10:34:06 -07002467 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002468}
2469
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002470/**
2471 * Find the video device by filename, and close it.
2472 * The video device is closed by path during an inotify event, where we don't have the
2473 * additional context about the video device fd, or the associated input device.
2474 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002475void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002476 // A video device may be owned by an existing input device, or it may be stored in
2477 // the mUnattachedVideoDevices queue. Check both locations.
Chris Ye989bb932020-07-04 16:18:59 -07002478 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002479 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002480 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002481 device->videoDevice = nullptr;
2482 return;
2483 }
2484 }
Siarhei Vishniakouf47c339e2021-12-30 11:22:26 -08002485 std::erase_if(mUnattachedVideoDevices,
2486 [&devicePath](const std::unique_ptr<TouchVideoDevice>& videoDevice) {
2487 return videoDevice->getPath() == devicePath;
2488 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08002489}
2490
2491void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002492 mUnattachedVideoDevices.clear();
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002493 while (!mDevices.empty()) {
2494 closeDeviceLocked(*(mDevices.begin()->second));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002495 }
2496}
2497
Chris Ye989bb932020-07-04 16:18:59 -07002498void EventHub::closeDeviceLocked(Device& device) {
2499 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=%s", device.path.c_str(),
2500 device.identifier.name.c_str(), device.id, device.fd, device.classes.string().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002501
Chris Ye989bb932020-07-04 16:18:59 -07002502 if (device.id == mBuiltInKeyboardId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002503 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Chris Ye989bb932020-07-04 16:18:59 -07002504 device.path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002505 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
2506 }
2507
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002508 unregisterDeviceFromEpollLocked(device);
Chris Ye989bb932020-07-04 16:18:59 -07002509 if (device.videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002510 // This must be done after the video device is removed from epoll
Chris Ye989bb932020-07-04 16:18:59 -07002511 mUnattachedVideoDevices.push_back(std::move(device.videoDevice));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002512 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002513
Chris Ye989bb932020-07-04 16:18:59 -07002514 releaseControllerNumberLocked(device.controllerNumber);
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002515 device.controllerNumber = 0;
Chris Ye989bb932020-07-04 16:18:59 -07002516 device.close();
Chris Ye989bb932020-07-04 16:18:59 -07002517 mClosingDevices.push_back(std::move(mDevices[device.id]));
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002518
Chris Ye989bb932020-07-04 16:18:59 -07002519 mDevices.erase(device.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002520}
2521
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002522base::Result<void> EventHub::readNotifyLocked() {
2523 static constexpr auto EVENT_SIZE = static_cast<ssize_t>(sizeof(inotify_event));
2524 uint8_t eventBuffer[512];
2525 ssize_t sizeRead;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002526
2527 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002528 do {
2529 sizeRead = read(mINotifyFd, eventBuffer, sizeof(eventBuffer));
2530 } while (sizeRead < 0 && errno == EINTR);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002531
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002532 if (sizeRead < EVENT_SIZE) return Errorf("could not get event, %s", strerror(errno));
2533
2534 for (ssize_t eventPos = 0; sizeRead >= EVENT_SIZE;) {
2535 const inotify_event* event;
2536 event = (const inotify_event*)(eventBuffer + eventPos);
2537 if (event->len == 0) continue;
2538
2539 handleNotifyEventLocked(*event);
2540
2541 const ssize_t eventSize = EVENT_SIZE + event->len;
2542 sizeRead -= eventSize;
2543 eventPos += eventSize;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002544 }
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002545 return {};
2546}
2547
2548void EventHub::handleNotifyEventLocked(const inotify_event& event) {
2549 if (event.wd == mDeviceInputWd) {
2550 std::string filename = std::string(DEVICE_INPUT_PATH) + "/" + event.name;
2551 if (event.mask & IN_CREATE) {
2552 openDeviceLocked(filename);
2553 } else {
2554 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
2555 closeDeviceByPathLocked(filename);
2556 }
2557 } else if (event.wd == mDeviceWd) {
2558 if (isV4lTouchNode(event.name)) {
2559 std::string filename = std::string(DEVICE_PATH) + "/" + event.name;
2560 if (event.mask & IN_CREATE) {
2561 openVideoDeviceLocked(filename);
2562 } else {
2563 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
2564 closeVideoDeviceByPathLocked(filename);
2565 }
2566 } else if (strcmp(event.name, "input") == 0 && event.mask & IN_CREATE) {
2567 addDeviceInputInotify();
2568 }
2569 } else {
2570 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event.wd);
2571 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002572}
2573
Chris Ye8594e192020-07-14 10:34:06 -07002574status_t EventHub::scanDirLocked(const std::string& dirname) {
2575 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2576 openDeviceLocked(entry.path());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002577 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002578 return 0;
2579}
2580
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002581/**
2582 * Look for all dirname/v4l-touch* devices, and open them.
2583 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002584status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Chris Ye8594e192020-07-14 10:34:06 -07002585 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2586 if (isV4lTouchNode(entry.path())) {
2587 ALOGI("Found touch video device %s", entry.path().c_str());
2588 openVideoDeviceLocked(entry.path());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002589 }
2590 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002591 return OK;
2592}
2593
Michael Wrightd02c5b62014-02-10 15:10:22 -08002594void EventHub::requestReopenDevices() {
2595 ALOGV("requestReopenDevices() called");
2596
Chris Ye87143712020-11-10 05:05:58 +00002597 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002598 mNeedToReopenDevices = true;
2599}
2600
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002601void EventHub::dump(std::string& dump) const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002602 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002603
2604 { // acquire lock
Chris Ye87143712020-11-10 05:05:58 +00002605 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002606
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002607 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002608
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002609 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002610
Chris Ye989bb932020-07-04 16:18:59 -07002611 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002612 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002613 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002614 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002615 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002616 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002617 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002618 }
Chris Ye1b0c7342020-07-28 21:57:03 -07002619 dump += StringPrintf(INDENT3 "Classes: %s\n", device->classes.string().c_str());
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002620 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002621 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002622 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
2623 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002624 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002625 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002626 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002627 "product=0x%04x, version=0x%04x\n",
2628 device->identifier.bus, device->identifier.vendor,
2629 device->identifier.product, device->identifier.version);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002630 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002631 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002632 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002633 device->keyMap.keyCharacterMapFile.c_str());
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00002634 dump += StringPrintf(INDENT3 "CountryCode: %d\n",
2635 device->associatedDevice ? device->associatedDevice->countryCode
2636 : InputDeviceCountryCode::INVALID);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002637 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002638 device->configurationFile.c_str());
Prabir Pradhan51894782022-08-23 16:29:10 +00002639 dump += StringPrintf(INDENT3 "VideoDevice: %s\n",
2640 device->videoDevice ? device->videoDevice->dump().c_str()
2641 : "<none>");
2642 dump += StringPrintf(INDENT3 "SysfsDevicePath: %s\n",
2643 device->associatedDevice
2644 ? device->associatedDevice->sysfsRootPath.c_str()
2645 : "<none>");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002646 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002647
2648 dump += INDENT "Unattached video devices:\n";
2649 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
2650 dump += INDENT2 + videoDevice->dump() + "\n";
2651 }
2652 if (mUnattachedVideoDevices.empty()) {
2653 dump += INDENT2 "<none>\n";
2654 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002655 } // release lock
2656}
2657
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002658void EventHub::monitor() const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002659 // Acquire and release the lock to ensure that the event hub has not deadlocked.
Chris Ye1c2e0892020-11-30 21:41:44 -08002660 std::unique_lock<std::mutex> lock(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002661}
2662
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00002663std::string EventHub::AssociatedDevice::dump() const {
2664 return StringPrintf("path=%s, numBatteries=%zu, numLight=%zu", sysfsRootPath.c_str(),
2665 batteryInfos.size(), lightInfos.size());
2666}
2667
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002668} // namespace android