blob: 5351a51016b03cd72f75686c03d3fa942fe74296 [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;
1419 for (const auto& [id, dev] : mDevices) {
1420 if (dev->associatedDevice && dev->associatedDevice->sysfsRootPath == path) {
1421 return dev->associatedDevice;
1422 }
1423 }
1424
1425 return std::make_shared<AssociatedDevice>(
1426 AssociatedDevice{.sysfsRootPath = path,
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001427 .countryCode = readCountryCodeLocked(path),
Prabir Pradhancb42b472022-08-23 16:01:19 +00001428 .batteryInfos = readBatteryConfiguration(path),
1429 .lightInfos = readLightsConfiguration(path)});
1430}
1431
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001432void EventHub::vibrate(int32_t deviceId, const VibrationElement& element) {
Chris Ye87143712020-11-10 05:05:58 +00001433 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001434 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001435 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001436 ff_effect effect;
1437 memset(&effect, 0, sizeof(effect));
1438 effect.type = FF_RUMBLE;
1439 effect.id = device->ffEffectId;
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001440 // evdev FF_RUMBLE effect only supports two channels of vibration.
Chris Ye6393a262020-08-04 19:41:36 -07001441 effect.u.rumble.strong_magnitude = element.getMagnitude(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1442 effect.u.rumble.weak_magnitude = element.getMagnitude(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001443 effect.replay.length = element.duration.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001444 effect.replay.delay = 0;
1445 if (ioctl(device->fd, EVIOCSFF, &effect)) {
1446 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001447 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001448 return;
1449 }
1450 device->ffEffectId = effect.id;
1451
1452 struct input_event ev;
1453 ev.time.tv_sec = 0;
1454 ev.time.tv_usec = 0;
1455 ev.type = EV_FF;
1456 ev.code = device->ffEffectId;
1457 ev.value = 1;
1458 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1459 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001460 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001461 return;
1462 }
1463 device->ffEffectPlaying = true;
1464 }
1465}
1466
1467void EventHub::cancelVibrate(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001468 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001469 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001470 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001471 if (device->ffEffectPlaying) {
1472 device->ffEffectPlaying = false;
1473
1474 struct input_event ev;
1475 ev.time.tv_sec = 0;
1476 ev.time.tv_usec = 0;
1477 ev.type = EV_FF;
1478 ev.code = device->ffEffectId;
1479 ev.value = 0;
1480 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1481 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001482 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001483 return;
1484 }
1485 }
1486 }
1487}
1488
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001489std::vector<int32_t> EventHub::getVibratorIds(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001490 std::scoped_lock _l(mLock);
1491 std::vector<int32_t> vibrators;
1492 Device* device = getDeviceLocked(deviceId);
1493 if (device != nullptr && device->hasValidFd() &&
1494 device->classes.test(InputDeviceClass::VIBRATOR)) {
1495 vibrators.push_back(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1496 vibrators.push_back(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
1497 }
1498 return vibrators;
1499}
1500
Josh Bartel938632f2022-07-19 15:34:22 -05001501/**
1502 * Checks both mDevices and mOpeningDevices for a device with the descriptor passed.
1503 */
1504bool EventHub::hasDeviceWithDescriptorLocked(const std::string& descriptor) const {
1505 for (const auto& device : mOpeningDevices) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001506 if (descriptor == device->identifier.descriptor) {
Josh Bartel938632f2022-07-19 15:34:22 -05001507 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001508 }
1509 }
Josh Bartel938632f2022-07-19 15:34:22 -05001510
1511 for (const auto& [id, device] : mDevices) {
1512 if (descriptor == device->identifier.descriptor) {
1513 return true;
1514 }
1515 }
1516 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001517}
1518
1519EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001520 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001521 deviceId = mBuiltInKeyboardId;
1522 }
Chris Ye989bb932020-07-04 16:18:59 -07001523 const auto& it = mDevices.find(deviceId);
1524 return it != mDevices.end() ? it->second.get() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001525}
1526
Chris Ye8594e192020-07-14 10:34:06 -07001527EventHub::Device* EventHub::getDeviceByPathLocked(const std::string& devicePath) const {
Chris Ye989bb932020-07-04 16:18:59 -07001528 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001529 if (device->path == devicePath) {
Chris Ye989bb932020-07-04 16:18:59 -07001530 return device.get();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001531 }
1532 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001533 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001534}
1535
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001536/**
1537 * The file descriptor could be either input device, or a video device (associated with a
1538 * specific input device). Check both cases here, and return the device that this event
1539 * belongs to. Caller can compare the fd's once more to determine event type.
1540 * Looks through all input devices, and only attached video devices. Unattached video
1541 * devices are ignored.
1542 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001543EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
Chris Ye989bb932020-07-04 16:18:59 -07001544 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001545 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001546 // This is an input device event
Chris Ye989bb932020-07-04 16:18:59 -07001547 return device.get();
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001548 }
1549 if (device->videoDevice && device->videoDevice->getFd() == fd) {
1550 // This is a video device event
Chris Ye989bb932020-07-04 16:18:59 -07001551 return device.get();
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001552 }
1553 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001554 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
1555 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001556 return nullptr;
1557}
1558
Chris Yee2b1e5c2021-03-10 22:45:12 -08001559std::optional<int32_t> EventHub::getBatteryCapacity(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001560 std::filesystem::path batteryPath;
1561 {
1562 // Do not read the sysfs node to get the battery state while holding
1563 // the EventHub lock. For some peripheral devices, reading battery state
1564 // can be broken and take 5+ seconds. Holding the lock in this case would
1565 // block all other event processing during this time. For now, we assume this
1566 // call never happens on the InputReader thread and read the sysfs node outside
1567 // the lock to prevent event processing from being blocked by this call.
1568 std::scoped_lock _l(mLock);
Kim Low03ea0352020-11-06 12:45:07 -08001569
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001570 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001571 auto it = infos.find(batteryId);
1572 if (it == infos.end()) {
1573 return std::nullopt;
1574 }
1575 batteryPath = it->second.path;
1576 } // release lock
1577
Chris Yee2b1e5c2021-03-10 22:45:12 -08001578 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001579
1580 // Some devices report battery capacity as an integer through the "capacity" file
Andy Chenf9f1a022022-08-29 20:07:10 -04001581 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001582 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001583 return std::stoi(base::Trim(buffer));
Kim Low03ea0352020-11-06 12:45:07 -08001584 }
1585
1586 // Other devices report capacity as an enum value POWER_SUPPLY_CAPACITY_LEVEL_XXX
1587 // These values are taken from kernel source code include/linux/power_supply.h
Andy Chenf9f1a022022-08-29 20:07:10 -04001588 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY_LEVEL),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001589 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001590 // Remove any white space such as trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001591 const auto levelIt = BATTERY_LEVEL.find(base::Trim(buffer));
1592 if (levelIt != BATTERY_LEVEL.end()) {
1593 return levelIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001594 }
1595 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001596
Kim Low03ea0352020-11-06 12:45:07 -08001597 return std::nullopt;
1598}
1599
Chris Yee2b1e5c2021-03-10 22:45:12 -08001600std::optional<int32_t> EventHub::getBatteryStatus(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001601 std::filesystem::path batteryPath;
1602 {
1603 // Do not read the sysfs node to get the battery state while holding
1604 // the EventHub lock. For some peripheral devices, reading battery state
1605 // can be broken and take 5+ seconds. Holding the lock in this case would
1606 // block all other event processing during this time. For now, we assume this
1607 // call never happens on the InputReader thread and read the sysfs node outside
1608 // the lock to prevent event processing from being blocked by this call.
1609 std::scoped_lock _l(mLock);
1610
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001611 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001612 auto it = infos.find(batteryId);
1613 if (it == infos.end()) {
1614 return std::nullopt;
1615 }
1616 batteryPath = it->second.path;
1617 } // release lock
1618
Chris Yee2b1e5c2021-03-10 22:45:12 -08001619 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001620
Andy Chenf9f1a022022-08-29 20:07:10 -04001621 if (!base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::STATUS),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001622 &buffer)) {
Kim Low03ea0352020-11-06 12:45:07 -08001623 ALOGE("Failed to read sysfs battery info: %s", strerror(errno));
1624 return std::nullopt;
1625 }
1626
Chris Yed1936772021-02-22 10:30:40 -08001627 // Remove white space like trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001628 const auto statusIt = BATTERY_STATUS.find(base::Trim(buffer));
1629 if (statusIt != BATTERY_STATUS.end()) {
1630 return statusIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001631 }
1632
1633 return std::nullopt;
1634}
1635
Michael Wrightd02c5b62014-02-10 15:10:22 -08001636size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
1637 ALOG_ASSERT(bufferSize >= 1);
1638
Chris Ye87143712020-11-10 05:05:58 +00001639 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001640
1641 struct input_event readBuffer[bufferSize];
1642
1643 RawEvent* event = buffer;
1644 size_t capacity = bufferSize;
1645 bool awoken = false;
1646 for (;;) {
1647 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
1648
1649 // Reopen input devices if needed.
1650 if (mNeedToReopenDevices) {
1651 mNeedToReopenDevices = false;
1652
1653 ALOGI("Reopening all input devices due to a configuration change.");
1654
1655 closeAllDevicesLocked();
1656 mNeedToScanDevices = true;
1657 break; // return to the caller before we actually rescan
1658 }
1659
1660 // Report any devices that had last been added/removed.
Chris Ye989bb932020-07-04 16:18:59 -07001661 for (auto it = mClosingDevices.begin(); it != mClosingDevices.end();) {
1662 std::unique_ptr<Device> device = std::move(*it);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001663 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001664 event->when = now;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001665 event->deviceId = (device->id == mBuiltInKeyboardId)
1666 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
1667 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001668 event->type = DEVICE_REMOVED;
1669 event += 1;
Chris Ye989bb932020-07-04 16:18:59 -07001670 it = mClosingDevices.erase(it);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001671 mNeedToSendFinishedDeviceScan = true;
1672 if (--capacity == 0) {
1673 break;
1674 }
1675 }
1676
1677 if (mNeedToScanDevices) {
1678 mNeedToScanDevices = false;
1679 scanDevicesLocked();
1680 mNeedToSendFinishedDeviceScan = true;
1681 }
1682
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001683 while (!mOpeningDevices.empty()) {
1684 std::unique_ptr<Device> device = std::move(*mOpeningDevices.rbegin());
1685 mOpeningDevices.pop_back();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001686 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001687 event->when = now;
1688 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1689 event->type = DEVICE_ADDED;
1690 event += 1;
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001691
1692 // Try to find a matching video device by comparing device names
1693 for (auto it = mUnattachedVideoDevices.begin(); it != mUnattachedVideoDevices.end();
1694 it++) {
1695 std::unique_ptr<TouchVideoDevice>& videoDevice = *it;
Chris Yed3fef462021-03-07 17:10:08 -08001696 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001697 // videoDevice was transferred to 'device'
1698 it = mUnattachedVideoDevices.erase(it);
1699 break;
1700 }
1701 }
1702
1703 auto [dev_it, inserted] = mDevices.insert_or_assign(device->id, std::move(device));
1704 if (!inserted) {
Chris Ye989bb932020-07-04 16:18:59 -07001705 ALOGW("Device id %d exists, replaced.", device->id);
1706 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001707 mNeedToSendFinishedDeviceScan = true;
1708 if (--capacity == 0) {
1709 break;
1710 }
1711 }
1712
1713 if (mNeedToSendFinishedDeviceScan) {
1714 mNeedToSendFinishedDeviceScan = false;
1715 event->when = now;
1716 event->type = FINISHED_DEVICE_SCAN;
1717 event += 1;
1718 if (--capacity == 0) {
1719 break;
1720 }
1721 }
1722
1723 // Grab the next input event.
1724 bool deviceChanged = false;
1725 while (mPendingEventIndex < mPendingEventCount) {
1726 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001727 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001728 if (eventItem.events & EPOLLIN) {
1729 mPendingINotify = true;
1730 } else {
1731 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
1732 }
1733 continue;
1734 }
1735
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001736 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001737 if (eventItem.events & EPOLLIN) {
1738 ALOGV("awoken after wake()");
1739 awoken = true;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001740 char wakeReadBuffer[16];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001741 ssize_t nRead;
1742 do {
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001743 nRead = read(mWakeReadPipeFd, wakeReadBuffer, sizeof(wakeReadBuffer));
1744 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(wakeReadBuffer));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001745 } else {
1746 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001747 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001748 }
1749 continue;
1750 }
1751
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001752 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Chris Ye989bb932020-07-04 16:18:59 -07001753 if (device == nullptr) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001754 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
1755 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001756 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001757 continue;
1758 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001759 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
1760 if (eventItem.events & EPOLLIN) {
1761 size_t numFrames = device->videoDevice->readAndQueueFrames();
1762 if (numFrames == 0) {
1763 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001764 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001765 }
1766 } else if (eventItem.events & EPOLLHUP) {
1767 // TODO(b/121395353) - consider adding EPOLLRDHUP
1768 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001769 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001770 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1771 device->videoDevice = nullptr;
1772 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001773 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1774 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001775 ALOG_ASSERT(!DEBUG);
1776 }
1777 continue;
1778 }
1779 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -08001780 if (eventItem.events & EPOLLIN) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001781 int32_t readSize =
1782 read(device->fd, readBuffer, sizeof(struct input_event) * capacity);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001783 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
1784 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -07001785 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001786 " bufferSize: %zu capacity: %zu errno: %d)\n",
1787 device->fd, readSize, bufferSize, capacity, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001788 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001789 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001790 } else if (readSize < 0) {
1791 if (errno != EAGAIN && errno != EINTR) {
1792 ALOGW("could not get event (errno=%d)", errno);
1793 }
1794 } else if ((readSize % sizeof(struct input_event)) != 0) {
1795 ALOGE("could not get event (wrong size: %d)", readSize);
1796 } else {
1797 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1798
1799 size_t count = size_t(readSize) / sizeof(struct input_event);
1800 for (size_t i = 0; i < count; i++) {
1801 struct input_event& iev = readBuffer[i];
Siarhei Vishniakou592bac22018-11-08 19:42:38 -08001802 event->when = processEventTimestamp(iev);
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001803 event->readTime = systemTime(SYSTEM_TIME_MONOTONIC);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001804 event->deviceId = deviceId;
1805 event->type = iev.type;
1806 event->code = iev.code;
1807 event->value = iev.value;
1808 event += 1;
1809 capacity -= 1;
1810 }
1811 if (capacity == 0) {
1812 // The result buffer is full. Reset the pending event index
1813 // so we will try to read the device again on the next iteration.
1814 mPendingEventIndex -= 1;
1815 break;
1816 }
1817 }
1818 } else if (eventItem.events & EPOLLHUP) {
1819 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001820 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001821 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001822 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001823 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001824 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1825 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001826 }
1827 }
1828
1829 // readNotify() will modify the list of devices so this must be done after
1830 // processing all other events to ensure that we read all remaining events
1831 // before closing the devices.
1832 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
1833 mPendingINotify = false;
Prabir Pradhan952e65b2022-06-23 17:49:55 +00001834 const auto res = readNotifyLocked();
1835 if (!res.ok()) {
1836 ALOGW("Failed to read from inotify: %s", res.error().message().c_str());
1837 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001838 deviceChanged = true;
1839 }
1840
1841 // Report added or removed devices immediately.
1842 if (deviceChanged) {
1843 continue;
1844 }
1845
1846 // Return now if we have collected any events or if we were explicitly awoken.
1847 if (event != buffer || awoken) {
1848 break;
1849 }
1850
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001851 // Poll for events.
1852 // When a device driver has pending (unread) events, it acquires
1853 // a kernel wake lock. Once the last pending event has been read, the device
1854 // driver will release the kernel wake lock, but the epoll will hold the wakelock,
1855 // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
1856 // is called again for the same fd that produced the event.
1857 // Thus the system can only sleep if there are no events pending or
1858 // currently being processed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001859 //
1860 // The timeout is advisory only. If the device is asleep, it will not wake just to
1861 // service the timeout.
1862 mPendingEventIndex = 0;
1863
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001864 mLock.unlock(); // release lock before poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001865
1866 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1867
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001868 mLock.lock(); // reacquire lock after poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001869
1870 if (pollResult == 0) {
1871 // Timed out.
1872 mPendingEventCount = 0;
1873 break;
1874 }
1875
1876 if (pollResult < 0) {
1877 // An error occurred.
1878 mPendingEventCount = 0;
1879
1880 // Sleep after errors to avoid locking up the system.
1881 // Hopefully the error is transient.
1882 if (errno != EINTR) {
1883 ALOGW("poll failed (errno=%d)\n", errno);
1884 usleep(100000);
1885 }
1886 } else {
1887 // Some events occurred.
1888 mPendingEventCount = size_t(pollResult);
1889 }
1890 }
1891
1892 // All done, return the number of events we read.
1893 return event - buffer;
1894}
1895
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001896std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001897 std::scoped_lock _l(mLock);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001898
1899 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001900 if (device == nullptr || !device->videoDevice) {
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001901 return {};
1902 }
1903 return device->videoDevice->consumeFrames();
1904}
1905
Michael Wrightd02c5b62014-02-10 15:10:22 -08001906void EventHub::wake() {
1907 ALOGV("wake() called");
1908
1909 ssize_t nWrite;
1910 do {
1911 nWrite = write(mWakeWritePipeFd, "W", 1);
1912 } while (nWrite == -1 && errno == EINTR);
1913
1914 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001915 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001916 }
1917}
1918
1919void EventHub::scanDevicesLocked() {
Usama Arifb27c8e62021-06-03 16:44:09 +01001920 status_t result;
1921 std::error_code errorCode;
1922
1923 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
1924 result = scanDirLocked(DEVICE_INPUT_PATH);
1925 if (result < 0) {
1926 ALOGE("scan dir failed for %s", DEVICE_INPUT_PATH);
1927 }
1928 } else {
1929 if (errorCode) {
1930 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
1931 errorCode.message().c_str());
1932 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001933 }
Philip Quinn39b81682019-01-09 22:20:39 -08001934 if (isV4lScanningEnabled()) {
Usama Arifb27c8e62021-06-03 16:44:09 +01001935 result = scanVideoDirLocked(DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08001936 if (result != OK) {
Usama Arifb27c8e62021-06-03 16:44:09 +01001937 ALOGE("scan video dir failed for %s", DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08001938 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001939 }
Chris Ye989bb932020-07-04 16:18:59 -07001940 if (mDevices.find(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) == mDevices.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001941 createVirtualKeyboardLocked();
1942 }
1943}
1944
1945// ----------------------------------------------------------------------------
1946
Michael Wrightd02c5b62014-02-10 15:10:22 -08001947static const int32_t GAMEPAD_KEYCODES[] = {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001948 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C, //
1949 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z, //
1950 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1, //
1951 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2, //
1952 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR, //
1953 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE, //
Michael Wrightd02c5b62014-02-10 15:10:22 -08001954};
1955
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001956status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001957 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001958 struct epoll_event eventItem = {};
1959 eventItem.events = EPOLLIN | EPOLLWAKEUP;
1960 eventItem.data.fd = fd;
1961 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1962 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001963 return -errno;
1964 }
1965 return OK;
1966}
1967
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001968status_t EventHub::unregisterFdFromEpoll(int fd) {
1969 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
1970 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
1971 return -errno;
1972 }
1973 return OK;
1974}
1975
Chris Ye989bb932020-07-04 16:18:59 -07001976status_t EventHub::registerDeviceForEpollLocked(Device& device) {
1977 status_t result = registerFdForEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001978 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07001979 ALOGE("Could not add input device fd to epoll for device %" PRId32, device.id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001980 return result;
1981 }
Chris Ye989bb932020-07-04 16:18:59 -07001982 if (device.videoDevice) {
1983 registerVideoDeviceForEpollLocked(*device.videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001984 }
1985 return result;
1986}
1987
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001988void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
1989 status_t result = registerFdForEpoll(videoDevice.getFd());
1990 if (result != OK) {
1991 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
1992 }
1993}
1994
Chris Ye989bb932020-07-04 16:18:59 -07001995status_t EventHub::unregisterDeviceFromEpollLocked(Device& device) {
1996 if (device.hasValidFd()) {
1997 status_t result = unregisterFdFromEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001998 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07001999 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device.id);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002000 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002001 }
2002 }
Chris Ye989bb932020-07-04 16:18:59 -07002003 if (device.videoDevice) {
2004 unregisterVideoDeviceFromEpollLocked(*device.videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002005 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002006 return OK;
2007}
2008
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002009void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
2010 if (videoDevice.hasValidFd()) {
2011 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
2012 if (result != OK) {
2013 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002014 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002015 }
2016 }
2017}
2018
Chris Yed3fef462021-03-07 17:10:08 -08002019void EventHub::reportDeviceAddedForStatisticsLocked(const InputDeviceIdentifier& identifier,
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002020 ftl::Flags<InputDeviceClass> classes) {
Chris Ye657c2f02021-05-25 16:24:37 -07002021 SHA256_CTX ctx;
2022 SHA256_Init(&ctx);
2023 SHA256_Update(&ctx, reinterpret_cast<const uint8_t*>(identifier.uniqueId.c_str()),
2024 identifier.uniqueId.size());
2025 std::array<uint8_t, SHA256_DIGEST_LENGTH> digest;
2026 SHA256_Final(digest.data(), &ctx);
2027
2028 std::string obfuscatedId;
2029 for (size_t i = 0; i < OBFUSCATED_LENGTH; i++) {
2030 obfuscatedId += StringPrintf("%02x", digest[i]);
2031 }
2032
Chris Yed3fef462021-03-07 17:10:08 -08002033 android::util::stats_write(android::util::INPUTDEVICE_REGISTERED, identifier.name.c_str(),
2034 identifier.vendor, identifier.product, identifier.version,
Chris Ye657c2f02021-05-25 16:24:37 -07002035 identifier.bus, obfuscatedId.c_str(), classes.get());
Chris Yed3fef462021-03-07 17:10:08 -08002036}
2037
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002038void EventHub::openDeviceLocked(const std::string& devicePath) {
2039 // If an input device happens to register around the time when EventHub's constructor runs, it
2040 // is possible that the same input event node (for example, /dev/input/event3) will be noticed
2041 // in both 'inotify' callback and also in the 'scanDirLocked' pass. To prevent duplicate devices
2042 // from getting registered, ensure that this path is not already covered by an existing device.
2043 for (const auto& [deviceId, device] : mDevices) {
2044 if (device->path == devicePath) {
2045 return; // device was already registered
2046 }
2047 }
2048
Michael Wrightd02c5b62014-02-10 15:10:22 -08002049 char buffer[80];
2050
Chris Ye8594e192020-07-14 10:34:06 -07002051 ALOGV("Opening device: %s", devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002052
Chris Ye8594e192020-07-14 10:34:06 -07002053 int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002054 if (fd < 0) {
Chris Ye8594e192020-07-14 10:34:06 -07002055 ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002056 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002057 }
2058
2059 InputDeviceIdentifier identifier;
2060
2061 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002062 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Chris Ye8594e192020-07-14 10:34:06 -07002063 ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002064 } else {
2065 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002066 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002067 }
2068
2069 // Check to see if the device is on our excluded list
2070 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002071 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002072 if (identifier.name == item) {
Chris Ye8594e192020-07-14 10:34:06 -07002073 ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002074 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002075 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002076 }
2077 }
2078
2079 // Get device driver version.
2080 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002081 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Chris Ye8594e192020-07-14 10:34:06 -07002082 ALOGE("could not get driver version for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002083 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002084 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002085 }
2086
2087 // Get device identifier.
2088 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002089 if (ioctl(fd, EVIOCGID, &inputId)) {
Chris Ye8594e192020-07-14 10:34:06 -07002090 ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002091 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002092 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002093 }
2094 identifier.bus = inputId.bustype;
2095 identifier.product = inputId.product;
2096 identifier.vendor = inputId.vendor;
2097 identifier.version = inputId.version;
2098
2099 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002100 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
2101 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002102 } else {
2103 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002104 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002105 }
2106
2107 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002108 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
2109 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002110 } else {
2111 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002112 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002113 }
2114
2115 // Fill in the descriptor.
2116 assignDescriptorLocked(identifier);
2117
Michael Wrightd02c5b62014-02-10 15:10:22 -08002118 // Allocate device. (The device object takes ownership of the fd at this point.)
2119 int32_t deviceId = mNextDeviceId++;
Prabir Pradhancb42b472022-08-23 16:01:19 +00002120 std::unique_ptr<Device> device =
2121 std::make_unique<Device>(fd, deviceId, devicePath, identifier,
2122 obtainAssociatedDeviceLocked(devicePath));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002123
Chris Ye8594e192020-07-14 10:34:06 -07002124 ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002125 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002126 " vendor %04x\n"
2127 " product %04x\n"
2128 " version %04x\n",
2129 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002130 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
2131 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
2132 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
2133 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002134 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
2135 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002136
2137 // Load the configuration file for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002138 device->loadConfigurationLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002139
2140 // Figure out the kinds of events the device reports.
Chris Ye66fbac32020-07-06 20:36:43 -07002141 device->readDeviceBitMask(EVIOCGBIT(EV_KEY, 0), device->keyBitmask);
2142 device->readDeviceBitMask(EVIOCGBIT(EV_ABS, 0), device->absBitmask);
2143 device->readDeviceBitMask(EVIOCGBIT(EV_REL, 0), device->relBitmask);
2144 device->readDeviceBitMask(EVIOCGBIT(EV_SW, 0), device->swBitmask);
2145 device->readDeviceBitMask(EVIOCGBIT(EV_LED, 0), device->ledBitmask);
2146 device->readDeviceBitMask(EVIOCGBIT(EV_FF, 0), device->ffBitmask);
Chris Yef59a2f42020-10-16 12:55:26 -07002147 device->readDeviceBitMask(EVIOCGBIT(EV_MSC, 0), device->mscBitmask);
Chris Ye66fbac32020-07-06 20:36:43 -07002148 device->readDeviceBitMask(EVIOCGPROP(0), device->propBitmask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002149
2150 // See if this is a keyboard. Ignore everything in the button range except for
2151 // joystick and gamepad buttons which are handled like keyboards for the most part.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002152 bool haveKeyboardKeys =
Chris Ye66fbac32020-07-06 20:36:43 -07002153 device->keyBitmask.any(0, BTN_MISC) || device->keyBitmask.any(BTN_WHEEL, KEY_MAX + 1);
2154 bool haveGamepadButtons = device->keyBitmask.any(BTN_MISC, BTN_MOUSE) ||
2155 device->keyBitmask.any(BTN_JOYSTICK, BTN_DIGI);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002156 if (haveKeyboardKeys || haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002157 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002158 }
2159
2160 // See if this is a cursor device such as a trackball or mouse.
Chris Ye66fbac32020-07-06 20:36:43 -07002161 if (device->keyBitmask.test(BTN_MOUSE) && device->relBitmask.test(REL_X) &&
2162 device->relBitmask.test(REL_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002163 device->classes |= InputDeviceClass::CURSOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002164 }
2165
Prashant Malani1941ff52015-08-11 18:29:28 -07002166 // See if this is a rotary encoder type device.
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07002167 std::string deviceType;
2168 if (device->configuration && device->configuration->tryGetProperty("device.type", deviceType)) {
2169 if (deviceType == "rotaryEncoder") {
Chris Ye1b0c7342020-07-28 21:57:03 -07002170 device->classes |= InputDeviceClass::ROTARY_ENCODER;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002171 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002172 }
2173
Michael Wrightd02c5b62014-02-10 15:10:22 -08002174 // See if this is a touch pad.
2175 // Is this a new modern multi-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002176 if (device->absBitmask.test(ABS_MT_POSITION_X) && device->absBitmask.test(ABS_MT_POSITION_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002177 // Some joysticks such as the PS3 controller report axes that conflict
2178 // with the ABS_MT range. Try to confirm that the device really is
2179 // a touch screen.
Chris Ye66fbac32020-07-06 20:36:43 -07002180 if (device->keyBitmask.test(BTN_TOUCH) || !haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002181 device->classes |= (InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002182 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002183 // Is this an old style single-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002184 } else if (device->keyBitmask.test(BTN_TOUCH) && device->absBitmask.test(ABS_X) &&
2185 device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002186 device->classes |= InputDeviceClass::TOUCH;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002187 // Is this a BT stylus?
Chris Ye66fbac32020-07-06 20:36:43 -07002188 } else if ((device->absBitmask.test(ABS_PRESSURE) || device->keyBitmask.test(BTN_TOUCH)) &&
2189 !device->absBitmask.test(ABS_X) && !device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002190 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -07002191 // Keyboard will try to claim some of the buttons but we really want to reserve those so we
2192 // can fuse it with the touch screen data, so just take them back. Note this means an
2193 // external stylus cannot also be a keyboard device.
Chris Ye1b0c7342020-07-28 21:57:03 -07002194 device->classes &= ~InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002195 }
2196
2197 // See if this device is a joystick.
2198 // Assumes that joysticks always have gamepad buttons in order to distinguish them
2199 // from other devices such as accelerometers that also have absolute axes.
2200 if (haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002201 auto assumedClasses = device->classes | InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002202 for (int i = 0; i <= ABS_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002203 if (device->absBitmask.test(i) &&
Chris Ye1b0c7342020-07-28 21:57:03 -07002204 (getAbsAxisUsage(i, assumedClasses).test(InputDeviceClass::JOYSTICK))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002205 device->classes = assumedClasses;
2206 break;
2207 }
2208 }
2209 }
2210
Chris Yef59a2f42020-10-16 12:55:26 -07002211 // Check whether this device is an accelerometer.
2212 if (device->propBitmask.test(INPUT_PROP_ACCELEROMETER)) {
2213 device->classes |= InputDeviceClass::SENSOR;
2214 }
2215
Michael Wrightd02c5b62014-02-10 15:10:22 -08002216 // Check whether this device has switches.
2217 for (int i = 0; i <= SW_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002218 if (device->swBitmask.test(i)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002219 device->classes |= InputDeviceClass::SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002220 break;
2221 }
2222 }
2223
2224 // Check whether this device supports the vibrator.
Chris Ye66fbac32020-07-06 20:36:43 -07002225 if (device->ffBitmask.test(FF_RUMBLE)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002226 device->classes |= InputDeviceClass::VIBRATOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002227 }
2228
2229 // Configure virtual keys.
Chris Ye1b0c7342020-07-28 21:57:03 -07002230 if ((device->classes.test(InputDeviceClass::TOUCH))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002231 // Load the virtual keys for the touch screen, if any.
2232 // We do this now so that we can make sure to load the keymap if necessary.
Chris Ye989bb932020-07-04 16:18:59 -07002233 bool success = device->loadVirtualKeyMapLocked();
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06002234 if (success) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002235 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002236 }
2237 }
2238
2239 // Load the key map.
Chris Yef59a2f42020-10-16 12:55:26 -07002240 // We need to do this for joysticks too because the key layout may specify axes, and for
2241 // sensor as well because the key layout may specify the axes to sensor data mapping.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242 status_t keyMapStatus = NAME_NOT_FOUND;
Chris Yef59a2f42020-10-16 12:55:26 -07002243 if (device->classes.any(InputDeviceClass::KEYBOARD | InputDeviceClass::JOYSTICK |
2244 InputDeviceClass::SENSOR)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002245 // Load the keymap for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002246 keyMapStatus = device->loadKeyMapLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002247 }
2248
2249 // Configure the keyboard, gamepad or virtual keyboard.
Chris Ye1b0c7342020-07-28 21:57:03 -07002250 if (device->classes.test(InputDeviceClass::KEYBOARD)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002251 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002252 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002253 isEligibleBuiltInKeyboard(device->identifier, device->configuration.get(),
2254 &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002255 mBuiltInKeyboardId = device->id;
2256 }
2257
2258 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
Chris Ye989bb932020-07-04 16:18:59 -07002259 if (device->hasKeycodeLocked(AKEYCODE_Q)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002260 device->classes |= InputDeviceClass::ALPHAKEY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002261 }
2262
2263 // See if this device has a DPAD.
Chris Ye989bb932020-07-04 16:18:59 -07002264 if (device->hasKeycodeLocked(AKEYCODE_DPAD_UP) &&
2265 device->hasKeycodeLocked(AKEYCODE_DPAD_DOWN) &&
2266 device->hasKeycodeLocked(AKEYCODE_DPAD_LEFT) &&
2267 device->hasKeycodeLocked(AKEYCODE_DPAD_RIGHT) &&
2268 device->hasKeycodeLocked(AKEYCODE_DPAD_CENTER)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002269 device->classes |= InputDeviceClass::DPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002270 }
2271
2272 // See if this device has a gamepad.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002273 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES) / sizeof(GAMEPAD_KEYCODES[0]); i++) {
Chris Ye989bb932020-07-04 16:18:59 -07002274 if (device->hasKeycodeLocked(GAMEPAD_KEYCODES[i])) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002275 device->classes |= InputDeviceClass::GAMEPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002276 break;
2277 }
2278 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002279 }
2280
2281 // If the device isn't recognized as something we handle, don't monitor it.
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002282 if (device->classes == ftl::Flags<InputDeviceClass>(0)) {
Chris Ye8594e192020-07-14 10:34:06 -07002283 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002284 device->identifier.name.c_str());
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002285 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002286 }
2287
Chris Ye3fdbfef2021-01-06 18:45:18 -08002288 // Classify InputDeviceClass::BATTERY.
Prabir Pradhan51894782022-08-23 16:29:10 +00002289 if (device->associatedDevice && !device->associatedDevice->batteryInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002290 device->classes |= InputDeviceClass::BATTERY;
2291 }
Kim Low03ea0352020-11-06 12:45:07 -08002292
Chris Ye3fdbfef2021-01-06 18:45:18 -08002293 // Classify InputDeviceClass::LIGHT.
Prabir Pradhan51894782022-08-23 16:29:10 +00002294 if (device->associatedDevice && !device->associatedDevice->lightInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002295 device->classes |= InputDeviceClass::LIGHT;
Kim Low03ea0352020-11-06 12:45:07 -08002296 }
2297
Tim Kilbourn063ff532015-04-08 10:26:18 -07002298 // Determine whether the device has a mic.
Chris Ye989bb932020-07-04 16:18:59 -07002299 if (device->deviceHasMicLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002300 device->classes |= InputDeviceClass::MIC;
Tim Kilbourn063ff532015-04-08 10:26:18 -07002301 }
2302
Michael Wrightd02c5b62014-02-10 15:10:22 -08002303 // Determine whether the device is external or internal.
Chris Ye989bb932020-07-04 16:18:59 -07002304 if (device->isExternalDeviceLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002305 device->classes |= InputDeviceClass::EXTERNAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002306 }
2307
Chris Ye1b0c7342020-07-28 21:57:03 -07002308 if (device->classes.any(InputDeviceClass::JOYSTICK | InputDeviceClass::DPAD) &&
2309 device->classes.test(InputDeviceClass::GAMEPAD)) {
Chris Ye989bb932020-07-04 16:18:59 -07002310 device->controllerNumber = getNextControllerNumberLocked(device->identifier.name);
2311 device->setLedForControllerLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002312 }
2313
Chris Ye989bb932020-07-04 16:18:59 -07002314 if (registerDeviceForEpollLocked(*device) != OK) {
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002315 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002316 }
2317
Chris Ye989bb932020-07-04 16:18:59 -07002318 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002319
Chris Ye1b0c7342020-07-28 21:57:03 -07002320 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=%s, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002321 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Chris Ye1b0c7342020-07-28 21:57:03 -07002322 deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(),
2323 device->classes.string().c_str(), device->configurationFile.c_str(),
2324 device->keyMap.keyLayoutFile.c_str(), device->keyMap.keyCharacterMapFile.c_str(),
2325 toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002326
Chris Ye989bb932020-07-04 16:18:59 -07002327 addDeviceLocked(std::move(device));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002328}
2329
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002330void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
2331 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
2332 if (!videoDevice) {
2333 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
2334 return;
2335 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002336 // Transfer ownership of this video device to a matching input device
Chris Ye989bb932020-07-04 16:18:59 -07002337 for (const auto& [id, device] : mDevices) {
Chris Yed3fef462021-03-07 17:10:08 -08002338 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002339 return; // 'device' now owns 'videoDevice'
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002340 }
2341 }
2342
2343 // Couldn't find a matching input device, so just add it to a temporary holding queue.
2344 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002345 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002346 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002347 mUnattachedVideoDevices.push_back(std::move(videoDevice));
2348}
2349
Chris Yed3fef462021-03-07 17:10:08 -08002350bool EventHub::tryAddVideoDeviceLocked(EventHub::Device& device,
2351 std::unique_ptr<TouchVideoDevice>& videoDevice) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002352 if (videoDevice->getName() != device.identifier.name) {
2353 return false;
2354 }
2355 device.videoDevice = std::move(videoDevice);
2356 if (device.enabled) {
2357 registerVideoDeviceForEpollLocked(*device.videoDevice);
2358 }
2359 return true;
2360}
2361
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002362bool EventHub::isDeviceEnabled(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00002363 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002364 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002365 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002366 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2367 return false;
2368 }
2369 return device->enabled;
2370}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002371
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002372status_t EventHub::enableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002373 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002374 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002375 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002376 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2377 return BAD_VALUE;
2378 }
2379 if (device->enabled) {
2380 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
2381 return OK;
2382 }
2383 status_t result = device->enable();
2384 if (result != OK) {
2385 ALOGE("Failed to enable device %" PRId32, deviceId);
2386 return result;
2387 }
2388
Chris Ye989bb932020-07-04 16:18:59 -07002389 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002390
Chris Ye989bb932020-07-04 16:18:59 -07002391 return registerDeviceForEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002392}
2393
2394status_t EventHub::disableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002395 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002396 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002397 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002398 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2399 return BAD_VALUE;
2400 }
2401 if (!device->enabled) {
2402 ALOGW("Duplicate call to %s, input device already disabled", __func__);
2403 return OK;
2404 }
Chris Ye989bb932020-07-04 16:18:59 -07002405 unregisterDeviceFromEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002406 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002407}
2408
2409void EventHub::createVirtualKeyboardLocked() {
2410 InputDeviceIdentifier identifier;
2411 identifier.name = "Virtual";
2412 identifier.uniqueId = "<virtual>";
2413 assignDescriptorLocked(identifier);
2414
Chris Ye989bb932020-07-04 16:18:59 -07002415 std::unique_ptr<Device> device =
2416 std::make_unique<Device>(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
Prabir Pradhancb42b472022-08-23 16:01:19 +00002417 identifier, nullptr /*associatedDevice*/);
Chris Ye1b0c7342020-07-28 21:57:03 -07002418 device->classes = InputDeviceClass::KEYBOARD | InputDeviceClass::ALPHAKEY |
2419 InputDeviceClass::DPAD | InputDeviceClass::VIRTUAL;
Chris Ye989bb932020-07-04 16:18:59 -07002420 device->loadKeyMapLocked();
2421 addDeviceLocked(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002422}
2423
Chris Ye989bb932020-07-04 16:18:59 -07002424void EventHub::addDeviceLocked(std::unique_ptr<Device> device) {
Chris Yed3fef462021-03-07 17:10:08 -08002425 reportDeviceAddedForStatisticsLocked(device->identifier, device->classes);
Chris Ye989bb932020-07-04 16:18:59 -07002426 mOpeningDevices.push_back(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002427}
2428
Chris Ye989bb932020-07-04 16:18:59 -07002429int32_t EventHub::getNextControllerNumberLocked(const std::string& name) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002430 if (mControllerNumbers.isFull()) {
2431 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Chris Ye989bb932020-07-04 16:18:59 -07002432 name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002433 return 0;
2434 }
2435 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
2436 // one
2437 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
2438}
2439
Chris Ye989bb932020-07-04 16:18:59 -07002440void EventHub::releaseControllerNumberLocked(int32_t num) {
2441 if (num > 0) {
2442 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002443 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002444}
2445
Chris Ye8594e192020-07-14 10:34:06 -07002446void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002447 Device* device = getDeviceByPathLocked(devicePath);
Chris Ye989bb932020-07-04 16:18:59 -07002448 if (device != nullptr) {
2449 closeDeviceLocked(*device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002450 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002451 }
Chris Ye8594e192020-07-14 10:34:06 -07002452 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002453}
2454
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002455/**
2456 * Find the video device by filename, and close it.
2457 * The video device is closed by path during an inotify event, where we don't have the
2458 * additional context about the video device fd, or the associated input device.
2459 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002460void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002461 // A video device may be owned by an existing input device, or it may be stored in
2462 // the mUnattachedVideoDevices queue. Check both locations.
Chris Ye989bb932020-07-04 16:18:59 -07002463 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002464 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002465 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002466 device->videoDevice = nullptr;
2467 return;
2468 }
2469 }
Siarhei Vishniakouf47c339e2021-12-30 11:22:26 -08002470 std::erase_if(mUnattachedVideoDevices,
2471 [&devicePath](const std::unique_ptr<TouchVideoDevice>& videoDevice) {
2472 return videoDevice->getPath() == devicePath;
2473 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08002474}
2475
2476void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002477 mUnattachedVideoDevices.clear();
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002478 while (!mDevices.empty()) {
2479 closeDeviceLocked(*(mDevices.begin()->second));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002480 }
2481}
2482
Chris Ye989bb932020-07-04 16:18:59 -07002483void EventHub::closeDeviceLocked(Device& device) {
2484 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=%s", device.path.c_str(),
2485 device.identifier.name.c_str(), device.id, device.fd, device.classes.string().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002486
Chris Ye989bb932020-07-04 16:18:59 -07002487 if (device.id == mBuiltInKeyboardId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002488 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Chris Ye989bb932020-07-04 16:18:59 -07002489 device.path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002490 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
2491 }
2492
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002493 unregisterDeviceFromEpollLocked(device);
Chris Ye989bb932020-07-04 16:18:59 -07002494 if (device.videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002495 // This must be done after the video device is removed from epoll
Chris Ye989bb932020-07-04 16:18:59 -07002496 mUnattachedVideoDevices.push_back(std::move(device.videoDevice));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002497 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002498
Chris Ye989bb932020-07-04 16:18:59 -07002499 releaseControllerNumberLocked(device.controllerNumber);
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002500 device.controllerNumber = 0;
Chris Ye989bb932020-07-04 16:18:59 -07002501 device.close();
Chris Ye989bb932020-07-04 16:18:59 -07002502 mClosingDevices.push_back(std::move(mDevices[device.id]));
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002503
Chris Ye989bb932020-07-04 16:18:59 -07002504 mDevices.erase(device.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002505}
2506
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002507base::Result<void> EventHub::readNotifyLocked() {
2508 static constexpr auto EVENT_SIZE = static_cast<ssize_t>(sizeof(inotify_event));
2509 uint8_t eventBuffer[512];
2510 ssize_t sizeRead;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002511
2512 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002513 do {
2514 sizeRead = read(mINotifyFd, eventBuffer, sizeof(eventBuffer));
2515 } while (sizeRead < 0 && errno == EINTR);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002516
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002517 if (sizeRead < EVENT_SIZE) return Errorf("could not get event, %s", strerror(errno));
2518
2519 for (ssize_t eventPos = 0; sizeRead >= EVENT_SIZE;) {
2520 const inotify_event* event;
2521 event = (const inotify_event*)(eventBuffer + eventPos);
2522 if (event->len == 0) continue;
2523
2524 handleNotifyEventLocked(*event);
2525
2526 const ssize_t eventSize = EVENT_SIZE + event->len;
2527 sizeRead -= eventSize;
2528 eventPos += eventSize;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002529 }
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002530 return {};
2531}
2532
2533void EventHub::handleNotifyEventLocked(const inotify_event& event) {
2534 if (event.wd == mDeviceInputWd) {
2535 std::string filename = std::string(DEVICE_INPUT_PATH) + "/" + event.name;
2536 if (event.mask & IN_CREATE) {
2537 openDeviceLocked(filename);
2538 } else {
2539 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
2540 closeDeviceByPathLocked(filename);
2541 }
2542 } else if (event.wd == mDeviceWd) {
2543 if (isV4lTouchNode(event.name)) {
2544 std::string filename = std::string(DEVICE_PATH) + "/" + event.name;
2545 if (event.mask & IN_CREATE) {
2546 openVideoDeviceLocked(filename);
2547 } else {
2548 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
2549 closeVideoDeviceByPathLocked(filename);
2550 }
2551 } else if (strcmp(event.name, "input") == 0 && event.mask & IN_CREATE) {
2552 addDeviceInputInotify();
2553 }
2554 } else {
2555 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event.wd);
2556 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002557}
2558
Chris Ye8594e192020-07-14 10:34:06 -07002559status_t EventHub::scanDirLocked(const std::string& dirname) {
2560 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2561 openDeviceLocked(entry.path());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002562 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002563 return 0;
2564}
2565
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002566/**
2567 * Look for all dirname/v4l-touch* devices, and open them.
2568 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002569status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Chris Ye8594e192020-07-14 10:34:06 -07002570 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2571 if (isV4lTouchNode(entry.path())) {
2572 ALOGI("Found touch video device %s", entry.path().c_str());
2573 openVideoDeviceLocked(entry.path());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002574 }
2575 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002576 return OK;
2577}
2578
Michael Wrightd02c5b62014-02-10 15:10:22 -08002579void EventHub::requestReopenDevices() {
2580 ALOGV("requestReopenDevices() called");
2581
Chris Ye87143712020-11-10 05:05:58 +00002582 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002583 mNeedToReopenDevices = true;
2584}
2585
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002586void EventHub::dump(std::string& dump) const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002587 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002588
2589 { // acquire lock
Chris Ye87143712020-11-10 05:05:58 +00002590 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002591
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002592 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002593
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002594 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002595
Chris Ye989bb932020-07-04 16:18:59 -07002596 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002597 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002598 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002599 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002600 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002601 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002602 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002603 }
Chris Ye1b0c7342020-07-28 21:57:03 -07002604 dump += StringPrintf(INDENT3 "Classes: %s\n", device->classes.string().c_str());
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002605 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002606 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002607 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
2608 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002609 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002610 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002611 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002612 "product=0x%04x, version=0x%04x\n",
2613 device->identifier.bus, device->identifier.vendor,
2614 device->identifier.product, device->identifier.version);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002615 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002616 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002617 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002618 device->keyMap.keyCharacterMapFile.c_str());
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00002619 dump += StringPrintf(INDENT3 "CountryCode: %d\n",
2620 device->associatedDevice ? device->associatedDevice->countryCode
2621 : InputDeviceCountryCode::INVALID);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002622 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002623 device->configurationFile.c_str());
Prabir Pradhan51894782022-08-23 16:29:10 +00002624 dump += StringPrintf(INDENT3 "VideoDevice: %s\n",
2625 device->videoDevice ? device->videoDevice->dump().c_str()
2626 : "<none>");
2627 dump += StringPrintf(INDENT3 "SysfsDevicePath: %s\n",
2628 device->associatedDevice
2629 ? device->associatedDevice->sysfsRootPath.c_str()
2630 : "<none>");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002631 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002632
2633 dump += INDENT "Unattached video devices:\n";
2634 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
2635 dump += INDENT2 + videoDevice->dump() + "\n";
2636 }
2637 if (mUnattachedVideoDevices.empty()) {
2638 dump += INDENT2 "<none>\n";
2639 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002640 } // release lock
2641}
2642
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002643void EventHub::monitor() const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002644 // Acquire and release the lock to ensure that the event hub has not deadlocked.
Chris Ye1c2e0892020-11-30 21:41:44 -08002645 std::unique_lock<std::mutex> lock(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002646}
2647
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002648} // namespace android