blob: 5f715666d950dd908910a84a7b533ed16aa38751 [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>
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070031#include <sys/limits.h>
Kim Low03ea0352020-11-06 12:45:07 -080032#include <sys/stat.h>
33#include <sys/sysmacros.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070034#include <unistd.h>
35
Michael Wrightd02c5b62014-02-10 15:10:22 -080036#define LOG_TAG "EventHub"
37
38// #define LOG_NDEBUG 0
Kim Low03ea0352020-11-06 12:45:07 -080039#include <android-base/file.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080040#include <android-base/stringprintf.h>
Chris Yed3fef462021-03-07 17:10:08 -080041#include <android-base/strings.h>
Philip Quinn39b81682019-01-09 22:20:39 -080042#include <cutils/properties.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080043#include <ftl/enum.h>
Chris Ye8594e192020-07-14 10:34:06 -070044#include <input/KeyCharacterMap.h>
45#include <input/KeyLayoutMap.h>
46#include <input/VirtualKeyMap.h>
Dan Albert677d87e2014-06-16 17:31:28 -070047#include <openssl/sha.h>
Chris Yed3fef462021-03-07 17:10:08 -080048#include <statslog.h>
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070049#include <utils/Errors.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080050#include <utils/Log.h>
51#include <utils/Timers.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080052
Chris Ye8594e192020-07-14 10:34:06 -070053#include <filesystem>
Chris Ye3fdbfef2021-01-06 18:45:18 -080054#include <regex>
Prabir Pradhancb42b472022-08-23 16:01:19 +000055#include <utility>
Chris Ye8594e192020-07-14 10:34:06 -070056
57#include "EventHub.h"
Michael Wrightd02c5b62014-02-10 15:10:22 -080058
Michael Wrightd02c5b62014-02-10 15:10:22 -080059#define INDENT " "
60#define INDENT2 " "
61#define INDENT3 " "
62
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080063using android::base::StringPrintf;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +000064using android::hardware::input::InputDeviceCountryCode;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080065
Michael Wrightd02c5b62014-02-10 15:10:22 -080066namespace android {
67
Dominik Laskowski2f01d772022-03-23 16:01:29 -070068using namespace ftl::flag_operators;
69
Usama Arifb27c8e62021-06-03 16:44:09 +010070static const char* DEVICE_INPUT_PATH = "/dev/input";
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080071// v4l2 devices go directly into /dev
Usama Arifb27c8e62021-06-03 16:44:09 +010072static const char* DEVICE_PATH = "/dev";
Michael Wrightd02c5b62014-02-10 15:10:22 -080073
Chris Ye657c2f02021-05-25 16:24:37 -070074static constexpr size_t OBFUSCATED_LENGTH = 8;
75
Chris Ye87143712020-11-10 05:05:58 +000076static constexpr int32_t FF_STRONG_MAGNITUDE_CHANNEL_IDX = 0;
77static constexpr int32_t FF_WEAK_MAGNITUDE_CHANNEL_IDX = 1;
Chris Ye6393a262020-08-04 19:41:36 -070078
Chris Yee2b1e5c2021-03-10 22:45:12 -080079// Mapping for input battery class node IDs lookup.
80// https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
81static const std::unordered_map<std::string, InputBatteryClass> BATTERY_CLASSES =
82 {{"capacity", InputBatteryClass::CAPACITY},
83 {"capacity_level", InputBatteryClass::CAPACITY_LEVEL},
84 {"status", InputBatteryClass::STATUS}};
85
86// Mapping for input battery class node names lookup.
87// https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
88static const std::unordered_map<InputBatteryClass, std::string> BATTERY_NODES =
89 {{InputBatteryClass::CAPACITY, "capacity"},
90 {InputBatteryClass::CAPACITY_LEVEL, "capacity_level"},
91 {InputBatteryClass::STATUS, "status"}};
92
Kim Low03ea0352020-11-06 12:45:07 -080093// must be kept in sync with definitions in kernel /drivers/power/supply/power_supply_sysfs.c
94static const std::unordered_map<std::string, int32_t> BATTERY_STATUS =
95 {{"Unknown", BATTERY_STATUS_UNKNOWN},
96 {"Charging", BATTERY_STATUS_CHARGING},
97 {"Discharging", BATTERY_STATUS_DISCHARGING},
98 {"Not charging", BATTERY_STATUS_NOT_CHARGING},
99 {"Full", BATTERY_STATUS_FULL}};
100
101// Mapping taken from
102// https://gitlab.freedesktop.org/upower/upower/-/blob/master/src/linux/up-device-supply.c#L484
103static const std::unordered_map<std::string, int32_t> BATTERY_LEVEL = {{"Critical", 5},
104 {"Low", 10},
105 {"Normal", 55},
106 {"High", 70},
107 {"Full", 100},
108 {"Unknown", 50}};
109
Chris Ye3fdbfef2021-01-06 18:45:18 -0800110// Mapping for input led class node names lookup.
111// https://www.kernel.org/doc/html/latest/leds/leds-class.html
112static const std::unordered_map<std::string, InputLightClass> LIGHT_CLASSES =
113 {{"red", InputLightClass::RED},
114 {"green", InputLightClass::GREEN},
115 {"blue", InputLightClass::BLUE},
116 {"global", InputLightClass::GLOBAL},
117 {"brightness", InputLightClass::BRIGHTNESS},
118 {"multi_index", InputLightClass::MULTI_INDEX},
119 {"multi_intensity", InputLightClass::MULTI_INTENSITY},
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000120 {"max_brightness", InputLightClass::MAX_BRIGHTNESS},
121 {"kbd_backlight", InputLightClass::KEYBOARD_BACKLIGHT}};
Chris Ye3fdbfef2021-01-06 18:45:18 -0800122
123// Mapping for input multicolor led class node names.
124// https://www.kernel.org/doc/html/latest/leds/leds-class-multicolor.html
125static const std::unordered_map<InputLightClass, std::string> LIGHT_NODES =
126 {{InputLightClass::BRIGHTNESS, "brightness"},
127 {InputLightClass::MULTI_INDEX, "multi_index"},
128 {InputLightClass::MULTI_INTENSITY, "multi_intensity"}};
129
130// Mapping for light color name and the light color
131const std::unordered_map<std::string, LightColor> LIGHT_COLORS = {{"red", LightColor::RED},
132 {"green", LightColor::GREEN},
133 {"blue", LightColor::BLUE}};
134
Michael Wrightd02c5b62014-02-10 15:10:22 -0800135static inline const char* toString(bool value) {
136 return value ? "true" : "false";
137}
138
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100139static std::string sha1(const std::string& in) {
Dan Albert677d87e2014-06-16 17:31:28 -0700140 SHA_CTX ctx;
141 SHA1_Init(&ctx);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100142 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
Dan Albert677d87e2014-06-16 17:31:28 -0700143 u_char digest[SHA_DIGEST_LENGTH];
144 SHA1_Final(digest, &ctx);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800145
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100146 std::string out;
Dan Albert677d87e2014-06-16 17:31:28 -0700147 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100148 out += StringPrintf("%02x", digest[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800149 }
150 return out;
151}
152
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800153/**
154 * Return true if name matches "v4l-touch*"
155 */
Chris Ye8594e192020-07-14 10:34:06 -0700156static bool isV4lTouchNode(std::string name) {
157 return name.find("v4l-touch") != std::string::npos;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800158}
159
Philip Quinn39b81682019-01-09 22:20:39 -0800160/**
161 * Returns true if V4L devices should be scanned.
162 *
163 * The system property ro.input.video_enabled can be used to control whether
164 * EventHub scans and opens V4L devices. As V4L does not support multiple
165 * clients, EventHub effectively blocks access to these devices when it opens
Siarhei Vishniakou29f88492019-04-05 14:11:43 -0700166 * them.
167 *
168 * Setting this to "false" would prevent any video devices from being discovered and
169 * associated with input devices.
170 *
171 * This property can be used as follows:
172 * 1. To turn off features that are dependent on video device presence.
173 * 2. During testing and development, to allow other clients to read video devices
174 * directly from /dev.
Philip Quinn39b81682019-01-09 22:20:39 -0800175 */
176static bool isV4lScanningEnabled() {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700177 return property_get_bool("ro.input.video_enabled", true /* default_value */);
Philip Quinn39b81682019-01-09 22:20:39 -0800178}
179
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800180static nsecs_t processEventTimestamp(const struct input_event& event) {
181 // Use the time specified in the event instead of the current time
182 // so that downstream code can get more accurate estimates of
183 // event dispatch latency from the time the event is enqueued onto
184 // the evdev client buffer.
185 //
186 // The event's timestamp fortuitously uses the same monotonic clock
187 // time base as the rest of Android. The kernel event device driver
188 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
189 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
190 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
191 // system call that also queries ktime_get_ts().
192
193 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.time.tv_sec) +
194 microseconds_to_nanoseconds(event.time.tv_usec);
195 return inputEventTime;
196}
197
Kim Low03ea0352020-11-06 12:45:07 -0800198/**
Prabir Pradhancb42b472022-08-23 16:01:19 +0000199 * Returns the sysfs root path of the input device.
Kim Low03ea0352020-11-06 12:45:07 -0800200 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800201static std::optional<std::filesystem::path> getSysfsRootPath(const char* devicePath) {
Kim Low03ea0352020-11-06 12:45:07 -0800202 std::error_code errorCode;
203
204 // Stat the device path to get the major and minor number of the character file
205 struct stat statbuf;
206 if (stat(devicePath, &statbuf) == -1) {
207 ALOGE("Could not stat device %s due to error: %s.", devicePath, std::strerror(errno));
Chris Ye3fdbfef2021-01-06 18:45:18 -0800208 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800209 }
210
211 unsigned int major_num = major(statbuf.st_rdev);
212 unsigned int minor_num = minor(statbuf.st_rdev);
213
214 // Realpath "/sys/dev/char/{major}:{minor}" to get the sysfs path to the input event
215 auto sysfsPath = std::filesystem::path("/sys/dev/char/");
216 sysfsPath /= std::to_string(major_num) + ":" + std::to_string(minor_num);
217 sysfsPath = std::filesystem::canonical(sysfsPath, errorCode);
218
219 // Make sure nothing went wrong in call to canonical()
220 if (errorCode) {
221 ALOGW("Could not run filesystem::canonical() due to error %d : %s.", errorCode.value(),
222 errorCode.message().c_str());
Chris Ye3fdbfef2021-01-06 18:45:18 -0800223 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800224 }
225
226 // Continue to go up a directory until we reach a directory named "input"
227 while (sysfsPath != "/" && sysfsPath.filename() != "input") {
228 sysfsPath = sysfsPath.parent_path();
229 }
230
231 // Then go up one more and you will be at the sysfs root of the device
232 sysfsPath = sysfsPath.parent_path();
233
234 // Make sure we didn't reach root path and that directory actually exists
235 if (sysfsPath == "/" || !std::filesystem::exists(sysfsPath, errorCode)) {
236 if (errorCode) {
237 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
238 errorCode.message().c_str());
239 }
240
241 // Not found
Chris Ye3fdbfef2021-01-06 18:45:18 -0800242 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800243 }
244
245 return sysfsPath;
246}
247
248/**
Chris Ye3fdbfef2021-01-06 18:45:18 -0800249 * Returns the list of files under a specified path.
Kim Low03ea0352020-11-06 12:45:07 -0800250 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800251static std::vector<std::filesystem::path> allFilesInPath(const std::filesystem::path& path) {
252 std::vector<std::filesystem::path> nodes;
253 std::error_code errorCode;
254 auto iter = std::filesystem::directory_iterator(path, errorCode);
255 while (!errorCode && iter != std::filesystem::directory_iterator()) {
256 nodes.push_back(iter->path());
257 iter++;
258 }
259 return nodes;
260}
261
262/**
263 * Returns the list of files under a specified directory in a sysfs path.
264 * Example:
265 * findSysfsNodes(sysfsRootPath, SysfsClass::LEDS) will return all led nodes under "leds" directory
266 * in the sysfs path.
267 */
268static std::vector<std::filesystem::path> findSysfsNodes(const std::filesystem::path& sysfsRoot,
269 SysfsClass clazz) {
Dominik Laskowski75788452021-02-09 18:51:25 -0800270 std::string nodeStr = ftl::enum_string(clazz);
Chris Ye3fdbfef2021-01-06 18:45:18 -0800271 std::for_each(nodeStr.begin(), nodeStr.end(),
272 [](char& c) { c = std::tolower(static_cast<unsigned char>(c)); });
273 std::vector<std::filesystem::path> nodes;
274 for (auto path = sysfsRoot; path != "/" && nodes.empty(); path = path.parent_path()) {
275 nodes = allFilesInPath(path / nodeStr);
276 }
277 return nodes;
278}
279
280static std::optional<std::array<LightColor, COLOR_NUM>> getColorIndexArray(
281 std::filesystem::path path) {
282 std::string indexStr;
283 if (!base::ReadFileToString(path, &indexStr)) {
284 return std::nullopt;
285 }
286
287 // Parse the multi color LED index file, refer to kernel docs
288 // leds/leds-class-multicolor.html
289 std::regex indexPattern("(red|green|blue)\\s(red|green|blue)\\s(red|green|blue)[\\n]");
290 std::smatch results;
291 std::array<LightColor, COLOR_NUM> colors;
292 if (!std::regex_match(indexStr, results, indexPattern)) {
293 return std::nullopt;
294 }
295
296 for (size_t i = 1; i < results.size(); i++) {
297 const auto it = LIGHT_COLORS.find(results[i].str());
298 if (it != LIGHT_COLORS.end()) {
299 // intensities.emplace(it->second, 0);
300 colors[i - 1] = it->second;
Kim Low03ea0352020-11-06 12:45:07 -0800301 }
302 }
Chris Ye3fdbfef2021-01-06 18:45:18 -0800303 return colors;
Kim Low03ea0352020-11-06 12:45:07 -0800304}
305
Prabir Pradhancb42b472022-08-23 16:01:19 +0000306/**
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000307 * Read country code information exposed through the sysfs path.
308 */
309static InputDeviceCountryCode readCountryCodeLocked(const std::filesystem::path& sysfsRootPath) {
310 // Check the sysfs root path
311 int hidCountryCode = static_cast<int>(InputDeviceCountryCode::INVALID);
312 std::string str;
313 if (base::ReadFileToString(sysfsRootPath / "country", &str)) {
314 hidCountryCode = std::stoi(str, nullptr, 16);
315 LOG_ALWAYS_FATAL_IF(hidCountryCode > 35 || hidCountryCode < 0,
316 "HID country code should be in range [0, 35]. Found country code "
317 "to be %d",
318 hidCountryCode);
319 }
320
321 return static_cast<InputDeviceCountryCode>(hidCountryCode);
322}
323
324/**
Prabir Pradhancb42b472022-08-23 16:01:19 +0000325 * Read information about batteries exposed through the sysfs path.
326 */
327static std::unordered_map<int32_t /*batteryId*/, RawBatteryInfo> readBatteryConfiguration(
328 const std::filesystem::path& sysfsRootPath) {
329 std::unordered_map<int32_t, RawBatteryInfo> batteryInfos;
330 int32_t nextBatteryId = 0;
331 // Check if device has any battery.
332 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::POWER_SUPPLY);
333 for (const auto& nodePath : paths) {
334 RawBatteryInfo info;
335 info.id = ++nextBatteryId;
336 info.path = nodePath;
337 info.name = nodePath.filename();
338
339 // Scan the path for all the files
340 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
341 const auto& files = allFilesInPath(nodePath);
342 for (const auto& file : files) {
343 const auto it = BATTERY_CLASSES.find(file.filename().string());
344 if (it != BATTERY_CLASSES.end()) {
345 info.flags |= it->second;
346 }
347 }
348 batteryInfos.insert_or_assign(info.id, info);
349 ALOGD("configureBatteryLocked rawBatteryId %d name %s", info.id, info.name.c_str());
350 }
351 return batteryInfos;
352}
353
354/**
355 * Read information about lights exposed through the sysfs path.
356 */
357static std::unordered_map<int32_t /*lightId*/, RawLightInfo> readLightsConfiguration(
358 const std::filesystem::path& sysfsRootPath) {
359 std::unordered_map<int32_t, RawLightInfo> lightInfos;
360 int32_t nextLightId = 0;
361 // Check if device has any lights.
362 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::LEDS);
363 for (const auto& nodePath : paths) {
364 RawLightInfo info;
365 info.id = ++nextLightId;
366 info.path = nodePath;
367 info.name = nodePath.filename();
368 info.maxBrightness = std::nullopt;
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000369
370 // Light name should follow the naming pattern <name>:<color>:<function>
371 // Refer kernel docs /leds/leds-class.html for valid supported LED names.
372 std::regex indexPattern("([a-zA-Z0-9_.:]*:)?([a-zA-Z0-9_.]*):([a-zA-Z0-9_.]*)");
373 std::smatch results;
374
375 if (std::regex_match(info.name, results, indexPattern)) {
376 // regex_match will return full match at index 0 and <name> at index 1. For RawLightInfo
377 // we only care about sections <color> and <function> which will be at index 2 and 3.
378 for (int i = 2; i <= 3; i++) {
379 const auto it = LIGHT_CLASSES.find(results.str(i));
380 if (it != LIGHT_CLASSES.end()) {
381 info.flags |= it->second;
382 }
Prabir Pradhancb42b472022-08-23 16:01:19 +0000383 }
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000384
385 // Set name of the raw light to <function> which represents playerIDs for LEDs that
386 // turn on/off based on the current player ID (Refer to PeripheralController.cpp for
387 // player ID logic)
388 info.name = results.str(3);
Prabir Pradhancb42b472022-08-23 16:01:19 +0000389 }
390 // Scan the path for all the files
391 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
392 const auto& files = allFilesInPath(nodePath);
393 for (const auto& file : files) {
394 const auto it = LIGHT_CLASSES.find(file.filename().string());
395 if (it != LIGHT_CLASSES.end()) {
396 info.flags |= it->second;
397 // If the node has maximum brightness, read it
398 if (it->second == InputLightClass::MAX_BRIGHTNESS) {
399 std::string str;
400 if (base::ReadFileToString(file, &str)) {
401 info.maxBrightness = std::stoi(str);
402 }
403 }
404 }
405 }
406 lightInfos.insert_or_assign(info.id, info);
407 ALOGD("configureLightsLocked rawLightId %d name %s", info.id, info.name.c_str());
408 }
409 return lightInfos;
410}
411
Michael Wrightd02c5b62014-02-10 15:10:22 -0800412// --- Global Functions ---
413
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700414ftl::Flags<InputDeviceClass> getAbsAxisUsage(int32_t axis,
415 ftl::Flags<InputDeviceClass> deviceClasses) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800416 // Touch devices get dibs on touch-related axes.
Chris Ye1b0c7342020-07-28 21:57:03 -0700417 if (deviceClasses.test(InputDeviceClass::TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800418 switch (axis) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700419 case ABS_X:
420 case ABS_Y:
421 case ABS_PRESSURE:
422 case ABS_TOOL_WIDTH:
423 case ABS_DISTANCE:
424 case ABS_TILT_X:
425 case ABS_TILT_Y:
426 case ABS_MT_SLOT:
427 case ABS_MT_TOUCH_MAJOR:
428 case ABS_MT_TOUCH_MINOR:
429 case ABS_MT_WIDTH_MAJOR:
430 case ABS_MT_WIDTH_MINOR:
431 case ABS_MT_ORIENTATION:
432 case ABS_MT_POSITION_X:
433 case ABS_MT_POSITION_Y:
434 case ABS_MT_TOOL_TYPE:
435 case ABS_MT_BLOB_ID:
436 case ABS_MT_TRACKING_ID:
437 case ABS_MT_PRESSURE:
438 case ABS_MT_DISTANCE:
Chris Ye1b0c7342020-07-28 21:57:03 -0700439 return InputDeviceClass::TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800440 }
441 }
442
Chris Yef59a2f42020-10-16 12:55:26 -0700443 if (deviceClasses.test(InputDeviceClass::SENSOR)) {
444 switch (axis) {
445 case ABS_X:
446 case ABS_Y:
447 case ABS_Z:
448 case ABS_RX:
449 case ABS_RY:
450 case ABS_RZ:
451 return InputDeviceClass::SENSOR;
452 }
453 }
454
Michael Wright842500e2015-03-13 17:32:02 -0700455 // External stylus gets the pressure axis
Chris Ye1b0c7342020-07-28 21:57:03 -0700456 if (deviceClasses.test(InputDeviceClass::EXTERNAL_STYLUS)) {
Michael Wright842500e2015-03-13 17:32:02 -0700457 if (axis == ABS_PRESSURE) {
Chris Ye1b0c7342020-07-28 21:57:03 -0700458 return InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -0700459 }
460 }
461
Michael Wrightd02c5b62014-02-10 15:10:22 -0800462 // Joystick devices get the rest.
Chris Ye1b0c7342020-07-28 21:57:03 -0700463 return deviceClasses & InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800464}
465
466// --- EventHub::Device ---
467
Prabir Pradhancb42b472022-08-23 16:01:19 +0000468EventHub::Device::Device(int fd, int32_t id, std::string path, InputDeviceIdentifier identifier,
469 std::shared_ptr<const AssociatedDevice> assocDev)
Chris Ye989bb932020-07-04 16:18:59 -0700470 : fd(fd),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700471 id(id),
Prabir Pradhancb42b472022-08-23 16:01:19 +0000472 path(std::move(path)),
473 identifier(std::move(identifier)),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700474 classes(0),
475 configuration(nullptr),
476 virtualKeyMap(nullptr),
477 ffEffectPlaying(false),
478 ffEffectId(-1),
Prabir Pradhancb42b472022-08-23 16:01:19 +0000479 associatedDevice(std::move(assocDev)),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700480 controllerNumber(0),
481 enabled(true),
Chris Ye66fbac32020-07-06 20:36:43 -0700482 isVirtual(fd < 0) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800483
484EventHub::Device::~Device() {
485 close();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800486}
487
488void EventHub::Device::close() {
489 if (fd >= 0) {
490 ::close(fd);
491 fd = -1;
492 }
493}
494
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700495status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100496 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700497 if (fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100498 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700499 return -errno;
500 }
501 enabled = true;
502 return OK;
503}
504
505status_t EventHub::Device::disable() {
506 close();
507 enabled = false;
508 return OK;
509}
510
Chris Ye989bb932020-07-04 16:18:59 -0700511bool EventHub::Device::hasValidFd() const {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700512 return !isVirtual && enabled;
513}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800514
Chris Ye3a1e4462020-08-12 10:13:15 -0700515const std::shared_ptr<KeyCharacterMap> EventHub::Device::getKeyCharacterMap() const {
Chris Ye989bb932020-07-04 16:18:59 -0700516 return keyMap.keyCharacterMap;
517}
518
519template <std::size_t N>
520status_t EventHub::Device::readDeviceBitMask(unsigned long ioctlCode, BitArray<N>& bitArray) {
521 if (!hasValidFd()) {
522 return BAD_VALUE;
523 }
524 if ((_IOC_SIZE(ioctlCode) == 0)) {
525 ioctlCode |= _IOC(0, 0, 0, bitArray.bytes());
526 }
527
528 typename BitArray<N>::Buffer buffer;
529 status_t ret = ioctl(fd, ioctlCode, buffer.data());
530 bitArray.loadFromBuffer(buffer);
531 return ret;
532}
533
534void EventHub::Device::configureFd() {
535 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
536 if (classes.test(InputDeviceClass::KEYBOARD)) {
537 // Disable kernel key repeat since we handle it ourselves
538 unsigned int repeatRate[] = {0, 0};
539 if (ioctl(fd, EVIOCSREP, repeatRate)) {
540 ALOGW("Unable to disable kernel key repeat for %s: %s", path.c_str(), strerror(errno));
541 }
542 }
543
544 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
545 // associated with input events. This is important because the input system
546 // uses the timestamps extensively and assumes they were recorded using the monotonic
547 // clock.
548 int clockId = CLOCK_MONOTONIC;
Chris Yef59a2f42020-10-16 12:55:26 -0700549 if (classes.test(InputDeviceClass::SENSOR)) {
550 // Each new sensor event should use the same time base as
551 // SystemClock.elapsedRealtimeNanos().
552 clockId = CLOCK_BOOTTIME;
553 }
Chris Ye989bb932020-07-04 16:18:59 -0700554 bool usingClockIoctl = !ioctl(fd, EVIOCSCLOCKID, &clockId);
555 ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
556}
557
558bool EventHub::Device::hasKeycodeLocked(int keycode) const {
559 if (!keyMap.haveKeyLayout()) {
560 return false;
561 }
562
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700563 std::vector<int32_t> scanCodes = keyMap.keyLayoutMap->findScanCodesForKey(keycode);
Chris Ye989bb932020-07-04 16:18:59 -0700564 const size_t N = scanCodes.size();
565 for (size_t i = 0; i < N && i <= KEY_MAX; i++) {
566 int32_t sc = scanCodes[i];
567 if (sc >= 0 && sc <= KEY_MAX && keyBitmask.test(sc)) {
568 return true;
569 }
570 }
571
572 return false;
573}
574
575void EventHub::Device::loadConfigurationLocked() {
576 configurationFile =
577 getInputDeviceConfigurationFilePathByDeviceIdentifier(identifier,
578 InputDeviceConfigurationFileType::
579 CONFIGURATION);
580 if (configurationFile.empty()) {
581 ALOGD("No input device configuration file found for device '%s'.", identifier.name.c_str());
582 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500583 android::base::Result<std::unique_ptr<PropertyMap>> propertyMap =
584 PropertyMap::load(configurationFile.c_str());
585 if (!propertyMap.ok()) {
Chris Ye989bb932020-07-04 16:18:59 -0700586 ALOGE("Error loading input device configuration file for device '%s'. "
587 "Using default configuration.",
588 identifier.name.c_str());
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500589 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500590 configuration = std::move(*propertyMap);
Chris Ye989bb932020-07-04 16:18:59 -0700591 }
592 }
593}
594
595bool EventHub::Device::loadVirtualKeyMapLocked() {
596 // The virtual key map is supplied by the kernel as a system board property file.
597 std::string propPath = "/sys/board_properties/virtualkeys.";
598 propPath += identifier.getCanonicalName();
599 if (access(propPath.c_str(), R_OK)) {
600 return false;
601 }
602 virtualKeyMap = VirtualKeyMap::load(propPath);
603 return virtualKeyMap != nullptr;
604}
605
606status_t EventHub::Device::loadKeyMapLocked() {
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500607 return keyMap.load(identifier, configuration.get());
Chris Ye989bb932020-07-04 16:18:59 -0700608}
609
610bool EventHub::Device::isExternalDeviceLocked() {
611 if (configuration) {
612 bool value;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700613 if (configuration->tryGetProperty("device.internal", value)) {
Chris Ye989bb932020-07-04 16:18:59 -0700614 return !value;
615 }
616 }
617 return identifier.bus == BUS_USB || identifier.bus == BUS_BLUETOOTH;
618}
619
620bool EventHub::Device::deviceHasMicLocked() {
621 if (configuration) {
622 bool value;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700623 if (configuration->tryGetProperty("audio.mic", value)) {
Chris Ye989bb932020-07-04 16:18:59 -0700624 return value;
625 }
626 }
627 return false;
628}
629
630void EventHub::Device::setLedStateLocked(int32_t led, bool on) {
631 int32_t sc;
632 if (hasValidFd() && mapLed(led, &sc) != NAME_NOT_FOUND) {
633 struct input_event ev;
634 ev.time.tv_sec = 0;
635 ev.time.tv_usec = 0;
636 ev.type = EV_LED;
637 ev.code = sc;
638 ev.value = on ? 1 : 0;
639
640 ssize_t nWrite;
641 do {
642 nWrite = write(fd, &ev, sizeof(struct input_event));
643 } while (nWrite == -1 && errno == EINTR);
644 }
645}
646
647void EventHub::Device::setLedForControllerLocked() {
648 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
649 setLedStateLocked(ALED_CONTROLLER_1 + i, controllerNumber == i + 1);
650 }
651}
652
653status_t EventHub::Device::mapLed(int32_t led, int32_t* outScanCode) const {
654 if (!keyMap.haveKeyLayout()) {
655 return NAME_NOT_FOUND;
656 }
657
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700658 std::optional<int32_t> scanCode = keyMap.keyLayoutMap->findScanCodeForLed(led);
659 if (scanCode.has_value()) {
660 if (*scanCode >= 0 && *scanCode <= LED_MAX && ledBitmask.test(*scanCode)) {
661 *outScanCode = *scanCode;
Chris Ye989bb932020-07-04 16:18:59 -0700662 return NO_ERROR;
663 }
664 }
665 return NAME_NOT_FOUND;
666}
667
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100668/**
669 * Get the capabilities for the current process.
670 * Crashes the system if unable to create / check / destroy the capabilities object.
671 */
672class Capabilities final {
673public:
674 explicit Capabilities() {
675 mCaps = cap_get_proc();
676 LOG_ALWAYS_FATAL_IF(mCaps == nullptr, "Could not get capabilities of the current process");
677 }
678
679 /**
680 * Check whether the current process has a specific capability
681 * in the set of effective capabilities.
682 * Return CAP_SET if the process has the requested capability
683 * Return CAP_CLEAR otherwise.
684 */
685 cap_flag_value_t checkEffectiveCapability(cap_value_t capability) {
686 cap_flag_value_t value;
687 const int result = cap_get_flag(mCaps, capability, CAP_EFFECTIVE, &value);
688 LOG_ALWAYS_FATAL_IF(result == -1, "Could not obtain the requested capability");
689 return value;
690 }
691
692 ~Capabilities() {
693 const int result = cap_free(mCaps);
694 LOG_ALWAYS_FATAL_IF(result == -1, "Could not release the capabilities structure");
695 }
696
697private:
698 cap_t mCaps;
699};
700
701static void ensureProcessCanBlockSuspend() {
702 Capabilities capabilities;
703 const bool canBlockSuspend =
704 capabilities.checkEffectiveCapability(CAP_BLOCK_SUSPEND) == CAP_SET;
705 LOG_ALWAYS_FATAL_IF(!canBlockSuspend,
706 "Input must be able to block suspend to properly process events");
707}
708
Michael Wrightd02c5b62014-02-10 15:10:22 -0800709// --- EventHub ---
710
Michael Wrightd02c5b62014-02-10 15:10:22 -0800711const int EventHub::EPOLL_MAX_EVENTS;
712
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700713EventHub::EventHub(void)
714 : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
715 mNextDeviceId(1),
716 mControllerNumbers(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800717 mNeedToSendFinishedDeviceScan(false),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700718 mNeedToReopenDevices(false),
719 mNeedToScanDevices(true),
720 mPendingEventCount(0),
721 mPendingEventIndex(0),
722 mPendingINotify(false) {
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100723 ensureProcessCanBlockSuspend();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800724
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800725 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800726 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800727
Michael Wright8e9a8562022-02-09 13:44:29 +0000728 mINotifyFd = inotify_init1(IN_CLOEXEC);
Prabir Pradhan952e65b2022-06-23 17:49:55 +0000729 LOG_ALWAYS_FATAL_IF(mINotifyFd < 0, "Could not create inotify instance: %s", strerror(errno));
Usama Arifb27c8e62021-06-03 16:44:09 +0100730
731 std::error_code errorCode;
732 bool isDeviceInotifyAdded = false;
733 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
734 addDeviceInputInotify();
Philip Quinn39b81682019-01-09 22:20:39 -0800735 } else {
Usama Arifb27c8e62021-06-03 16:44:09 +0100736 addDeviceInotify();
737 isDeviceInotifyAdded = true;
738 if (errorCode) {
739 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
740 errorCode.message().c_str());
741 }
742 }
743
744 if (isV4lScanningEnabled() && !isDeviceInotifyAdded) {
745 addDeviceInotify();
746 } else {
Philip Quinn39b81682019-01-09 22:20:39 -0800747 ALOGI("Video device scanning disabled");
748 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800749
Siarhei Vishniakou2d0e9482019-09-24 12:52:47 +0100750 struct epoll_event eventItem = {};
751 eventItem.events = EPOLLIN | EPOLLWAKEUP;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700752 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800753 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800754 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
755
756 int wakeFds[2];
Michael Wright8e9a8562022-02-09 13:44:29 +0000757 result = pipe2(wakeFds, O_CLOEXEC);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800758 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
759
760 mWakeReadPipeFd = wakeFds[0];
761 mWakeWritePipeFd = wakeFds[1];
762
763 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
764 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700765 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800766
767 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
768 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700769 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800770
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700771 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800772 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
773 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700774 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800775}
776
777EventHub::~EventHub(void) {
778 closeAllDevicesLocked();
779
Michael Wrightd02c5b62014-02-10 15:10:22 -0800780 ::close(mEpollFd);
781 ::close(mINotifyFd);
782 ::close(mWakeReadPipeFd);
783 ::close(mWakeWritePipeFd);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800784}
785
Usama Arifb27c8e62021-06-03 16:44:09 +0100786/**
787 * On devices that don't have any input devices (like some development boards), the /dev/input
788 * directory will be absent. However, the user may still plug in an input device at a later time.
789 * Add watch for contents of /dev/input only when /dev/input appears.
790 */
791void EventHub::addDeviceInputInotify() {
792 mDeviceInputWd = inotify_add_watch(mINotifyFd, DEVICE_INPUT_PATH, IN_DELETE | IN_CREATE);
793 LOG_ALWAYS_FATAL_IF(mDeviceInputWd < 0, "Could not register INotify for %s: %s",
794 DEVICE_INPUT_PATH, strerror(errno));
795}
796
797void EventHub::addDeviceInotify() {
798 mDeviceWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
799 LOG_ALWAYS_FATAL_IF(mDeviceWd < 0, "Could not register INotify for %s: %s", DEVICE_PATH,
800 strerror(errno));
801}
802
Michael Wrightd02c5b62014-02-10 15:10:22 -0800803InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000804 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800805 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700806 return device != nullptr ? device->identifier : InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800807}
808
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700809ftl::Flags<InputDeviceClass> EventHub::getDeviceClasses(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000810 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800811 Device* device = getDeviceLocked(deviceId);
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700812 return device != nullptr ? device->classes : ftl::Flags<InputDeviceClass>(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800813}
814
815int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000816 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800817 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700818 return device != nullptr ? device->controllerNumber : 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800819}
820
821void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
Chris Ye87143712020-11-10 05:05:58 +0000822 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800823 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700824 if (device != nullptr && device->configuration) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800825 *outConfiguration = *device->configuration;
826 } else {
827 outConfiguration->clear();
828 }
829}
830
831status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700832 RawAbsoluteAxisInfo* outAxisInfo) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800833 outAxisInfo->clear();
834
835 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000836 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800837
838 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700839 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800840 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700841 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
842 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
843 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800844 return -errno;
845 }
846
847 if (info.minimum != info.maximum) {
848 outAxisInfo->valid = true;
849 outAxisInfo->minValue = info.minimum;
850 outAxisInfo->maxValue = info.maximum;
851 outAxisInfo->flat = info.flat;
852 outAxisInfo->fuzz = info.fuzz;
853 outAxisInfo->resolution = info.resolution;
854 }
855 return OK;
856 }
857 }
858 return -1;
859}
860
861bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
862 if (axis >= 0 && axis <= REL_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000863 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800864 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700865 return device != nullptr ? device->relBitmask.test(axis) : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800866 }
867 return false;
868}
869
870bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
Chris Ye87143712020-11-10 05:05:58 +0000871 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800872
Chris Ye989bb932020-07-04 16:18:59 -0700873 Device* device = getDeviceLocked(deviceId);
874 return property >= 0 && property <= INPUT_PROP_MAX && device != nullptr
875 ? device->propBitmask.test(property)
876 : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800877}
878
Chris Yef59a2f42020-10-16 12:55:26 -0700879bool EventHub::hasMscEvent(int32_t deviceId, int mscEvent) const {
880 std::scoped_lock _l(mLock);
881
882 Device* device = getDeviceLocked(deviceId);
883 return mscEvent >= 0 && mscEvent <= MSC_MAX && device != nullptr
884 ? device->mscBitmask.test(mscEvent)
885 : false;
886}
887
Michael Wrightd02c5b62014-02-10 15:10:22 -0800888int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
889 if (scanCode >= 0 && scanCode <= KEY_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000890 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800891
892 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700893 if (device != nullptr && device->hasValidFd() && device->keyBitmask.test(scanCode)) {
894 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
895 return device->keyState.test(scanCode) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800896 }
897 }
898 }
899 return AKEY_STATE_UNKNOWN;
900}
901
902int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
Chris Ye87143712020-11-10 05:05:58 +0000903 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904
905 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700906 if (device != nullptr && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700907 std::vector<int32_t> scanCodes = device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800908 if (scanCodes.size() != 0) {
Chris Ye66fbac32020-07-06 20:36:43 -0700909 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800910 for (size_t i = 0; i < scanCodes.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800911 int32_t sc = scanCodes[i];
Chris Ye66fbac32020-07-06 20:36:43 -0700912 if (sc >= 0 && sc <= KEY_MAX && device->keyState.test(sc)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800913 return AKEY_STATE_DOWN;
914 }
915 }
916 return AKEY_STATE_UP;
917 }
918 }
919 }
920 return AKEY_STATE_UNKNOWN;
921}
922
Philip Junker4af3b3d2021-12-14 10:36:55 +0100923int32_t EventHub::getKeyCodeForKeyLocation(int32_t deviceId, int32_t locationKeyCode) const {
924 std::scoped_lock _l(mLock);
925
926 Device* device = getDeviceLocked(deviceId);
927 if (device == nullptr || !device->hasValidFd() || device->keyMap.keyCharacterMap == nullptr ||
928 device->keyMap.keyLayoutMap == nullptr) {
929 return AKEYCODE_UNKNOWN;
930 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700931 std::vector<int32_t> scanCodes =
932 device->keyMap.keyLayoutMap->findScanCodesForKey(locationKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +0100933 if (scanCodes.empty()) {
934 ALOGW("Failed to get key code for key location: no scan code maps to key code %d for input"
935 "device %d",
936 locationKeyCode, deviceId);
937 return AKEYCODE_UNKNOWN;
938 }
939 if (scanCodes.size() > 1) {
940 ALOGW("Multiple scan codes map to the same key code %d, returning only the first match",
941 locationKeyCode);
942 }
943 int32_t outKeyCode;
944 status_t mapKeyRes =
945 device->getKeyCharacterMap()->mapKey(scanCodes[0], 0 /*usageCode*/, &outKeyCode);
946 switch (mapKeyRes) {
947 case OK:
948 return outKeyCode;
949 case NAME_NOT_FOUND:
950 // key character map doesn't re-map this scanCode, hence the keyCode remains the same
951 return locationKeyCode;
952 default:
953 ALOGW("Failed to get key code for key location: Key character map returned error %s",
954 statusToString(mapKeyRes).c_str());
955 return AKEYCODE_UNKNOWN;
956 }
957}
958
Michael Wrightd02c5b62014-02-10 15:10:22 -0800959int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
960 if (sw >= 0 && sw <= SW_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000961 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800962
963 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700964 if (device != nullptr && device->hasValidFd() && device->swBitmask.test(sw)) {
965 if (device->readDeviceBitMask(EVIOCGSW(0), device->swState) >= 0) {
966 return device->swState.test(sw) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800967 }
968 }
969 }
970 return AKEY_STATE_UNKNOWN;
971}
972
973status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
974 *outValue = 0;
975
976 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000977 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800978
979 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700980 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800981 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700982 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
983 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
984 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800985 return -errno;
986 }
987
988 *outValue = info.value;
989 return OK;
990 }
991 }
992 return -1;
993}
994
Siarhei Vishniakou74007942022-06-13 13:57:47 -0700995bool EventHub::markSupportedKeyCodes(int32_t deviceId, const std::vector<int32_t>& keyCodes,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700996 uint8_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +0000997 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800998
999 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001000 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001001 for (size_t codeIndex = 0; codeIndex < keyCodes.size(); codeIndex++) {
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001002 std::vector<int32_t> scanCodes =
1003 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCodes[codeIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001004
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001005 // check the possible scan codes identified by the layout map against the
1006 // map of codes actually emitted by the driver
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001007 for (const int32_t scanCode : scanCodes) {
1008 if (device->keyBitmask.test(scanCode)) {
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001009 outFlags[codeIndex] = 1;
1010 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001011 }
1012 }
1013 }
1014 return true;
1015 }
1016 return false;
1017}
1018
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001019status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
1020 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +00001021 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001022 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001023 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001024
Chris Ye66fbac32020-07-06 20:36:43 -07001025 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026 // Check the key character map first.
Chris Ye3a1e4462020-08-12 10:13:15 -07001027 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
1028 if (kcm) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001029 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
1030 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001031 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001032 }
1033 }
1034
1035 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001036 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -08001037 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001038 status = NO_ERROR;
1039 }
1040 }
1041
1042 if (status == NO_ERROR) {
Chris Ye3a1e4462020-08-12 10:13:15 -07001043 if (kcm) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001044 kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState);
1045 } else {
1046 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001047 }
1048 }
1049 }
1050
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001051 if (status != NO_ERROR) {
1052 *outKeycode = 0;
1053 *outFlags = 0;
1054 *outMetaState = metaState;
1055 }
1056
1057 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001058}
1059
1060status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
Chris Ye87143712020-11-10 05:05:58 +00001061 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001062 Device* device = getDeviceLocked(deviceId);
1063
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001064 if (device == nullptr || !device->keyMap.haveKeyLayout()) {
1065 return NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001066 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001067 std::optional<AxisInfo> info = device->keyMap.keyLayoutMap->mapAxis(scanCode);
1068 if (!info.has_value()) {
1069 return NAME_NOT_FOUND;
1070 }
1071 *outAxisInfo = *info;
1072 return NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001073}
1074
Chris Yef59a2f42020-10-16 12:55:26 -07001075base::Result<std::pair<InputDeviceSensorType, int32_t>> EventHub::mapSensor(int32_t deviceId,
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001076 int32_t absCode) const {
Chris Yef59a2f42020-10-16 12:55:26 -07001077 std::scoped_lock _l(mLock);
1078 Device* device = getDeviceLocked(deviceId);
1079
1080 if (device != nullptr && device->keyMap.haveKeyLayout()) {
1081 return device->keyMap.keyLayoutMap->mapSensor(absCode);
1082 }
1083 return Errorf("Device not found or device has no key layout.");
1084}
1085
Chris Yee2b1e5c2021-03-10 22:45:12 -08001086// Gets the battery info map from battery ID to RawBatteryInfo of the miscellaneous device
1087// associated with the device ID. Returns an empty map if no miscellaneous device found.
1088const std::unordered_map<int32_t, RawBatteryInfo>& EventHub::getBatteryInfoLocked(
1089 int32_t deviceId) const {
1090 static const std::unordered_map<int32_t, RawBatteryInfo> EMPTY_BATTERY_INFO = {};
1091 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001092 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001093 return EMPTY_BATTERY_INFO;
1094 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001095 return device->associatedDevice->batteryInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001096}
1097
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001098std::vector<int32_t> EventHub::getRawBatteryIds(int32_t deviceId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001099 std::scoped_lock _l(mLock);
1100 std::vector<int32_t> batteryIds;
1101
Prabir Pradhan51894782022-08-23 16:29:10 +00001102 for (const auto& [id, info] : getBatteryInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001103 batteryIds.push_back(id);
1104 }
1105
1106 return batteryIds;
1107}
1108
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001109std::optional<RawBatteryInfo> EventHub::getRawBatteryInfo(int32_t deviceId,
1110 int32_t batteryId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001111 std::scoped_lock _l(mLock);
1112
1113 const auto infos = getBatteryInfoLocked(deviceId);
1114
1115 auto it = infos.find(batteryId);
1116 if (it != infos.end()) {
1117 return it->second;
1118 }
1119
1120 return std::nullopt;
1121}
1122
1123// Gets the light info map from light ID to RawLightInfo of the miscellaneous device associated
Prabir Pradhan51894782022-08-23 16:29:10 +00001124// with the device ID. Returns an empty map if no miscellaneous device found.
Chris Yee2b1e5c2021-03-10 22:45:12 -08001125const std::unordered_map<int32_t, RawLightInfo>& EventHub::getLightInfoLocked(
1126 int32_t deviceId) const {
1127 static const std::unordered_map<int32_t, RawLightInfo> EMPTY_LIGHT_INFO = {};
1128 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001129 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001130 return EMPTY_LIGHT_INFO;
1131 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001132 return device->associatedDevice->lightInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001133}
1134
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001135std::vector<int32_t> EventHub::getRawLightIds(int32_t deviceId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001136 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001137 std::vector<int32_t> lightIds;
1138
Prabir Pradhan51894782022-08-23 16:29:10 +00001139 for (const auto& [id, info] : getLightInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001140 lightIds.push_back(id);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001141 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001142
Chris Ye3fdbfef2021-01-06 18:45:18 -08001143 return lightIds;
1144}
1145
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001146std::optional<RawLightInfo> EventHub::getRawLightInfo(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001147 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001148
Chris Yee2b1e5c2021-03-10 22:45:12 -08001149 const auto infos = getLightInfoLocked(deviceId);
1150
1151 auto it = infos.find(lightId);
1152 if (it != infos.end()) {
1153 return it->second;
Chris Ye3fdbfef2021-01-06 18:45:18 -08001154 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001155
Chris Ye3fdbfef2021-01-06 18:45:18 -08001156 return std::nullopt;
1157}
1158
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001159std::optional<int32_t> EventHub::getLightBrightness(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001160 std::scoped_lock _l(mLock);
1161
Chris Yee2b1e5c2021-03-10 22:45:12 -08001162 const auto infos = getLightInfoLocked(deviceId);
1163 auto it = infos.find(lightId);
1164 if (it == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001165 return std::nullopt;
1166 }
1167 std::string buffer;
1168 if (!base::ReadFileToString(it->second.path / LIGHT_NODES.at(InputLightClass::BRIGHTNESS),
1169 &buffer)) {
1170 return std::nullopt;
1171 }
1172 return std::stoi(buffer);
1173}
1174
1175std::optional<std::unordered_map<LightColor, int32_t>> EventHub::getLightIntensities(
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001176 int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001177 std::scoped_lock _l(mLock);
1178
Chris Yee2b1e5c2021-03-10 22:45:12 -08001179 const auto infos = getLightInfoLocked(deviceId);
1180 auto lightIt = infos.find(lightId);
1181 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001182 return std::nullopt;
1183 }
1184
1185 auto ret =
1186 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1187
1188 if (!ret.has_value()) {
1189 return std::nullopt;
1190 }
1191 std::array<LightColor, COLOR_NUM> colors = ret.value();
1192
1193 std::string intensityStr;
1194 if (!base::ReadFileToString(lightIt->second.path /
1195 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY),
1196 &intensityStr)) {
1197 return std::nullopt;
1198 }
1199
1200 // Intensity node outputs 3 color values
1201 std::regex intensityPattern("([0-9]+)\\s([0-9]+)\\s([0-9]+)[\\n]");
1202 std::smatch results;
1203
1204 if (!std::regex_match(intensityStr, results, intensityPattern)) {
1205 return std::nullopt;
1206 }
1207 std::unordered_map<LightColor, int32_t> intensities;
1208 for (size_t i = 1; i < results.size(); i++) {
1209 int value = std::stoi(results[i].str());
1210 intensities.emplace(colors[i - 1], value);
1211 }
1212 return intensities;
1213}
1214
1215void EventHub::setLightBrightness(int32_t deviceId, int32_t lightId, int32_t brightness) {
1216 std::scoped_lock _l(mLock);
1217
Chris Yee2b1e5c2021-03-10 22:45:12 -08001218 const auto infos = getLightInfoLocked(deviceId);
1219 auto lightIt = infos.find(lightId);
1220 if (lightIt == infos.end()) {
1221 ALOGE("%s lightId %d not found ", __func__, lightId);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001222 return;
1223 }
1224
1225 if (!base::WriteStringToFile(std::to_string(brightness),
1226 lightIt->second.path /
1227 LIGHT_NODES.at(InputLightClass::BRIGHTNESS))) {
1228 ALOGE("Can not write to file, error: %s", strerror(errno));
1229 }
1230}
1231
1232void EventHub::setLightIntensities(int32_t deviceId, int32_t lightId,
1233 std::unordered_map<LightColor, int32_t> intensities) {
1234 std::scoped_lock _l(mLock);
1235
Chris Yee2b1e5c2021-03-10 22:45:12 -08001236 const auto infos = getLightInfoLocked(deviceId);
1237 auto lightIt = infos.find(lightId);
1238 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001239 ALOGE("Light Id %d does not exist.", lightId);
1240 return;
1241 }
1242
1243 auto ret =
1244 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1245
1246 if (!ret.has_value()) {
1247 return;
1248 }
1249 std::array<LightColor, COLOR_NUM> colors = ret.value();
1250
1251 std::string rgbStr;
1252 for (size_t i = 0; i < COLOR_NUM; i++) {
1253 auto it = intensities.find(colors[i]);
1254 if (it != intensities.end()) {
1255 rgbStr += std::to_string(it->second);
1256 // Insert space between colors
1257 if (i < COLOR_NUM - 1) {
1258 rgbStr += " ";
1259 }
1260 }
1261 }
1262 // Append new line
1263 rgbStr += "\n";
1264
1265 if (!base::WriteStringToFile(rgbStr,
1266 lightIt->second.path /
1267 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY))) {
1268 ALOGE("Can not write to file, error: %s", strerror(errno));
1269 }
1270}
1271
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001272InputDeviceCountryCode EventHub::getCountryCode(int32_t deviceId) const {
1273 std::scoped_lock _l(mLock);
1274 Device* device = getDeviceLocked(deviceId);
1275 if (device == nullptr || !device->associatedDevice) {
1276 return InputDeviceCountryCode::INVALID;
1277 }
1278 return device->associatedDevice->countryCode;
1279}
1280
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001281void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Chris Ye87143712020-11-10 05:05:58 +00001282 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001283
1284 mExcludedDevices = devices;
1285}
1286
1287bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
Chris Ye87143712020-11-10 05:05:58 +00001288 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001289 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001290 if (device != nullptr && scanCode >= 0 && scanCode <= KEY_MAX) {
1291 return device->keyBitmask.test(scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001292 }
1293 return false;
1294}
1295
Arthur Hungcb40a002021-08-03 14:31:01 +00001296bool EventHub::hasKeyCode(int32_t deviceId, int32_t keyCode) const {
1297 std::scoped_lock _l(mLock);
1298 Device* device = getDeviceLocked(deviceId);
1299 if (device != nullptr) {
1300 return device->hasKeycodeLocked(keyCode);
1301 }
1302 return false;
1303}
1304
Michael Wrightd02c5b62014-02-10 15:10:22 -08001305bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
Chris Ye87143712020-11-10 05:05:58 +00001306 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001307 Device* device = getDeviceLocked(deviceId);
1308 int32_t sc;
Chris Ye989bb932020-07-04 16:18:59 -07001309 if (device != nullptr && device->mapLed(led, &sc) == NO_ERROR) {
Chris Ye66fbac32020-07-06 20:36:43 -07001310 return device->ledBitmask.test(sc);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001311 }
1312 return false;
1313}
1314
1315void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
Chris Ye87143712020-11-10 05:05:58 +00001316 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001317 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -07001318 if (device != nullptr && device->hasValidFd()) {
1319 device->setLedStateLocked(led, on);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001320 }
1321}
1322
1323void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001324 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001325 outVirtualKeys.clear();
1326
Chris Ye87143712020-11-10 05:05:58 +00001327 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001328 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001329 if (device != nullptr && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001330 const std::vector<VirtualKeyDefinition> virtualKeys =
1331 device->virtualKeyMap->getVirtualKeys();
1332 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001333 }
1334}
1335
Chris Ye3a1e4462020-08-12 10:13:15 -07001336const std::shared_ptr<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001337 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001338 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001339 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001340 return device->getKeyCharacterMap();
1341 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001342 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001343}
1344
Chris Ye3a1e4462020-08-12 10:13:15 -07001345bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, std::shared_ptr<KeyCharacterMap> map) {
Chris Ye87143712020-11-10 05:05:58 +00001346 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001347 Device* device = getDeviceLocked(deviceId);
Philip Junker90bc9492021-12-10 18:39:42 +01001348 if (device == nullptr || map == nullptr || device->keyMap.keyCharacterMap == nullptr) {
1349 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001350 }
Philip Junker90bc9492021-12-10 18:39:42 +01001351 device->keyMap.keyCharacterMap->combine(*map);
1352 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001353}
1354
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001355static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
1356 std::string rawDescriptor;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001357 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001358 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001359 if (!identifier.uniqueId.empty()) {
1360 rawDescriptor += "uniqueId:";
1361 rawDescriptor += identifier.uniqueId;
Josh Bartel938632f2022-07-19 15:34:22 -05001362 }
1363 if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001364 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001365 }
1366
1367 if (identifier.vendor == 0 && identifier.product == 0) {
1368 // If we don't know the vendor and product id, then the device is probably
1369 // built-in so we need to rely on other information to uniquely identify
1370 // the input device. Usually we try to avoid relying on the device name or
1371 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001372 if (!identifier.name.empty()) {
1373 rawDescriptor += "name:";
1374 rawDescriptor += identifier.name;
1375 } else if (!identifier.location.empty()) {
1376 rawDescriptor += "location:";
1377 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001378 }
1379 }
1380 identifier.descriptor = sha1(rawDescriptor);
1381 return rawDescriptor;
1382}
1383
1384void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
1385 // Compute a device descriptor that uniquely identifies the device.
1386 // The descriptor is assumed to be a stable identifier. Its value should not
1387 // change between reboots, reconnections, firmware updates or new releases
1388 // of Android. In practice we sometimes get devices that cannot be uniquely
1389 // identified. In this case we enforce uniqueness between connected devices.
1390 // Ideally, we also want the descriptor to be short and relatively opaque.
Josh Bartel938632f2022-07-19 15:34:22 -05001391 // Note that we explicitly do not use the path or location for external devices
1392 // as their path or location will change as they are plugged/unplugged or moved
1393 // to different ports. We do fallback to using name and location in the case of
1394 // internal devices which are detected by the vendor and product being 0 in
1395 // generateDescriptor. If two identical descriptors are detected we will fallback
1396 // to using a 'nonce' and incrementing it until the new descriptor no longer has
1397 // a match with any existing descriptors.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001398
1399 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001400 std::string rawDescriptor = generateDescriptor(identifier);
Josh Bartel938632f2022-07-19 15:34:22 -05001401 // Enforce that the generated descriptor is unique.
1402 while (hasDeviceWithDescriptorLocked(identifier.descriptor)) {
1403 identifier.nonce++;
1404 rawDescriptor = generateDescriptor(identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001405 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001406 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001407 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001408}
1409
Prabir Pradhancb42b472022-08-23 16:01:19 +00001410std::shared_ptr<const EventHub::AssociatedDevice> EventHub::obtainAssociatedDeviceLocked(
1411 const std::filesystem::path& devicePath) const {
1412 const std::optional<std::filesystem::path> sysfsRootPathOpt =
1413 getSysfsRootPath(devicePath.c_str());
1414 if (!sysfsRootPathOpt) {
1415 return nullptr;
1416 }
1417
1418 const auto& path = *sysfsRootPathOpt;
Prabir Pradhancb42b472022-08-23 16:01:19 +00001419
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00001420 std::shared_ptr<const AssociatedDevice> associatedDevice = std::make_shared<AssociatedDevice>(
Prabir Pradhancb42b472022-08-23 16:01:19 +00001421 AssociatedDevice{.sysfsRootPath = path,
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001422 .countryCode = readCountryCodeLocked(path),
Prabir Pradhancb42b472022-08-23 16:01:19 +00001423 .batteryInfos = readBatteryConfiguration(path),
1424 .lightInfos = readLightsConfiguration(path)});
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00001425
1426 bool associatedDeviceChanged = false;
1427 for (const auto& [id, dev] : mDevices) {
1428 if (dev->associatedDevice && dev->associatedDevice->sysfsRootPath == path) {
1429 if (*associatedDevice != *dev->associatedDevice) {
1430 associatedDeviceChanged = true;
1431 dev->associatedDevice = associatedDevice;
1432 }
1433 associatedDevice = dev->associatedDevice;
1434 }
1435 }
1436 ALOGI_IF(associatedDeviceChanged,
1437 "The AssociatedDevice changed for path '%s'. Using new AssociatedDevice: %s",
1438 path.c_str(), associatedDevice->dump().c_str());
1439
1440 return associatedDevice;
Prabir Pradhancb42b472022-08-23 16:01:19 +00001441}
1442
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001443void EventHub::vibrate(int32_t deviceId, const VibrationElement& element) {
Chris Ye87143712020-11-10 05:05:58 +00001444 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001445 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001446 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001447 ff_effect effect;
1448 memset(&effect, 0, sizeof(effect));
1449 effect.type = FF_RUMBLE;
1450 effect.id = device->ffEffectId;
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001451 // evdev FF_RUMBLE effect only supports two channels of vibration.
Chris Ye6393a262020-08-04 19:41:36 -07001452 effect.u.rumble.strong_magnitude = element.getMagnitude(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1453 effect.u.rumble.weak_magnitude = element.getMagnitude(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001454 effect.replay.length = element.duration.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001455 effect.replay.delay = 0;
1456 if (ioctl(device->fd, EVIOCSFF, &effect)) {
1457 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001458 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001459 return;
1460 }
1461 device->ffEffectId = effect.id;
1462
1463 struct input_event ev;
1464 ev.time.tv_sec = 0;
1465 ev.time.tv_usec = 0;
1466 ev.type = EV_FF;
1467 ev.code = device->ffEffectId;
1468 ev.value = 1;
1469 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1470 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001471 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001472 return;
1473 }
1474 device->ffEffectPlaying = true;
1475 }
1476}
1477
1478void EventHub::cancelVibrate(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001479 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001481 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001482 if (device->ffEffectPlaying) {
1483 device->ffEffectPlaying = false;
1484
1485 struct input_event ev;
1486 ev.time.tv_sec = 0;
1487 ev.time.tv_usec = 0;
1488 ev.type = EV_FF;
1489 ev.code = device->ffEffectId;
1490 ev.value = 0;
1491 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1492 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001493 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001494 return;
1495 }
1496 }
1497 }
1498}
1499
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001500std::vector<int32_t> EventHub::getVibratorIds(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001501 std::scoped_lock _l(mLock);
1502 std::vector<int32_t> vibrators;
1503 Device* device = getDeviceLocked(deviceId);
1504 if (device != nullptr && device->hasValidFd() &&
1505 device->classes.test(InputDeviceClass::VIBRATOR)) {
1506 vibrators.push_back(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1507 vibrators.push_back(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
1508 }
1509 return vibrators;
1510}
1511
Josh Bartel938632f2022-07-19 15:34:22 -05001512/**
1513 * Checks both mDevices and mOpeningDevices for a device with the descriptor passed.
1514 */
1515bool EventHub::hasDeviceWithDescriptorLocked(const std::string& descriptor) const {
1516 for (const auto& device : mOpeningDevices) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001517 if (descriptor == device->identifier.descriptor) {
Josh Bartel938632f2022-07-19 15:34:22 -05001518 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001519 }
1520 }
Josh Bartel938632f2022-07-19 15:34:22 -05001521
1522 for (const auto& [id, device] : mDevices) {
1523 if (descriptor == device->identifier.descriptor) {
1524 return true;
1525 }
1526 }
1527 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001528}
1529
1530EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001531 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001532 deviceId = mBuiltInKeyboardId;
1533 }
Chris Ye989bb932020-07-04 16:18:59 -07001534 const auto& it = mDevices.find(deviceId);
1535 return it != mDevices.end() ? it->second.get() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001536}
1537
Chris Ye8594e192020-07-14 10:34:06 -07001538EventHub::Device* EventHub::getDeviceByPathLocked(const std::string& devicePath) const {
Chris Ye989bb932020-07-04 16:18:59 -07001539 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001540 if (device->path == devicePath) {
Chris Ye989bb932020-07-04 16:18:59 -07001541 return device.get();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001542 }
1543 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001544 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001545}
1546
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001547/**
1548 * The file descriptor could be either input device, or a video device (associated with a
1549 * specific input device). Check both cases here, and return the device that this event
1550 * belongs to. Caller can compare the fd's once more to determine event type.
1551 * Looks through all input devices, and only attached video devices. Unattached video
1552 * devices are ignored.
1553 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001554EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
Chris Ye989bb932020-07-04 16:18:59 -07001555 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001556 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001557 // This is an input device event
Chris Ye989bb932020-07-04 16:18:59 -07001558 return device.get();
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001559 }
1560 if (device->videoDevice && device->videoDevice->getFd() == fd) {
1561 // This is a video device event
Chris Ye989bb932020-07-04 16:18:59 -07001562 return device.get();
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001563 }
1564 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001565 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
1566 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001567 return nullptr;
1568}
1569
Chris Yee2b1e5c2021-03-10 22:45:12 -08001570std::optional<int32_t> EventHub::getBatteryCapacity(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001571 std::filesystem::path batteryPath;
1572 {
1573 // Do not read the sysfs node to get the battery state while holding
1574 // the EventHub lock. For some peripheral devices, reading battery state
1575 // can be broken and take 5+ seconds. Holding the lock in this case would
1576 // block all other event processing during this time. For now, we assume this
1577 // call never happens on the InputReader thread and read the sysfs node outside
1578 // the lock to prevent event processing from being blocked by this call.
1579 std::scoped_lock _l(mLock);
Kim Low03ea0352020-11-06 12:45:07 -08001580
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001581 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001582 auto it = infos.find(batteryId);
1583 if (it == infos.end()) {
1584 return std::nullopt;
1585 }
1586 batteryPath = it->second.path;
1587 } // release lock
1588
Chris Yee2b1e5c2021-03-10 22:45:12 -08001589 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001590
1591 // Some devices report battery capacity as an integer through the "capacity" file
Andy Chenf9f1a022022-08-29 20:07:10 -04001592 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001593 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001594 return std::stoi(base::Trim(buffer));
Kim Low03ea0352020-11-06 12:45:07 -08001595 }
1596
1597 // Other devices report capacity as an enum value POWER_SUPPLY_CAPACITY_LEVEL_XXX
1598 // These values are taken from kernel source code include/linux/power_supply.h
Andy Chenf9f1a022022-08-29 20:07:10 -04001599 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY_LEVEL),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001600 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001601 // Remove any white space such as trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001602 const auto levelIt = BATTERY_LEVEL.find(base::Trim(buffer));
1603 if (levelIt != BATTERY_LEVEL.end()) {
1604 return levelIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001605 }
1606 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001607
Kim Low03ea0352020-11-06 12:45:07 -08001608 return std::nullopt;
1609}
1610
Chris Yee2b1e5c2021-03-10 22:45:12 -08001611std::optional<int32_t> EventHub::getBatteryStatus(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001612 std::filesystem::path batteryPath;
1613 {
1614 // Do not read the sysfs node to get the battery state while holding
1615 // the EventHub lock. For some peripheral devices, reading battery state
1616 // can be broken and take 5+ seconds. Holding the lock in this case would
1617 // block all other event processing during this time. For now, we assume this
1618 // call never happens on the InputReader thread and read the sysfs node outside
1619 // the lock to prevent event processing from being blocked by this call.
1620 std::scoped_lock _l(mLock);
1621
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001622 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001623 auto it = infos.find(batteryId);
1624 if (it == infos.end()) {
1625 return std::nullopt;
1626 }
1627 batteryPath = it->second.path;
1628 } // release lock
1629
Chris Yee2b1e5c2021-03-10 22:45:12 -08001630 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001631
Andy Chenf9f1a022022-08-29 20:07:10 -04001632 if (!base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::STATUS),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001633 &buffer)) {
Kim Low03ea0352020-11-06 12:45:07 -08001634 ALOGE("Failed to read sysfs battery info: %s", strerror(errno));
1635 return std::nullopt;
1636 }
1637
Chris Yed1936772021-02-22 10:30:40 -08001638 // Remove white space like trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001639 const auto statusIt = BATTERY_STATUS.find(base::Trim(buffer));
1640 if (statusIt != BATTERY_STATUS.end()) {
1641 return statusIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001642 }
1643
1644 return std::nullopt;
1645}
1646
Michael Wrightd02c5b62014-02-10 15:10:22 -08001647size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
1648 ALOG_ASSERT(bufferSize >= 1);
1649
Chris Ye87143712020-11-10 05:05:58 +00001650 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001651
1652 struct input_event readBuffer[bufferSize];
1653
1654 RawEvent* event = buffer;
1655 size_t capacity = bufferSize;
1656 bool awoken = false;
1657 for (;;) {
1658 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
1659
1660 // Reopen input devices if needed.
1661 if (mNeedToReopenDevices) {
1662 mNeedToReopenDevices = false;
1663
1664 ALOGI("Reopening all input devices due to a configuration change.");
1665
1666 closeAllDevicesLocked();
1667 mNeedToScanDevices = true;
1668 break; // return to the caller before we actually rescan
1669 }
1670
1671 // Report any devices that had last been added/removed.
Chris Ye989bb932020-07-04 16:18:59 -07001672 for (auto it = mClosingDevices.begin(); it != mClosingDevices.end();) {
1673 std::unique_ptr<Device> device = std::move(*it);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001674 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001675 event->when = now;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001676 event->deviceId = (device->id == mBuiltInKeyboardId)
1677 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
1678 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001679 event->type = DEVICE_REMOVED;
1680 event += 1;
Chris Ye989bb932020-07-04 16:18:59 -07001681 it = mClosingDevices.erase(it);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001682 mNeedToSendFinishedDeviceScan = true;
1683 if (--capacity == 0) {
1684 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());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001698 event->when = now;
1699 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1700 event->type = DEVICE_ADDED;
1701 event += 1;
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001702
1703 // Try to find a matching video device by comparing device names
1704 for (auto it = mUnattachedVideoDevices.begin(); it != mUnattachedVideoDevices.end();
1705 it++) {
1706 std::unique_ptr<TouchVideoDevice>& videoDevice = *it;
Chris Yed3fef462021-03-07 17:10:08 -08001707 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001708 // videoDevice was transferred to 'device'
1709 it = mUnattachedVideoDevices.erase(it);
1710 break;
1711 }
1712 }
1713
1714 auto [dev_it, inserted] = mDevices.insert_or_assign(device->id, std::move(device));
1715 if (!inserted) {
Chris Ye989bb932020-07-04 16:18:59 -07001716 ALOGW("Device id %d exists, replaced.", device->id);
1717 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001718 mNeedToSendFinishedDeviceScan = true;
1719 if (--capacity == 0) {
1720 break;
1721 }
1722 }
1723
1724 if (mNeedToSendFinishedDeviceScan) {
1725 mNeedToSendFinishedDeviceScan = false;
1726 event->when = now;
1727 event->type = FINISHED_DEVICE_SCAN;
1728 event += 1;
1729 if (--capacity == 0) {
1730 break;
1731 }
1732 }
1733
1734 // Grab the next input event.
1735 bool deviceChanged = false;
1736 while (mPendingEventIndex < mPendingEventCount) {
1737 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001738 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001739 if (eventItem.events & EPOLLIN) {
1740 mPendingINotify = true;
1741 } else {
1742 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
1743 }
1744 continue;
1745 }
1746
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001747 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001748 if (eventItem.events & EPOLLIN) {
1749 ALOGV("awoken after wake()");
1750 awoken = true;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001751 char wakeReadBuffer[16];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001752 ssize_t nRead;
1753 do {
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001754 nRead = read(mWakeReadPipeFd, wakeReadBuffer, sizeof(wakeReadBuffer));
1755 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(wakeReadBuffer));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001756 } else {
1757 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001758 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001759 }
1760 continue;
1761 }
1762
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001763 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Chris Ye989bb932020-07-04 16:18:59 -07001764 if (device == nullptr) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001765 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
1766 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001767 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001768 continue;
1769 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001770 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
1771 if (eventItem.events & EPOLLIN) {
1772 size_t numFrames = device->videoDevice->readAndQueueFrames();
1773 if (numFrames == 0) {
1774 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001775 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001776 }
1777 } else if (eventItem.events & EPOLLHUP) {
1778 // TODO(b/121395353) - consider adding EPOLLRDHUP
1779 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001780 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001781 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1782 device->videoDevice = nullptr;
1783 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001784 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1785 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001786 ALOG_ASSERT(!DEBUG);
1787 }
1788 continue;
1789 }
1790 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -08001791 if (eventItem.events & EPOLLIN) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001792 int32_t readSize =
1793 read(device->fd, readBuffer, sizeof(struct input_event) * capacity);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001794 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
1795 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -07001796 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001797 " bufferSize: %zu capacity: %zu errno: %d)\n",
1798 device->fd, readSize, bufferSize, capacity, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001800 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001801 } else if (readSize < 0) {
1802 if (errno != EAGAIN && errno != EINTR) {
1803 ALOGW("could not get event (errno=%d)", errno);
1804 }
1805 } else if ((readSize % sizeof(struct input_event)) != 0) {
1806 ALOGE("could not get event (wrong size: %d)", readSize);
1807 } else {
1808 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1809
1810 size_t count = size_t(readSize) / sizeof(struct input_event);
1811 for (size_t i = 0; i < count; i++) {
1812 struct input_event& iev = readBuffer[i];
Siarhei Vishniakou592bac22018-11-08 19:42:38 -08001813 event->when = processEventTimestamp(iev);
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001814 event->readTime = systemTime(SYSTEM_TIME_MONOTONIC);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001815 event->deviceId = deviceId;
1816 event->type = iev.type;
1817 event->code = iev.code;
1818 event->value = iev.value;
1819 event += 1;
1820 capacity -= 1;
1821 }
1822 if (capacity == 0) {
1823 // The result buffer is full. Reset the pending event index
1824 // so we will try to read the device again on the next iteration.
1825 mPendingEventIndex -= 1;
1826 break;
1827 }
1828 }
1829 } else if (eventItem.events & EPOLLHUP) {
1830 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001831 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001832 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001833 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001834 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001835 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1836 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001837 }
1838 }
1839
1840 // readNotify() will modify the list of devices so this must be done after
1841 // processing all other events to ensure that we read all remaining events
1842 // before closing the devices.
1843 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
1844 mPendingINotify = false;
Prabir Pradhan952e65b2022-06-23 17:49:55 +00001845 const auto res = readNotifyLocked();
1846 if (!res.ok()) {
1847 ALOGW("Failed to read from inotify: %s", res.error().message().c_str());
1848 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001849 deviceChanged = true;
1850 }
1851
1852 // Report added or removed devices immediately.
1853 if (deviceChanged) {
1854 continue;
1855 }
1856
1857 // Return now if we have collected any events or if we were explicitly awoken.
1858 if (event != buffer || awoken) {
1859 break;
1860 }
1861
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001862 // Poll for events.
1863 // When a device driver has pending (unread) events, it acquires
1864 // a kernel wake lock. Once the last pending event has been read, the device
1865 // driver will release the kernel wake lock, but the epoll will hold the wakelock,
1866 // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
1867 // is called again for the same fd that produced the event.
1868 // Thus the system can only sleep if there are no events pending or
1869 // currently being processed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001870 //
1871 // The timeout is advisory only. If the device is asleep, it will not wake just to
1872 // service the timeout.
1873 mPendingEventIndex = 0;
1874
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001875 mLock.unlock(); // release lock before poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001876
1877 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1878
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001879 mLock.lock(); // reacquire lock after poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001880
1881 if (pollResult == 0) {
1882 // Timed out.
1883 mPendingEventCount = 0;
1884 break;
1885 }
1886
1887 if (pollResult < 0) {
1888 // An error occurred.
1889 mPendingEventCount = 0;
1890
1891 // Sleep after errors to avoid locking up the system.
1892 // Hopefully the error is transient.
1893 if (errno != EINTR) {
1894 ALOGW("poll failed (errno=%d)\n", errno);
1895 usleep(100000);
1896 }
1897 } else {
1898 // Some events occurred.
1899 mPendingEventCount = size_t(pollResult);
1900 }
1901 }
1902
1903 // All done, return the number of events we read.
1904 return event - buffer;
1905}
1906
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001907std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001908 std::scoped_lock _l(mLock);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001909
1910 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001911 if (device == nullptr || !device->videoDevice) {
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001912 return {};
1913 }
1914 return device->videoDevice->consumeFrames();
1915}
1916
Michael Wrightd02c5b62014-02-10 15:10:22 -08001917void EventHub::wake() {
1918 ALOGV("wake() called");
1919
1920 ssize_t nWrite;
1921 do {
1922 nWrite = write(mWakeWritePipeFd, "W", 1);
1923 } while (nWrite == -1 && errno == EINTR);
1924
1925 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001926 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001927 }
1928}
1929
1930void EventHub::scanDevicesLocked() {
Usama Arifb27c8e62021-06-03 16:44:09 +01001931 status_t result;
1932 std::error_code errorCode;
1933
1934 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
1935 result = scanDirLocked(DEVICE_INPUT_PATH);
1936 if (result < 0) {
1937 ALOGE("scan dir failed for %s", DEVICE_INPUT_PATH);
1938 }
1939 } else {
1940 if (errorCode) {
1941 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
1942 errorCode.message().c_str());
1943 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001944 }
Philip Quinn39b81682019-01-09 22:20:39 -08001945 if (isV4lScanningEnabled()) {
Usama Arifb27c8e62021-06-03 16:44:09 +01001946 result = scanVideoDirLocked(DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08001947 if (result != OK) {
Usama Arifb27c8e62021-06-03 16:44:09 +01001948 ALOGE("scan video dir failed for %s", DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08001949 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001950 }
Chris Ye989bb932020-07-04 16:18:59 -07001951 if (mDevices.find(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) == mDevices.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001952 createVirtualKeyboardLocked();
1953 }
1954}
1955
1956// ----------------------------------------------------------------------------
1957
Michael Wrightd02c5b62014-02-10 15:10:22 -08001958static const int32_t GAMEPAD_KEYCODES[] = {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001959 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C, //
1960 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z, //
1961 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1, //
1962 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2, //
1963 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR, //
1964 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE, //
Michael Wrightd02c5b62014-02-10 15:10:22 -08001965};
1966
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001967status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001968 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001969 struct epoll_event eventItem = {};
1970 eventItem.events = EPOLLIN | EPOLLWAKEUP;
1971 eventItem.data.fd = fd;
1972 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1973 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001974 return -errno;
1975 }
1976 return OK;
1977}
1978
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001979status_t EventHub::unregisterFdFromEpoll(int fd) {
1980 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
1981 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
1982 return -errno;
1983 }
1984 return OK;
1985}
1986
Chris Ye989bb932020-07-04 16:18:59 -07001987status_t EventHub::registerDeviceForEpollLocked(Device& device) {
1988 status_t result = registerFdForEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001989 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07001990 ALOGE("Could not add input device fd to epoll for device %" PRId32, device.id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001991 return result;
1992 }
Chris Ye989bb932020-07-04 16:18:59 -07001993 if (device.videoDevice) {
1994 registerVideoDeviceForEpollLocked(*device.videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001995 }
1996 return result;
1997}
1998
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001999void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
2000 status_t result = registerFdForEpoll(videoDevice.getFd());
2001 if (result != OK) {
2002 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
2003 }
2004}
2005
Chris Ye989bb932020-07-04 16:18:59 -07002006status_t EventHub::unregisterDeviceFromEpollLocked(Device& device) {
2007 if (device.hasValidFd()) {
2008 status_t result = unregisterFdFromEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002009 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07002010 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device.id);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002011 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002012 }
2013 }
Chris Ye989bb932020-07-04 16:18:59 -07002014 if (device.videoDevice) {
2015 unregisterVideoDeviceFromEpollLocked(*device.videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002016 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002017 return OK;
2018}
2019
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002020void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
2021 if (videoDevice.hasValidFd()) {
2022 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
2023 if (result != OK) {
2024 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002025 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002026 }
2027 }
2028}
2029
Chris Yed3fef462021-03-07 17:10:08 -08002030void EventHub::reportDeviceAddedForStatisticsLocked(const InputDeviceIdentifier& identifier,
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002031 ftl::Flags<InputDeviceClass> classes) {
Chris Ye657c2f02021-05-25 16:24:37 -07002032 SHA256_CTX ctx;
2033 SHA256_Init(&ctx);
2034 SHA256_Update(&ctx, reinterpret_cast<const uint8_t*>(identifier.uniqueId.c_str()),
2035 identifier.uniqueId.size());
2036 std::array<uint8_t, SHA256_DIGEST_LENGTH> digest;
2037 SHA256_Final(digest.data(), &ctx);
2038
2039 std::string obfuscatedId;
2040 for (size_t i = 0; i < OBFUSCATED_LENGTH; i++) {
2041 obfuscatedId += StringPrintf("%02x", digest[i]);
2042 }
2043
Chris Yed3fef462021-03-07 17:10:08 -08002044 android::util::stats_write(android::util::INPUTDEVICE_REGISTERED, identifier.name.c_str(),
2045 identifier.vendor, identifier.product, identifier.version,
Chris Ye657c2f02021-05-25 16:24:37 -07002046 identifier.bus, obfuscatedId.c_str(), classes.get());
Chris Yed3fef462021-03-07 17:10:08 -08002047}
2048
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002049void EventHub::openDeviceLocked(const std::string& devicePath) {
2050 // If an input device happens to register around the time when EventHub's constructor runs, it
2051 // is possible that the same input event node (for example, /dev/input/event3) will be noticed
2052 // in both 'inotify' callback and also in the 'scanDirLocked' pass. To prevent duplicate devices
2053 // from getting registered, ensure that this path is not already covered by an existing device.
2054 for (const auto& [deviceId, device] : mDevices) {
2055 if (device->path == devicePath) {
2056 return; // device was already registered
2057 }
2058 }
2059
Michael Wrightd02c5b62014-02-10 15:10:22 -08002060 char buffer[80];
2061
Chris Ye8594e192020-07-14 10:34:06 -07002062 ALOGV("Opening device: %s", devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002063
Chris Ye8594e192020-07-14 10:34:06 -07002064 int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002065 if (fd < 0) {
Chris Ye8594e192020-07-14 10:34:06 -07002066 ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002067 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002068 }
2069
2070 InputDeviceIdentifier identifier;
2071
2072 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002073 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Chris Ye8594e192020-07-14 10:34:06 -07002074 ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002075 } else {
2076 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002077 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002078 }
2079
2080 // Check to see if the device is on our excluded list
2081 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002082 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002083 if (identifier.name == item) {
Chris Ye8594e192020-07-14 10:34:06 -07002084 ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002085 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002086 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002087 }
2088 }
2089
2090 // Get device driver version.
2091 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002092 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Chris Ye8594e192020-07-14 10:34:06 -07002093 ALOGE("could not get driver version for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002094 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002095 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002096 }
2097
2098 // Get device identifier.
2099 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002100 if (ioctl(fd, EVIOCGID, &inputId)) {
Chris Ye8594e192020-07-14 10:34:06 -07002101 ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002102 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002103 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002104 }
2105 identifier.bus = inputId.bustype;
2106 identifier.product = inputId.product;
2107 identifier.vendor = inputId.vendor;
2108 identifier.version = inputId.version;
2109
2110 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002111 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
2112 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002113 } else {
2114 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002115 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002116 }
2117
2118 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002119 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
2120 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002121 } else {
2122 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002123 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002124 }
2125
2126 // Fill in the descriptor.
2127 assignDescriptorLocked(identifier);
2128
Michael Wrightd02c5b62014-02-10 15:10:22 -08002129 // Allocate device. (The device object takes ownership of the fd at this point.)
2130 int32_t deviceId = mNextDeviceId++;
Prabir Pradhancb42b472022-08-23 16:01:19 +00002131 std::unique_ptr<Device> device =
2132 std::make_unique<Device>(fd, deviceId, devicePath, identifier,
2133 obtainAssociatedDeviceLocked(devicePath));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002134
Chris Ye8594e192020-07-14 10:34:06 -07002135 ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002136 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002137 " vendor %04x\n"
2138 " product %04x\n"
2139 " version %04x\n",
2140 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002141 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
2142 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
2143 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
2144 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002145 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
2146 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002147
2148 // Load the configuration file for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002149 device->loadConfigurationLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002150
2151 // Figure out the kinds of events the device reports.
Chris Ye66fbac32020-07-06 20:36:43 -07002152 device->readDeviceBitMask(EVIOCGBIT(EV_KEY, 0), device->keyBitmask);
2153 device->readDeviceBitMask(EVIOCGBIT(EV_ABS, 0), device->absBitmask);
2154 device->readDeviceBitMask(EVIOCGBIT(EV_REL, 0), device->relBitmask);
2155 device->readDeviceBitMask(EVIOCGBIT(EV_SW, 0), device->swBitmask);
2156 device->readDeviceBitMask(EVIOCGBIT(EV_LED, 0), device->ledBitmask);
2157 device->readDeviceBitMask(EVIOCGBIT(EV_FF, 0), device->ffBitmask);
Chris Yef59a2f42020-10-16 12:55:26 -07002158 device->readDeviceBitMask(EVIOCGBIT(EV_MSC, 0), device->mscBitmask);
Chris Ye66fbac32020-07-06 20:36:43 -07002159 device->readDeviceBitMask(EVIOCGPROP(0), device->propBitmask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002160
2161 // See if this is a keyboard. Ignore everything in the button range except for
2162 // joystick and gamepad buttons which are handled like keyboards for the most part.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002163 bool haveKeyboardKeys =
Chris Ye66fbac32020-07-06 20:36:43 -07002164 device->keyBitmask.any(0, BTN_MISC) || device->keyBitmask.any(BTN_WHEEL, KEY_MAX + 1);
2165 bool haveGamepadButtons = device->keyBitmask.any(BTN_MISC, BTN_MOUSE) ||
2166 device->keyBitmask.any(BTN_JOYSTICK, BTN_DIGI);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002167 if (haveKeyboardKeys || haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002168 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002169 }
2170
2171 // See if this is a cursor device such as a trackball or mouse.
Chris Ye66fbac32020-07-06 20:36:43 -07002172 if (device->keyBitmask.test(BTN_MOUSE) && device->relBitmask.test(REL_X) &&
2173 device->relBitmask.test(REL_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002174 device->classes |= InputDeviceClass::CURSOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002175 }
2176
Prashant Malani1941ff52015-08-11 18:29:28 -07002177 // See if this is a rotary encoder type device.
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07002178 std::string deviceType;
2179 if (device->configuration && device->configuration->tryGetProperty("device.type", deviceType)) {
2180 if (deviceType == "rotaryEncoder") {
Chris Ye1b0c7342020-07-28 21:57:03 -07002181 device->classes |= InputDeviceClass::ROTARY_ENCODER;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002182 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002183 }
2184
Michael Wrightd02c5b62014-02-10 15:10:22 -08002185 // See if this is a touch pad.
2186 // Is this a new modern multi-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002187 if (device->absBitmask.test(ABS_MT_POSITION_X) && device->absBitmask.test(ABS_MT_POSITION_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002188 // Some joysticks such as the PS3 controller report axes that conflict
2189 // with the ABS_MT range. Try to confirm that the device really is
2190 // a touch screen.
Chris Ye66fbac32020-07-06 20:36:43 -07002191 if (device->keyBitmask.test(BTN_TOUCH) || !haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002192 device->classes |= (InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002193 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002194 // Is this an old style single-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002195 } else if (device->keyBitmask.test(BTN_TOUCH) && device->absBitmask.test(ABS_X) &&
2196 device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002197 device->classes |= InputDeviceClass::TOUCH;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002198 // Is this a BT stylus?
Chris Ye66fbac32020-07-06 20:36:43 -07002199 } else if ((device->absBitmask.test(ABS_PRESSURE) || device->keyBitmask.test(BTN_TOUCH)) &&
2200 !device->absBitmask.test(ABS_X) && !device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002201 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -07002202 // Keyboard will try to claim some of the buttons but we really want to reserve those so we
2203 // can fuse it with the touch screen data, so just take them back. Note this means an
2204 // external stylus cannot also be a keyboard device.
Chris Ye1b0c7342020-07-28 21:57:03 -07002205 device->classes &= ~InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002206 }
2207
2208 // See if this device is a joystick.
2209 // Assumes that joysticks always have gamepad buttons in order to distinguish them
2210 // from other devices such as accelerometers that also have absolute axes.
2211 if (haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002212 auto assumedClasses = device->classes | InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002213 for (int i = 0; i <= ABS_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002214 if (device->absBitmask.test(i) &&
Chris Ye1b0c7342020-07-28 21:57:03 -07002215 (getAbsAxisUsage(i, assumedClasses).test(InputDeviceClass::JOYSTICK))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002216 device->classes = assumedClasses;
2217 break;
2218 }
2219 }
2220 }
2221
Chris Yef59a2f42020-10-16 12:55:26 -07002222 // Check whether this device is an accelerometer.
2223 if (device->propBitmask.test(INPUT_PROP_ACCELEROMETER)) {
2224 device->classes |= InputDeviceClass::SENSOR;
2225 }
2226
Michael Wrightd02c5b62014-02-10 15:10:22 -08002227 // Check whether this device has switches.
2228 for (int i = 0; i <= SW_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002229 if (device->swBitmask.test(i)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002230 device->classes |= InputDeviceClass::SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002231 break;
2232 }
2233 }
2234
2235 // Check whether this device supports the vibrator.
Chris Ye66fbac32020-07-06 20:36:43 -07002236 if (device->ffBitmask.test(FF_RUMBLE)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002237 device->classes |= InputDeviceClass::VIBRATOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002238 }
2239
2240 // Configure virtual keys.
Chris Ye1b0c7342020-07-28 21:57:03 -07002241 if ((device->classes.test(InputDeviceClass::TOUCH))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242 // Load the virtual keys for the touch screen, if any.
2243 // We do this now so that we can make sure to load the keymap if necessary.
Chris Ye989bb932020-07-04 16:18:59 -07002244 bool success = device->loadVirtualKeyMapLocked();
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06002245 if (success) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002246 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002247 }
2248 }
2249
2250 // Load the key map.
Chris Yef59a2f42020-10-16 12:55:26 -07002251 // We need to do this for joysticks too because the key layout may specify axes, and for
2252 // sensor as well because the key layout may specify the axes to sensor data mapping.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002253 status_t keyMapStatus = NAME_NOT_FOUND;
Chris Yef59a2f42020-10-16 12:55:26 -07002254 if (device->classes.any(InputDeviceClass::KEYBOARD | InputDeviceClass::JOYSTICK |
2255 InputDeviceClass::SENSOR)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002256 // Load the keymap for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002257 keyMapStatus = device->loadKeyMapLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002258 }
2259
2260 // Configure the keyboard, gamepad or virtual keyboard.
Chris Ye1b0c7342020-07-28 21:57:03 -07002261 if (device->classes.test(InputDeviceClass::KEYBOARD)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002262 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002263 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002264 isEligibleBuiltInKeyboard(device->identifier, device->configuration.get(),
2265 &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002266 mBuiltInKeyboardId = device->id;
2267 }
2268
2269 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
Chris Ye989bb932020-07-04 16:18:59 -07002270 if (device->hasKeycodeLocked(AKEYCODE_Q)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002271 device->classes |= InputDeviceClass::ALPHAKEY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002272 }
2273
2274 // See if this device has a DPAD.
Chris Ye989bb932020-07-04 16:18:59 -07002275 if (device->hasKeycodeLocked(AKEYCODE_DPAD_UP) &&
2276 device->hasKeycodeLocked(AKEYCODE_DPAD_DOWN) &&
2277 device->hasKeycodeLocked(AKEYCODE_DPAD_LEFT) &&
2278 device->hasKeycodeLocked(AKEYCODE_DPAD_RIGHT) &&
2279 device->hasKeycodeLocked(AKEYCODE_DPAD_CENTER)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002280 device->classes |= InputDeviceClass::DPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002281 }
2282
2283 // See if this device has a gamepad.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002284 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES) / sizeof(GAMEPAD_KEYCODES[0]); i++) {
Chris Ye989bb932020-07-04 16:18:59 -07002285 if (device->hasKeycodeLocked(GAMEPAD_KEYCODES[i])) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002286 device->classes |= InputDeviceClass::GAMEPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002287 break;
2288 }
2289 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002290 }
2291
2292 // If the device isn't recognized as something we handle, don't monitor it.
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002293 if (device->classes == ftl::Flags<InputDeviceClass>(0)) {
Chris Ye8594e192020-07-14 10:34:06 -07002294 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002295 device->identifier.name.c_str());
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002296 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002297 }
2298
Chris Ye3fdbfef2021-01-06 18:45:18 -08002299 // Classify InputDeviceClass::BATTERY.
Prabir Pradhan51894782022-08-23 16:29:10 +00002300 if (device->associatedDevice && !device->associatedDevice->batteryInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002301 device->classes |= InputDeviceClass::BATTERY;
2302 }
Kim Low03ea0352020-11-06 12:45:07 -08002303
Chris Ye3fdbfef2021-01-06 18:45:18 -08002304 // Classify InputDeviceClass::LIGHT.
Prabir Pradhan51894782022-08-23 16:29:10 +00002305 if (device->associatedDevice && !device->associatedDevice->lightInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002306 device->classes |= InputDeviceClass::LIGHT;
Kim Low03ea0352020-11-06 12:45:07 -08002307 }
2308
Tim Kilbourn063ff532015-04-08 10:26:18 -07002309 // Determine whether the device has a mic.
Chris Ye989bb932020-07-04 16:18:59 -07002310 if (device->deviceHasMicLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002311 device->classes |= InputDeviceClass::MIC;
Tim Kilbourn063ff532015-04-08 10:26:18 -07002312 }
2313
Michael Wrightd02c5b62014-02-10 15:10:22 -08002314 // Determine whether the device is external or internal.
Chris Ye989bb932020-07-04 16:18:59 -07002315 if (device->isExternalDeviceLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002316 device->classes |= InputDeviceClass::EXTERNAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002317 }
2318
Chris Ye1b0c7342020-07-28 21:57:03 -07002319 if (device->classes.any(InputDeviceClass::JOYSTICK | InputDeviceClass::DPAD) &&
2320 device->classes.test(InputDeviceClass::GAMEPAD)) {
Chris Ye989bb932020-07-04 16:18:59 -07002321 device->controllerNumber = getNextControllerNumberLocked(device->identifier.name);
2322 device->setLedForControllerLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002323 }
2324
Chris Ye989bb932020-07-04 16:18:59 -07002325 if (registerDeviceForEpollLocked(*device) != OK) {
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002326 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002327 }
2328
Chris Ye989bb932020-07-04 16:18:59 -07002329 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002330
Chris Ye1b0c7342020-07-28 21:57:03 -07002331 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=%s, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002332 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Chris Ye1b0c7342020-07-28 21:57:03 -07002333 deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(),
2334 device->classes.string().c_str(), device->configurationFile.c_str(),
2335 device->keyMap.keyLayoutFile.c_str(), device->keyMap.keyCharacterMapFile.c_str(),
2336 toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002337
Chris Ye989bb932020-07-04 16:18:59 -07002338 addDeviceLocked(std::move(device));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002339}
2340
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002341void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
2342 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
2343 if (!videoDevice) {
2344 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
2345 return;
2346 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002347 // Transfer ownership of this video device to a matching input device
Chris Ye989bb932020-07-04 16:18:59 -07002348 for (const auto& [id, device] : mDevices) {
Chris Yed3fef462021-03-07 17:10:08 -08002349 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002350 return; // 'device' now owns 'videoDevice'
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002351 }
2352 }
2353
2354 // Couldn't find a matching input device, so just add it to a temporary holding queue.
2355 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002356 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002357 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002358 mUnattachedVideoDevices.push_back(std::move(videoDevice));
2359}
2360
Chris Yed3fef462021-03-07 17:10:08 -08002361bool EventHub::tryAddVideoDeviceLocked(EventHub::Device& device,
2362 std::unique_ptr<TouchVideoDevice>& videoDevice) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002363 if (videoDevice->getName() != device.identifier.name) {
2364 return false;
2365 }
2366 device.videoDevice = std::move(videoDevice);
2367 if (device.enabled) {
2368 registerVideoDeviceForEpollLocked(*device.videoDevice);
2369 }
2370 return true;
2371}
2372
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002373bool EventHub::isDeviceEnabled(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00002374 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002375 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002376 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002377 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2378 return false;
2379 }
2380 return device->enabled;
2381}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002382
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002383status_t EventHub::enableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002384 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002385 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002386 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002387 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2388 return BAD_VALUE;
2389 }
2390 if (device->enabled) {
2391 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
2392 return OK;
2393 }
2394 status_t result = device->enable();
2395 if (result != OK) {
2396 ALOGE("Failed to enable device %" PRId32, deviceId);
2397 return result;
2398 }
2399
Chris Ye989bb932020-07-04 16:18:59 -07002400 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002401
Chris Ye989bb932020-07-04 16:18:59 -07002402 return registerDeviceForEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002403}
2404
2405status_t EventHub::disableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002406 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002407 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002408 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002409 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2410 return BAD_VALUE;
2411 }
2412 if (!device->enabled) {
2413 ALOGW("Duplicate call to %s, input device already disabled", __func__);
2414 return OK;
2415 }
Chris Ye989bb932020-07-04 16:18:59 -07002416 unregisterDeviceFromEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002417 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002418}
2419
2420void EventHub::createVirtualKeyboardLocked() {
2421 InputDeviceIdentifier identifier;
2422 identifier.name = "Virtual";
2423 identifier.uniqueId = "<virtual>";
2424 assignDescriptorLocked(identifier);
2425
Chris Ye989bb932020-07-04 16:18:59 -07002426 std::unique_ptr<Device> device =
2427 std::make_unique<Device>(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
Prabir Pradhancb42b472022-08-23 16:01:19 +00002428 identifier, nullptr /*associatedDevice*/);
Chris Ye1b0c7342020-07-28 21:57:03 -07002429 device->classes = InputDeviceClass::KEYBOARD | InputDeviceClass::ALPHAKEY |
2430 InputDeviceClass::DPAD | InputDeviceClass::VIRTUAL;
Chris Ye989bb932020-07-04 16:18:59 -07002431 device->loadKeyMapLocked();
2432 addDeviceLocked(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002433}
2434
Chris Ye989bb932020-07-04 16:18:59 -07002435void EventHub::addDeviceLocked(std::unique_ptr<Device> device) {
Chris Yed3fef462021-03-07 17:10:08 -08002436 reportDeviceAddedForStatisticsLocked(device->identifier, device->classes);
Chris Ye989bb932020-07-04 16:18:59 -07002437 mOpeningDevices.push_back(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002438}
2439
Chris Ye989bb932020-07-04 16:18:59 -07002440int32_t EventHub::getNextControllerNumberLocked(const std::string& name) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002441 if (mControllerNumbers.isFull()) {
2442 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Chris Ye989bb932020-07-04 16:18:59 -07002443 name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002444 return 0;
2445 }
2446 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
2447 // one
2448 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
2449}
2450
Chris Ye989bb932020-07-04 16:18:59 -07002451void EventHub::releaseControllerNumberLocked(int32_t num) {
2452 if (num > 0) {
2453 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002454 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002455}
2456
Chris Ye8594e192020-07-14 10:34:06 -07002457void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002458 Device* device = getDeviceByPathLocked(devicePath);
Chris Ye989bb932020-07-04 16:18:59 -07002459 if (device != nullptr) {
2460 closeDeviceLocked(*device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002461 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002462 }
Chris Ye8594e192020-07-14 10:34:06 -07002463 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002464}
2465
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002466/**
2467 * Find the video device by filename, and close it.
2468 * The video device is closed by path during an inotify event, where we don't have the
2469 * additional context about the video device fd, or the associated input device.
2470 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002471void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002472 // A video device may be owned by an existing input device, or it may be stored in
2473 // the mUnattachedVideoDevices queue. Check both locations.
Chris Ye989bb932020-07-04 16:18:59 -07002474 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002475 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002476 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002477 device->videoDevice = nullptr;
2478 return;
2479 }
2480 }
Siarhei Vishniakouf47c339e2021-12-30 11:22:26 -08002481 std::erase_if(mUnattachedVideoDevices,
2482 [&devicePath](const std::unique_ptr<TouchVideoDevice>& videoDevice) {
2483 return videoDevice->getPath() == devicePath;
2484 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08002485}
2486
2487void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002488 mUnattachedVideoDevices.clear();
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002489 while (!mDevices.empty()) {
2490 closeDeviceLocked(*(mDevices.begin()->second));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002491 }
2492}
2493
Chris Ye989bb932020-07-04 16:18:59 -07002494void EventHub::closeDeviceLocked(Device& device) {
2495 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=%s", device.path.c_str(),
2496 device.identifier.name.c_str(), device.id, device.fd, device.classes.string().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002497
Chris Ye989bb932020-07-04 16:18:59 -07002498 if (device.id == mBuiltInKeyboardId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002499 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Chris Ye989bb932020-07-04 16:18:59 -07002500 device.path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002501 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
2502 }
2503
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002504 unregisterDeviceFromEpollLocked(device);
Chris Ye989bb932020-07-04 16:18:59 -07002505 if (device.videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002506 // This must be done after the video device is removed from epoll
Chris Ye989bb932020-07-04 16:18:59 -07002507 mUnattachedVideoDevices.push_back(std::move(device.videoDevice));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002508 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002509
Chris Ye989bb932020-07-04 16:18:59 -07002510 releaseControllerNumberLocked(device.controllerNumber);
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002511 device.controllerNumber = 0;
Chris Ye989bb932020-07-04 16:18:59 -07002512 device.close();
Chris Ye989bb932020-07-04 16:18:59 -07002513 mClosingDevices.push_back(std::move(mDevices[device.id]));
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002514
Chris Ye989bb932020-07-04 16:18:59 -07002515 mDevices.erase(device.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002516}
2517
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002518base::Result<void> EventHub::readNotifyLocked() {
2519 static constexpr auto EVENT_SIZE = static_cast<ssize_t>(sizeof(inotify_event));
2520 uint8_t eventBuffer[512];
2521 ssize_t sizeRead;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002522
2523 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002524 do {
2525 sizeRead = read(mINotifyFd, eventBuffer, sizeof(eventBuffer));
2526 } while (sizeRead < 0 && errno == EINTR);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002527
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002528 if (sizeRead < EVENT_SIZE) return Errorf("could not get event, %s", strerror(errno));
2529
2530 for (ssize_t eventPos = 0; sizeRead >= EVENT_SIZE;) {
2531 const inotify_event* event;
2532 event = (const inotify_event*)(eventBuffer + eventPos);
2533 if (event->len == 0) continue;
2534
2535 handleNotifyEventLocked(*event);
2536
2537 const ssize_t eventSize = EVENT_SIZE + event->len;
2538 sizeRead -= eventSize;
2539 eventPos += eventSize;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002540 }
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002541 return {};
2542}
2543
2544void EventHub::handleNotifyEventLocked(const inotify_event& event) {
2545 if (event.wd == mDeviceInputWd) {
2546 std::string filename = std::string(DEVICE_INPUT_PATH) + "/" + event.name;
2547 if (event.mask & IN_CREATE) {
2548 openDeviceLocked(filename);
2549 } else {
2550 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
2551 closeDeviceByPathLocked(filename);
2552 }
2553 } else if (event.wd == mDeviceWd) {
2554 if (isV4lTouchNode(event.name)) {
2555 std::string filename = std::string(DEVICE_PATH) + "/" + event.name;
2556 if (event.mask & IN_CREATE) {
2557 openVideoDeviceLocked(filename);
2558 } else {
2559 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
2560 closeVideoDeviceByPathLocked(filename);
2561 }
2562 } else if (strcmp(event.name, "input") == 0 && event.mask & IN_CREATE) {
2563 addDeviceInputInotify();
2564 }
2565 } else {
2566 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event.wd);
2567 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002568}
2569
Chris Ye8594e192020-07-14 10:34:06 -07002570status_t EventHub::scanDirLocked(const std::string& dirname) {
2571 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2572 openDeviceLocked(entry.path());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002573 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002574 return 0;
2575}
2576
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002577/**
2578 * Look for all dirname/v4l-touch* devices, and open them.
2579 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002580status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Chris Ye8594e192020-07-14 10:34:06 -07002581 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2582 if (isV4lTouchNode(entry.path())) {
2583 ALOGI("Found touch video device %s", entry.path().c_str());
2584 openVideoDeviceLocked(entry.path());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002585 }
2586 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002587 return OK;
2588}
2589
Michael Wrightd02c5b62014-02-10 15:10:22 -08002590void EventHub::requestReopenDevices() {
2591 ALOGV("requestReopenDevices() called");
2592
Chris Ye87143712020-11-10 05:05:58 +00002593 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002594 mNeedToReopenDevices = true;
2595}
2596
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002597void EventHub::dump(std::string& dump) const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002598 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002599
2600 { // acquire lock
Chris Ye87143712020-11-10 05:05:58 +00002601 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002602
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002603 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002604
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002605 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002606
Chris Ye989bb932020-07-04 16:18:59 -07002607 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002608 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002609 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002610 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002611 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002612 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002613 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002614 }
Chris Ye1b0c7342020-07-28 21:57:03 -07002615 dump += StringPrintf(INDENT3 "Classes: %s\n", device->classes.string().c_str());
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002616 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002617 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002618 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
2619 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002620 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002621 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002622 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002623 "product=0x%04x, version=0x%04x\n",
2624 device->identifier.bus, device->identifier.vendor,
2625 device->identifier.product, device->identifier.version);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002626 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002627 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002628 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002629 device->keyMap.keyCharacterMapFile.c_str());
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00002630 dump += StringPrintf(INDENT3 "CountryCode: %d\n",
2631 device->associatedDevice ? device->associatedDevice->countryCode
2632 : InputDeviceCountryCode::INVALID);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002633 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002634 device->configurationFile.c_str());
Prabir Pradhan51894782022-08-23 16:29:10 +00002635 dump += StringPrintf(INDENT3 "VideoDevice: %s\n",
2636 device->videoDevice ? device->videoDevice->dump().c_str()
2637 : "<none>");
2638 dump += StringPrintf(INDENT3 "SysfsDevicePath: %s\n",
2639 device->associatedDevice
2640 ? device->associatedDevice->sysfsRootPath.c_str()
2641 : "<none>");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002642 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002643
2644 dump += INDENT "Unattached video devices:\n";
2645 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
2646 dump += INDENT2 + videoDevice->dump() + "\n";
2647 }
2648 if (mUnattachedVideoDevices.empty()) {
2649 dump += INDENT2 "<none>\n";
2650 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002651 } // release lock
2652}
2653
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002654void EventHub::monitor() const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002655 // Acquire and release the lock to ensure that the event hub has not deadlocked.
Chris Ye1c2e0892020-11-30 21:41:44 -08002656 std::unique_lock<std::mutex> lock(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002657}
2658
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00002659std::string EventHub::AssociatedDevice::dump() const {
2660 return StringPrintf("path=%s, numBatteries=%zu, numLight=%zu", sysfsRootPath.c_str(),
2661 batteryInfos.size(), lightInfos.size());
2662}
2663
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002664} // namespace android