blob: 5c24244dfdb3761dda3ebf0e90feee7b879719fe [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
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -070079static constexpr size_t EVENT_BUFFER_SIZE = 256;
80
Chris Yee2b1e5c2021-03-10 22:45:12 -080081// Mapping for input battery class node IDs lookup.
82// https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
83static const std::unordered_map<std::string, InputBatteryClass> BATTERY_CLASSES =
84 {{"capacity", InputBatteryClass::CAPACITY},
85 {"capacity_level", InputBatteryClass::CAPACITY_LEVEL},
86 {"status", InputBatteryClass::STATUS}};
87
88// Mapping for input battery class node names lookup.
89// https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
90static const std::unordered_map<InputBatteryClass, std::string> BATTERY_NODES =
91 {{InputBatteryClass::CAPACITY, "capacity"},
92 {InputBatteryClass::CAPACITY_LEVEL, "capacity_level"},
93 {InputBatteryClass::STATUS, "status"}};
94
Kim Low03ea0352020-11-06 12:45:07 -080095// must be kept in sync with definitions in kernel /drivers/power/supply/power_supply_sysfs.c
96static const std::unordered_map<std::string, int32_t> BATTERY_STATUS =
97 {{"Unknown", BATTERY_STATUS_UNKNOWN},
98 {"Charging", BATTERY_STATUS_CHARGING},
99 {"Discharging", BATTERY_STATUS_DISCHARGING},
100 {"Not charging", BATTERY_STATUS_NOT_CHARGING},
101 {"Full", BATTERY_STATUS_FULL}};
102
103// Mapping taken from
104// https://gitlab.freedesktop.org/upower/upower/-/blob/master/src/linux/up-device-supply.c#L484
105static const std::unordered_map<std::string, int32_t> BATTERY_LEVEL = {{"Critical", 5},
106 {"Low", 10},
107 {"Normal", 55},
108 {"High", 70},
109 {"Full", 100},
110 {"Unknown", 50}};
111
Chris Ye3fdbfef2021-01-06 18:45:18 -0800112// Mapping for input led class node names lookup.
113// https://www.kernel.org/doc/html/latest/leds/leds-class.html
114static const std::unordered_map<std::string, InputLightClass> LIGHT_CLASSES =
115 {{"red", InputLightClass::RED},
116 {"green", InputLightClass::GREEN},
117 {"blue", InputLightClass::BLUE},
118 {"global", InputLightClass::GLOBAL},
119 {"brightness", InputLightClass::BRIGHTNESS},
120 {"multi_index", InputLightClass::MULTI_INDEX},
121 {"multi_intensity", InputLightClass::MULTI_INTENSITY},
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000122 {"max_brightness", InputLightClass::MAX_BRIGHTNESS},
123 {"kbd_backlight", InputLightClass::KEYBOARD_BACKLIGHT}};
Chris Ye3fdbfef2021-01-06 18:45:18 -0800124
125// Mapping for input multicolor led class node names.
126// https://www.kernel.org/doc/html/latest/leds/leds-class-multicolor.html
127static const std::unordered_map<InputLightClass, std::string> LIGHT_NODES =
128 {{InputLightClass::BRIGHTNESS, "brightness"},
129 {InputLightClass::MULTI_INDEX, "multi_index"},
130 {InputLightClass::MULTI_INTENSITY, "multi_intensity"}};
131
132// Mapping for light color name and the light color
133const std::unordered_map<std::string, LightColor> LIGHT_COLORS = {{"red", LightColor::RED},
134 {"green", LightColor::GREEN},
135 {"blue", LightColor::BLUE}};
136
Michael Wrightd02c5b62014-02-10 15:10:22 -0800137static inline const char* toString(bool value) {
138 return value ? "true" : "false";
139}
140
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100141static std::string sha1(const std::string& in) {
Dan Albert677d87e2014-06-16 17:31:28 -0700142 SHA_CTX ctx;
143 SHA1_Init(&ctx);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100144 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
Dan Albert677d87e2014-06-16 17:31:28 -0700145 u_char digest[SHA_DIGEST_LENGTH];
146 SHA1_Final(digest, &ctx);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800147
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100148 std::string out;
Dan Albert677d87e2014-06-16 17:31:28 -0700149 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100150 out += StringPrintf("%02x", digest[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800151 }
152 return out;
153}
154
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800155/**
156 * Return true if name matches "v4l-touch*"
157 */
Chris Ye8594e192020-07-14 10:34:06 -0700158static bool isV4lTouchNode(std::string name) {
159 return name.find("v4l-touch") != std::string::npos;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800160}
161
Philip Quinn39b81682019-01-09 22:20:39 -0800162/**
163 * Returns true if V4L devices should be scanned.
164 *
165 * The system property ro.input.video_enabled can be used to control whether
166 * EventHub scans and opens V4L devices. As V4L does not support multiple
167 * clients, EventHub effectively blocks access to these devices when it opens
Siarhei Vishniakou29f88492019-04-05 14:11:43 -0700168 * them.
169 *
170 * Setting this to "false" would prevent any video devices from being discovered and
171 * associated with input devices.
172 *
173 * This property can be used as follows:
174 * 1. To turn off features that are dependent on video device presence.
175 * 2. During testing and development, to allow other clients to read video devices
176 * directly from /dev.
Philip Quinn39b81682019-01-09 22:20:39 -0800177 */
178static bool isV4lScanningEnabled() {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700179 return property_get_bool("ro.input.video_enabled", true /* default_value */);
Philip Quinn39b81682019-01-09 22:20:39 -0800180}
181
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800182static nsecs_t processEventTimestamp(const struct input_event& event) {
183 // Use the time specified in the event instead of the current time
184 // so that downstream code can get more accurate estimates of
185 // event dispatch latency from the time the event is enqueued onto
186 // the evdev client buffer.
187 //
188 // The event's timestamp fortuitously uses the same monotonic clock
189 // time base as the rest of Android. The kernel event device driver
190 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
191 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
192 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
193 // system call that also queries ktime_get_ts().
194
195 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.time.tv_sec) +
196 microseconds_to_nanoseconds(event.time.tv_usec);
197 return inputEventTime;
198}
199
Kim Low03ea0352020-11-06 12:45:07 -0800200/**
Prabir Pradhancb42b472022-08-23 16:01:19 +0000201 * Returns the sysfs root path of the input device.
Kim Low03ea0352020-11-06 12:45:07 -0800202 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800203static std::optional<std::filesystem::path> getSysfsRootPath(const char* devicePath) {
Kim Low03ea0352020-11-06 12:45:07 -0800204 std::error_code errorCode;
205
206 // Stat the device path to get the major and minor number of the character file
207 struct stat statbuf;
208 if (stat(devicePath, &statbuf) == -1) {
209 ALOGE("Could not stat device %s due to error: %s.", devicePath, std::strerror(errno));
Chris Ye3fdbfef2021-01-06 18:45:18 -0800210 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800211 }
212
213 unsigned int major_num = major(statbuf.st_rdev);
214 unsigned int minor_num = minor(statbuf.st_rdev);
215
216 // Realpath "/sys/dev/char/{major}:{minor}" to get the sysfs path to the input event
217 auto sysfsPath = std::filesystem::path("/sys/dev/char/");
218 sysfsPath /= std::to_string(major_num) + ":" + std::to_string(minor_num);
219 sysfsPath = std::filesystem::canonical(sysfsPath, errorCode);
220
221 // Make sure nothing went wrong in call to canonical()
222 if (errorCode) {
223 ALOGW("Could not run filesystem::canonical() due to error %d : %s.", errorCode.value(),
224 errorCode.message().c_str());
Chris Ye3fdbfef2021-01-06 18:45:18 -0800225 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800226 }
227
228 // Continue to go up a directory until we reach a directory named "input"
229 while (sysfsPath != "/" && sysfsPath.filename() != "input") {
230 sysfsPath = sysfsPath.parent_path();
231 }
232
233 // Then go up one more and you will be at the sysfs root of the device
234 sysfsPath = sysfsPath.parent_path();
235
236 // Make sure we didn't reach root path and that directory actually exists
237 if (sysfsPath == "/" || !std::filesystem::exists(sysfsPath, errorCode)) {
238 if (errorCode) {
239 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
240 errorCode.message().c_str());
241 }
242
243 // Not found
Chris Ye3fdbfef2021-01-06 18:45:18 -0800244 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800245 }
246
247 return sysfsPath;
248}
249
250/**
Chris Ye3fdbfef2021-01-06 18:45:18 -0800251 * Returns the list of files under a specified path.
Kim Low03ea0352020-11-06 12:45:07 -0800252 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800253static std::vector<std::filesystem::path> allFilesInPath(const std::filesystem::path& path) {
254 std::vector<std::filesystem::path> nodes;
255 std::error_code errorCode;
256 auto iter = std::filesystem::directory_iterator(path, errorCode);
257 while (!errorCode && iter != std::filesystem::directory_iterator()) {
258 nodes.push_back(iter->path());
259 iter++;
260 }
261 return nodes;
262}
263
264/**
265 * Returns the list of files under a specified directory in a sysfs path.
266 * Example:
267 * findSysfsNodes(sysfsRootPath, SysfsClass::LEDS) will return all led nodes under "leds" directory
268 * in the sysfs path.
269 */
270static std::vector<std::filesystem::path> findSysfsNodes(const std::filesystem::path& sysfsRoot,
271 SysfsClass clazz) {
Dominik Laskowski75788452021-02-09 18:51:25 -0800272 std::string nodeStr = ftl::enum_string(clazz);
Chris Ye3fdbfef2021-01-06 18:45:18 -0800273 std::for_each(nodeStr.begin(), nodeStr.end(),
274 [](char& c) { c = std::tolower(static_cast<unsigned char>(c)); });
275 std::vector<std::filesystem::path> nodes;
276 for (auto path = sysfsRoot; path != "/" && nodes.empty(); path = path.parent_path()) {
277 nodes = allFilesInPath(path / nodeStr);
278 }
279 return nodes;
280}
281
282static std::optional<std::array<LightColor, COLOR_NUM>> getColorIndexArray(
283 std::filesystem::path path) {
284 std::string indexStr;
285 if (!base::ReadFileToString(path, &indexStr)) {
286 return std::nullopt;
287 }
288
289 // Parse the multi color LED index file, refer to kernel docs
290 // leds/leds-class-multicolor.html
291 std::regex indexPattern("(red|green|blue)\\s(red|green|blue)\\s(red|green|blue)[\\n]");
292 std::smatch results;
293 std::array<LightColor, COLOR_NUM> colors;
294 if (!std::regex_match(indexStr, results, indexPattern)) {
295 return std::nullopt;
296 }
297
298 for (size_t i = 1; i < results.size(); i++) {
299 const auto it = LIGHT_COLORS.find(results[i].str());
300 if (it != LIGHT_COLORS.end()) {
301 // intensities.emplace(it->second, 0);
302 colors[i - 1] = it->second;
Kim Low03ea0352020-11-06 12:45:07 -0800303 }
304 }
Chris Ye3fdbfef2021-01-06 18:45:18 -0800305 return colors;
Kim Low03ea0352020-11-06 12:45:07 -0800306}
307
Prabir Pradhancb42b472022-08-23 16:01:19 +0000308/**
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000309 * Read country code information exposed through the sysfs path.
310 */
311static InputDeviceCountryCode readCountryCodeLocked(const std::filesystem::path& sysfsRootPath) {
312 // Check the sysfs root path
313 int hidCountryCode = static_cast<int>(InputDeviceCountryCode::INVALID);
314 std::string str;
315 if (base::ReadFileToString(sysfsRootPath / "country", &str)) {
316 hidCountryCode = std::stoi(str, nullptr, 16);
317 LOG_ALWAYS_FATAL_IF(hidCountryCode > 35 || hidCountryCode < 0,
318 "HID country code should be in range [0, 35]. Found country code "
319 "to be %d",
320 hidCountryCode);
321 }
322
323 return static_cast<InputDeviceCountryCode>(hidCountryCode);
324}
325
326/**
Prabir Pradhancb42b472022-08-23 16:01:19 +0000327 * Read information about batteries exposed through the sysfs path.
328 */
329static std::unordered_map<int32_t /*batteryId*/, RawBatteryInfo> readBatteryConfiguration(
330 const std::filesystem::path& sysfsRootPath) {
331 std::unordered_map<int32_t, RawBatteryInfo> batteryInfos;
332 int32_t nextBatteryId = 0;
333 // Check if device has any battery.
334 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::POWER_SUPPLY);
335 for (const auto& nodePath : paths) {
336 RawBatteryInfo info;
337 info.id = ++nextBatteryId;
338 info.path = nodePath;
339 info.name = nodePath.filename();
340
341 // Scan the path for all the files
342 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
343 const auto& files = allFilesInPath(nodePath);
344 for (const auto& file : files) {
345 const auto it = BATTERY_CLASSES.find(file.filename().string());
346 if (it != BATTERY_CLASSES.end()) {
347 info.flags |= it->second;
348 }
349 }
350 batteryInfos.insert_or_assign(info.id, info);
351 ALOGD("configureBatteryLocked rawBatteryId %d name %s", info.id, info.name.c_str());
352 }
353 return batteryInfos;
354}
355
356/**
357 * Read information about lights exposed through the sysfs path.
358 */
359static std::unordered_map<int32_t /*lightId*/, RawLightInfo> readLightsConfiguration(
360 const std::filesystem::path& sysfsRootPath) {
361 std::unordered_map<int32_t, RawLightInfo> lightInfos;
362 int32_t nextLightId = 0;
363 // Check if device has any lights.
364 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::LEDS);
365 for (const auto& nodePath : paths) {
366 RawLightInfo info;
367 info.id = ++nextLightId;
368 info.path = nodePath;
369 info.name = nodePath.filename();
370 info.maxBrightness = std::nullopt;
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000371
372 // Light name should follow the naming pattern <name>:<color>:<function>
373 // Refer kernel docs /leds/leds-class.html for valid supported LED names.
374 std::regex indexPattern("([a-zA-Z0-9_.:]*:)?([a-zA-Z0-9_.]*):([a-zA-Z0-9_.]*)");
375 std::smatch results;
376
377 if (std::regex_match(info.name, results, indexPattern)) {
378 // regex_match will return full match at index 0 and <name> at index 1. For RawLightInfo
379 // we only care about sections <color> and <function> which will be at index 2 and 3.
380 for (int i = 2; i <= 3; i++) {
381 const auto it = LIGHT_CLASSES.find(results.str(i));
382 if (it != LIGHT_CLASSES.end()) {
383 info.flags |= it->second;
384 }
Prabir Pradhancb42b472022-08-23 16:01:19 +0000385 }
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000386
387 // Set name of the raw light to <function> which represents playerIDs for LEDs that
388 // turn on/off based on the current player ID (Refer to PeripheralController.cpp for
389 // player ID logic)
390 info.name = results.str(3);
Prabir Pradhancb42b472022-08-23 16:01:19 +0000391 }
392 // Scan the path for all the files
393 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
394 const auto& files = allFilesInPath(nodePath);
395 for (const auto& file : files) {
396 const auto it = LIGHT_CLASSES.find(file.filename().string());
397 if (it != LIGHT_CLASSES.end()) {
398 info.flags |= it->second;
399 // If the node has maximum brightness, read it
400 if (it->second == InputLightClass::MAX_BRIGHTNESS) {
401 std::string str;
402 if (base::ReadFileToString(file, &str)) {
403 info.maxBrightness = std::stoi(str);
404 }
405 }
406 }
407 }
408 lightInfos.insert_or_assign(info.id, info);
409 ALOGD("configureLightsLocked rawLightId %d name %s", info.id, info.name.c_str());
410 }
411 return lightInfos;
412}
413
Michael Wrightd02c5b62014-02-10 15:10:22 -0800414// --- Global Functions ---
415
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700416ftl::Flags<InputDeviceClass> getAbsAxisUsage(int32_t axis,
417 ftl::Flags<InputDeviceClass> deviceClasses) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800418 // Touch devices get dibs on touch-related axes.
Chris Ye1b0c7342020-07-28 21:57:03 -0700419 if (deviceClasses.test(InputDeviceClass::TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800420 switch (axis) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700421 case ABS_X:
422 case ABS_Y:
423 case ABS_PRESSURE:
424 case ABS_TOOL_WIDTH:
425 case ABS_DISTANCE:
426 case ABS_TILT_X:
427 case ABS_TILT_Y:
428 case ABS_MT_SLOT:
429 case ABS_MT_TOUCH_MAJOR:
430 case ABS_MT_TOUCH_MINOR:
431 case ABS_MT_WIDTH_MAJOR:
432 case ABS_MT_WIDTH_MINOR:
433 case ABS_MT_ORIENTATION:
434 case ABS_MT_POSITION_X:
435 case ABS_MT_POSITION_Y:
436 case ABS_MT_TOOL_TYPE:
437 case ABS_MT_BLOB_ID:
438 case ABS_MT_TRACKING_ID:
439 case ABS_MT_PRESSURE:
440 case ABS_MT_DISTANCE:
Chris Ye1b0c7342020-07-28 21:57:03 -0700441 return InputDeviceClass::TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800442 }
443 }
444
Chris Yef59a2f42020-10-16 12:55:26 -0700445 if (deviceClasses.test(InputDeviceClass::SENSOR)) {
446 switch (axis) {
447 case ABS_X:
448 case ABS_Y:
449 case ABS_Z:
450 case ABS_RX:
451 case ABS_RY:
452 case ABS_RZ:
453 return InputDeviceClass::SENSOR;
454 }
455 }
456
Michael Wright842500e2015-03-13 17:32:02 -0700457 // External stylus gets the pressure axis
Chris Ye1b0c7342020-07-28 21:57:03 -0700458 if (deviceClasses.test(InputDeviceClass::EXTERNAL_STYLUS)) {
Michael Wright842500e2015-03-13 17:32:02 -0700459 if (axis == ABS_PRESSURE) {
Chris Ye1b0c7342020-07-28 21:57:03 -0700460 return InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -0700461 }
462 }
463
Michael Wrightd02c5b62014-02-10 15:10:22 -0800464 // Joystick devices get the rest.
Chris Ye1b0c7342020-07-28 21:57:03 -0700465 return deviceClasses & InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800466}
467
468// --- EventHub::Device ---
469
Prabir Pradhancb42b472022-08-23 16:01:19 +0000470EventHub::Device::Device(int fd, int32_t id, std::string path, InputDeviceIdentifier identifier,
471 std::shared_ptr<const AssociatedDevice> assocDev)
Chris Ye989bb932020-07-04 16:18:59 -0700472 : fd(fd),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700473 id(id),
Prabir Pradhancb42b472022-08-23 16:01:19 +0000474 path(std::move(path)),
475 identifier(std::move(identifier)),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700476 classes(0),
477 configuration(nullptr),
478 virtualKeyMap(nullptr),
479 ffEffectPlaying(false),
480 ffEffectId(-1),
Prabir Pradhancb42b472022-08-23 16:01:19 +0000481 associatedDevice(std::move(assocDev)),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700482 controllerNumber(0),
483 enabled(true),
Chris Ye66fbac32020-07-06 20:36:43 -0700484 isVirtual(fd < 0) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800485
486EventHub::Device::~Device() {
487 close();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800488}
489
490void EventHub::Device::close() {
491 if (fd >= 0) {
492 ::close(fd);
493 fd = -1;
494 }
495}
496
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700497status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100498 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700499 if (fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100500 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700501 return -errno;
502 }
503 enabled = true;
504 return OK;
505}
506
507status_t EventHub::Device::disable() {
508 close();
509 enabled = false;
510 return OK;
511}
512
Chris Ye989bb932020-07-04 16:18:59 -0700513bool EventHub::Device::hasValidFd() const {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700514 return !isVirtual && enabled;
515}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800516
Chris Ye3a1e4462020-08-12 10:13:15 -0700517const std::shared_ptr<KeyCharacterMap> EventHub::Device::getKeyCharacterMap() const {
Chris Ye989bb932020-07-04 16:18:59 -0700518 return keyMap.keyCharacterMap;
519}
520
521template <std::size_t N>
522status_t EventHub::Device::readDeviceBitMask(unsigned long ioctlCode, BitArray<N>& bitArray) {
523 if (!hasValidFd()) {
524 return BAD_VALUE;
525 }
526 if ((_IOC_SIZE(ioctlCode) == 0)) {
527 ioctlCode |= _IOC(0, 0, 0, bitArray.bytes());
528 }
529
530 typename BitArray<N>::Buffer buffer;
531 status_t ret = ioctl(fd, ioctlCode, buffer.data());
532 bitArray.loadFromBuffer(buffer);
533 return ret;
534}
535
536void EventHub::Device::configureFd() {
537 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
538 if (classes.test(InputDeviceClass::KEYBOARD)) {
539 // Disable kernel key repeat since we handle it ourselves
540 unsigned int repeatRate[] = {0, 0};
541 if (ioctl(fd, EVIOCSREP, repeatRate)) {
542 ALOGW("Unable to disable kernel key repeat for %s: %s", path.c_str(), strerror(errno));
543 }
544 }
545
546 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
547 // associated with input events. This is important because the input system
548 // uses the timestamps extensively and assumes they were recorded using the monotonic
549 // clock.
550 int clockId = CLOCK_MONOTONIC;
Chris Yef59a2f42020-10-16 12:55:26 -0700551 if (classes.test(InputDeviceClass::SENSOR)) {
552 // Each new sensor event should use the same time base as
553 // SystemClock.elapsedRealtimeNanos().
554 clockId = CLOCK_BOOTTIME;
555 }
Chris Ye989bb932020-07-04 16:18:59 -0700556 bool usingClockIoctl = !ioctl(fd, EVIOCSCLOCKID, &clockId);
557 ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
558}
559
560bool EventHub::Device::hasKeycodeLocked(int keycode) const {
561 if (!keyMap.haveKeyLayout()) {
562 return false;
563 }
564
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700565 std::vector<int32_t> scanCodes = keyMap.keyLayoutMap->findScanCodesForKey(keycode);
Chris Ye989bb932020-07-04 16:18:59 -0700566 const size_t N = scanCodes.size();
567 for (size_t i = 0; i < N && i <= KEY_MAX; i++) {
568 int32_t sc = scanCodes[i];
569 if (sc >= 0 && sc <= KEY_MAX && keyBitmask.test(sc)) {
570 return true;
571 }
572 }
573
574 return false;
575}
576
577void EventHub::Device::loadConfigurationLocked() {
578 configurationFile =
579 getInputDeviceConfigurationFilePathByDeviceIdentifier(identifier,
580 InputDeviceConfigurationFileType::
581 CONFIGURATION);
582 if (configurationFile.empty()) {
583 ALOGD("No input device configuration file found for device '%s'.", identifier.name.c_str());
584 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500585 android::base::Result<std::unique_ptr<PropertyMap>> propertyMap =
586 PropertyMap::load(configurationFile.c_str());
587 if (!propertyMap.ok()) {
Chris Ye989bb932020-07-04 16:18:59 -0700588 ALOGE("Error loading input device configuration file for device '%s'. "
589 "Using default configuration.",
590 identifier.name.c_str());
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500591 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500592 configuration = std::move(*propertyMap);
Chris Ye989bb932020-07-04 16:18:59 -0700593 }
594 }
595}
596
597bool EventHub::Device::loadVirtualKeyMapLocked() {
598 // The virtual key map is supplied by the kernel as a system board property file.
599 std::string propPath = "/sys/board_properties/virtualkeys.";
600 propPath += identifier.getCanonicalName();
601 if (access(propPath.c_str(), R_OK)) {
602 return false;
603 }
604 virtualKeyMap = VirtualKeyMap::load(propPath);
605 return virtualKeyMap != nullptr;
606}
607
608status_t EventHub::Device::loadKeyMapLocked() {
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500609 return keyMap.load(identifier, configuration.get());
Chris Ye989bb932020-07-04 16:18:59 -0700610}
611
612bool EventHub::Device::isExternalDeviceLocked() {
613 if (configuration) {
614 bool value;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700615 if (configuration->tryGetProperty("device.internal", value)) {
Chris Ye989bb932020-07-04 16:18:59 -0700616 return !value;
617 }
618 }
619 return identifier.bus == BUS_USB || identifier.bus == BUS_BLUETOOTH;
620}
621
622bool EventHub::Device::deviceHasMicLocked() {
623 if (configuration) {
624 bool value;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700625 if (configuration->tryGetProperty("audio.mic", value)) {
Chris Ye989bb932020-07-04 16:18:59 -0700626 return value;
627 }
628 }
629 return false;
630}
631
632void EventHub::Device::setLedStateLocked(int32_t led, bool on) {
633 int32_t sc;
634 if (hasValidFd() && mapLed(led, &sc) != NAME_NOT_FOUND) {
635 struct input_event ev;
636 ev.time.tv_sec = 0;
637 ev.time.tv_usec = 0;
638 ev.type = EV_LED;
639 ev.code = sc;
640 ev.value = on ? 1 : 0;
641
642 ssize_t nWrite;
643 do {
644 nWrite = write(fd, &ev, sizeof(struct input_event));
645 } while (nWrite == -1 && errno == EINTR);
646 }
647}
648
649void EventHub::Device::setLedForControllerLocked() {
650 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
651 setLedStateLocked(ALED_CONTROLLER_1 + i, controllerNumber == i + 1);
652 }
653}
654
655status_t EventHub::Device::mapLed(int32_t led, int32_t* outScanCode) const {
656 if (!keyMap.haveKeyLayout()) {
657 return NAME_NOT_FOUND;
658 }
659
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700660 std::optional<int32_t> scanCode = keyMap.keyLayoutMap->findScanCodeForLed(led);
661 if (scanCode.has_value()) {
662 if (*scanCode >= 0 && *scanCode <= LED_MAX && ledBitmask.test(*scanCode)) {
663 *outScanCode = *scanCode;
Chris Ye989bb932020-07-04 16:18:59 -0700664 return NO_ERROR;
665 }
666 }
667 return NAME_NOT_FOUND;
668}
669
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100670/**
671 * Get the capabilities for the current process.
672 * Crashes the system if unable to create / check / destroy the capabilities object.
673 */
674class Capabilities final {
675public:
676 explicit Capabilities() {
677 mCaps = cap_get_proc();
678 LOG_ALWAYS_FATAL_IF(mCaps == nullptr, "Could not get capabilities of the current process");
679 }
680
681 /**
682 * Check whether the current process has a specific capability
683 * in the set of effective capabilities.
684 * Return CAP_SET if the process has the requested capability
685 * Return CAP_CLEAR otherwise.
686 */
687 cap_flag_value_t checkEffectiveCapability(cap_value_t capability) {
688 cap_flag_value_t value;
689 const int result = cap_get_flag(mCaps, capability, CAP_EFFECTIVE, &value);
690 LOG_ALWAYS_FATAL_IF(result == -1, "Could not obtain the requested capability");
691 return value;
692 }
693
694 ~Capabilities() {
695 const int result = cap_free(mCaps);
696 LOG_ALWAYS_FATAL_IF(result == -1, "Could not release the capabilities structure");
697 }
698
699private:
700 cap_t mCaps;
701};
702
703static void ensureProcessCanBlockSuspend() {
704 Capabilities capabilities;
705 const bool canBlockSuspend =
706 capabilities.checkEffectiveCapability(CAP_BLOCK_SUSPEND) == CAP_SET;
707 LOG_ALWAYS_FATAL_IF(!canBlockSuspend,
708 "Input must be able to block suspend to properly process events");
709}
710
Michael Wrightd02c5b62014-02-10 15:10:22 -0800711// --- EventHub ---
712
Michael Wrightd02c5b62014-02-10 15:10:22 -0800713const int EventHub::EPOLL_MAX_EVENTS;
714
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700715EventHub::EventHub(void)
716 : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
717 mNextDeviceId(1),
718 mControllerNumbers(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800719 mNeedToSendFinishedDeviceScan(false),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700720 mNeedToReopenDevices(false),
721 mNeedToScanDevices(true),
722 mPendingEventCount(0),
723 mPendingEventIndex(0),
724 mPendingINotify(false) {
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100725 ensureProcessCanBlockSuspend();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800726
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800727 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800728 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800729
Michael Wright8e9a8562022-02-09 13:44:29 +0000730 mINotifyFd = inotify_init1(IN_CLOEXEC);
Prabir Pradhan952e65b2022-06-23 17:49:55 +0000731 LOG_ALWAYS_FATAL_IF(mINotifyFd < 0, "Could not create inotify instance: %s", strerror(errno));
Usama Arifb27c8e62021-06-03 16:44:09 +0100732
733 std::error_code errorCode;
734 bool isDeviceInotifyAdded = false;
735 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
736 addDeviceInputInotify();
Philip Quinn39b81682019-01-09 22:20:39 -0800737 } else {
Usama Arifb27c8e62021-06-03 16:44:09 +0100738 addDeviceInotify();
739 isDeviceInotifyAdded = true;
740 if (errorCode) {
741 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
742 errorCode.message().c_str());
743 }
744 }
745
746 if (isV4lScanningEnabled() && !isDeviceInotifyAdded) {
747 addDeviceInotify();
748 } else {
Philip Quinn39b81682019-01-09 22:20:39 -0800749 ALOGI("Video device scanning disabled");
750 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800751
Siarhei Vishniakou2d0e9482019-09-24 12:52:47 +0100752 struct epoll_event eventItem = {};
753 eventItem.events = EPOLLIN | EPOLLWAKEUP;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700754 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800755 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800756 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
757
758 int wakeFds[2];
Michael Wright8e9a8562022-02-09 13:44:29 +0000759 result = pipe2(wakeFds, O_CLOEXEC);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800760 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
761
762 mWakeReadPipeFd = wakeFds[0];
763 mWakeWritePipeFd = wakeFds[1];
764
765 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
766 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700767 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800768
769 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
770 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700771 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800772
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700773 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800774 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
775 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700776 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800777}
778
779EventHub::~EventHub(void) {
780 closeAllDevicesLocked();
781
Michael Wrightd02c5b62014-02-10 15:10:22 -0800782 ::close(mEpollFd);
783 ::close(mINotifyFd);
784 ::close(mWakeReadPipeFd);
785 ::close(mWakeWritePipeFd);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800786}
787
Usama Arifb27c8e62021-06-03 16:44:09 +0100788/**
789 * On devices that don't have any input devices (like some development boards), the /dev/input
790 * directory will be absent. However, the user may still plug in an input device at a later time.
791 * Add watch for contents of /dev/input only when /dev/input appears.
792 */
793void EventHub::addDeviceInputInotify() {
794 mDeviceInputWd = inotify_add_watch(mINotifyFd, DEVICE_INPUT_PATH, IN_DELETE | IN_CREATE);
795 LOG_ALWAYS_FATAL_IF(mDeviceInputWd < 0, "Could not register INotify for %s: %s",
796 DEVICE_INPUT_PATH, strerror(errno));
797}
798
799void EventHub::addDeviceInotify() {
800 mDeviceWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
801 LOG_ALWAYS_FATAL_IF(mDeviceWd < 0, "Could not register INotify for %s: %s", DEVICE_PATH,
802 strerror(errno));
803}
804
Michael Wrightd02c5b62014-02-10 15:10:22 -0800805InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000806 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800807 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700808 return device != nullptr ? device->identifier : InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800809}
810
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700811ftl::Flags<InputDeviceClass> EventHub::getDeviceClasses(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000812 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800813 Device* device = getDeviceLocked(deviceId);
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700814 return device != nullptr ? device->classes : ftl::Flags<InputDeviceClass>(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800815}
816
817int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000818 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800819 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700820 return device != nullptr ? device->controllerNumber : 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800821}
822
823void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
Chris Ye87143712020-11-10 05:05:58 +0000824 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800825 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700826 if (device != nullptr && device->configuration) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800827 *outConfiguration = *device->configuration;
828 } else {
829 outConfiguration->clear();
830 }
831}
832
833status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700834 RawAbsoluteAxisInfo* outAxisInfo) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800835 outAxisInfo->clear();
836
837 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000838 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800839
840 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700841 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800842 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700843 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
844 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
845 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800846 return -errno;
847 }
848
849 if (info.minimum != info.maximum) {
850 outAxisInfo->valid = true;
851 outAxisInfo->minValue = info.minimum;
852 outAxisInfo->maxValue = info.maximum;
853 outAxisInfo->flat = info.flat;
854 outAxisInfo->fuzz = info.fuzz;
855 outAxisInfo->resolution = info.resolution;
856 }
857 return OK;
858 }
859 }
860 return -1;
861}
862
863bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
864 if (axis >= 0 && axis <= REL_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000865 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800866 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700867 return device != nullptr ? device->relBitmask.test(axis) : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800868 }
869 return false;
870}
871
872bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
Chris Ye87143712020-11-10 05:05:58 +0000873 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874
Chris Ye989bb932020-07-04 16:18:59 -0700875 Device* device = getDeviceLocked(deviceId);
876 return property >= 0 && property <= INPUT_PROP_MAX && device != nullptr
877 ? device->propBitmask.test(property)
878 : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800879}
880
Chris Yef59a2f42020-10-16 12:55:26 -0700881bool EventHub::hasMscEvent(int32_t deviceId, int mscEvent) const {
882 std::scoped_lock _l(mLock);
883
884 Device* device = getDeviceLocked(deviceId);
885 return mscEvent >= 0 && mscEvent <= MSC_MAX && device != nullptr
886 ? device->mscBitmask.test(mscEvent)
887 : false;
888}
889
Michael Wrightd02c5b62014-02-10 15:10:22 -0800890int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
891 if (scanCode >= 0 && scanCode <= KEY_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000892 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800893
894 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700895 if (device != nullptr && device->hasValidFd() && device->keyBitmask.test(scanCode)) {
896 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
897 return device->keyState.test(scanCode) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800898 }
899 }
900 }
901 return AKEY_STATE_UNKNOWN;
902}
903
904int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
Chris Ye87143712020-11-10 05:05:58 +0000905 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800906
907 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700908 if (device != nullptr && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700909 std::vector<int32_t> scanCodes = device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800910 if (scanCodes.size() != 0) {
Chris Ye66fbac32020-07-06 20:36:43 -0700911 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800912 for (size_t i = 0; i < scanCodes.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800913 int32_t sc = scanCodes[i];
Chris Ye66fbac32020-07-06 20:36:43 -0700914 if (sc >= 0 && sc <= KEY_MAX && device->keyState.test(sc)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800915 return AKEY_STATE_DOWN;
916 }
917 }
918 return AKEY_STATE_UP;
919 }
920 }
921 }
922 return AKEY_STATE_UNKNOWN;
923}
924
Philip Junker4af3b3d2021-12-14 10:36:55 +0100925int32_t EventHub::getKeyCodeForKeyLocation(int32_t deviceId, int32_t locationKeyCode) const {
926 std::scoped_lock _l(mLock);
927
928 Device* device = getDeviceLocked(deviceId);
929 if (device == nullptr || !device->hasValidFd() || device->keyMap.keyCharacterMap == nullptr ||
930 device->keyMap.keyLayoutMap == nullptr) {
931 return AKEYCODE_UNKNOWN;
932 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700933 std::vector<int32_t> scanCodes =
934 device->keyMap.keyLayoutMap->findScanCodesForKey(locationKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +0100935 if (scanCodes.empty()) {
936 ALOGW("Failed to get key code for key location: no scan code maps to key code %d for input"
937 "device %d",
938 locationKeyCode, deviceId);
939 return AKEYCODE_UNKNOWN;
940 }
941 if (scanCodes.size() > 1) {
942 ALOGW("Multiple scan codes map to the same key code %d, returning only the first match",
943 locationKeyCode);
944 }
945 int32_t outKeyCode;
946 status_t mapKeyRes =
947 device->getKeyCharacterMap()->mapKey(scanCodes[0], 0 /*usageCode*/, &outKeyCode);
948 switch (mapKeyRes) {
949 case OK:
950 return outKeyCode;
951 case NAME_NOT_FOUND:
952 // key character map doesn't re-map this scanCode, hence the keyCode remains the same
953 return locationKeyCode;
954 default:
955 ALOGW("Failed to get key code for key location: Key character map returned error %s",
956 statusToString(mapKeyRes).c_str());
957 return AKEYCODE_UNKNOWN;
958 }
959}
960
Michael Wrightd02c5b62014-02-10 15:10:22 -0800961int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
962 if (sw >= 0 && sw <= SW_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000963 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800964
965 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700966 if (device != nullptr && device->hasValidFd() && device->swBitmask.test(sw)) {
967 if (device->readDeviceBitMask(EVIOCGSW(0), device->swState) >= 0) {
968 return device->swState.test(sw) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800969 }
970 }
971 }
972 return AKEY_STATE_UNKNOWN;
973}
974
975status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
976 *outValue = 0;
977
978 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000979 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800980
981 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700982 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800983 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700984 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
985 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
986 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800987 return -errno;
988 }
989
990 *outValue = info.value;
991 return OK;
992 }
993 }
994 return -1;
995}
996
Siarhei Vishniakou74007942022-06-13 13:57:47 -0700997bool EventHub::markSupportedKeyCodes(int32_t deviceId, const std::vector<int32_t>& keyCodes,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700998 uint8_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +0000999 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001000
1001 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001002 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001003 for (size_t codeIndex = 0; codeIndex < keyCodes.size(); codeIndex++) {
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001004 std::vector<int32_t> scanCodes =
1005 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCodes[codeIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001006
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001007 // check the possible scan codes identified by the layout map against the
1008 // map of codes actually emitted by the driver
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001009 for (const int32_t scanCode : scanCodes) {
1010 if (device->keyBitmask.test(scanCode)) {
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001011 outFlags[codeIndex] = 1;
1012 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001013 }
1014 }
1015 }
1016 return true;
1017 }
1018 return false;
1019}
1020
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001021status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
1022 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +00001023 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001024 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001025 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026
Chris Ye66fbac32020-07-06 20:36:43 -07001027 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001028 // Check the key character map first.
Chris Ye3a1e4462020-08-12 10:13:15 -07001029 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
1030 if (kcm) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001031 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
1032 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001033 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001034 }
1035 }
1036
1037 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001038 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -08001039 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001040 status = NO_ERROR;
1041 }
1042 }
1043
1044 if (status == NO_ERROR) {
Chris Ye3a1e4462020-08-12 10:13:15 -07001045 if (kcm) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001046 kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState);
1047 } else {
1048 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001049 }
1050 }
1051 }
1052
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001053 if (status != NO_ERROR) {
1054 *outKeycode = 0;
1055 *outFlags = 0;
1056 *outMetaState = metaState;
1057 }
1058
1059 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001060}
1061
1062status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
Chris Ye87143712020-11-10 05:05:58 +00001063 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001064 Device* device = getDeviceLocked(deviceId);
1065
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001066 if (device == nullptr || !device->keyMap.haveKeyLayout()) {
1067 return NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001068 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001069 std::optional<AxisInfo> info = device->keyMap.keyLayoutMap->mapAxis(scanCode);
1070 if (!info.has_value()) {
1071 return NAME_NOT_FOUND;
1072 }
1073 *outAxisInfo = *info;
1074 return NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001075}
1076
Chris Yef59a2f42020-10-16 12:55:26 -07001077base::Result<std::pair<InputDeviceSensorType, int32_t>> EventHub::mapSensor(int32_t deviceId,
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001078 int32_t absCode) const {
Chris Yef59a2f42020-10-16 12:55:26 -07001079 std::scoped_lock _l(mLock);
1080 Device* device = getDeviceLocked(deviceId);
1081
1082 if (device != nullptr && device->keyMap.haveKeyLayout()) {
1083 return device->keyMap.keyLayoutMap->mapSensor(absCode);
1084 }
1085 return Errorf("Device not found or device has no key layout.");
1086}
1087
Chris Yee2b1e5c2021-03-10 22:45:12 -08001088// Gets the battery info map from battery ID to RawBatteryInfo of the miscellaneous device
1089// associated with the device ID. Returns an empty map if no miscellaneous device found.
1090const std::unordered_map<int32_t, RawBatteryInfo>& EventHub::getBatteryInfoLocked(
1091 int32_t deviceId) const {
1092 static const std::unordered_map<int32_t, RawBatteryInfo> EMPTY_BATTERY_INFO = {};
1093 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001094 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001095 return EMPTY_BATTERY_INFO;
1096 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001097 return device->associatedDevice->batteryInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001098}
1099
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001100std::vector<int32_t> EventHub::getRawBatteryIds(int32_t deviceId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001101 std::scoped_lock _l(mLock);
1102 std::vector<int32_t> batteryIds;
1103
Prabir Pradhan51894782022-08-23 16:29:10 +00001104 for (const auto& [id, info] : getBatteryInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001105 batteryIds.push_back(id);
1106 }
1107
1108 return batteryIds;
1109}
1110
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001111std::optional<RawBatteryInfo> EventHub::getRawBatteryInfo(int32_t deviceId,
1112 int32_t batteryId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001113 std::scoped_lock _l(mLock);
1114
1115 const auto infos = getBatteryInfoLocked(deviceId);
1116
1117 auto it = infos.find(batteryId);
1118 if (it != infos.end()) {
1119 return it->second;
1120 }
1121
1122 return std::nullopt;
1123}
1124
1125// Gets the light info map from light ID to RawLightInfo of the miscellaneous device associated
Prabir Pradhan51894782022-08-23 16:29:10 +00001126// with the device ID. Returns an empty map if no miscellaneous device found.
Chris Yee2b1e5c2021-03-10 22:45:12 -08001127const std::unordered_map<int32_t, RawLightInfo>& EventHub::getLightInfoLocked(
1128 int32_t deviceId) const {
1129 static const std::unordered_map<int32_t, RawLightInfo> EMPTY_LIGHT_INFO = {};
1130 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001131 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001132 return EMPTY_LIGHT_INFO;
1133 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001134 return device->associatedDevice->lightInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001135}
1136
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001137std::vector<int32_t> EventHub::getRawLightIds(int32_t deviceId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001138 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001139 std::vector<int32_t> lightIds;
1140
Prabir Pradhan51894782022-08-23 16:29:10 +00001141 for (const auto& [id, info] : getLightInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001142 lightIds.push_back(id);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001143 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001144
Chris Ye3fdbfef2021-01-06 18:45:18 -08001145 return lightIds;
1146}
1147
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001148std::optional<RawLightInfo> EventHub::getRawLightInfo(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001149 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001150
Chris Yee2b1e5c2021-03-10 22:45:12 -08001151 const auto infos = getLightInfoLocked(deviceId);
1152
1153 auto it = infos.find(lightId);
1154 if (it != infos.end()) {
1155 return it->second;
Chris Ye3fdbfef2021-01-06 18:45:18 -08001156 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001157
Chris Ye3fdbfef2021-01-06 18:45:18 -08001158 return std::nullopt;
1159}
1160
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001161std::optional<int32_t> EventHub::getLightBrightness(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001162 std::scoped_lock _l(mLock);
1163
Chris Yee2b1e5c2021-03-10 22:45:12 -08001164 const auto infos = getLightInfoLocked(deviceId);
1165 auto it = infos.find(lightId);
1166 if (it == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001167 return std::nullopt;
1168 }
1169 std::string buffer;
1170 if (!base::ReadFileToString(it->second.path / LIGHT_NODES.at(InputLightClass::BRIGHTNESS),
1171 &buffer)) {
1172 return std::nullopt;
1173 }
1174 return std::stoi(buffer);
1175}
1176
1177std::optional<std::unordered_map<LightColor, int32_t>> EventHub::getLightIntensities(
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001178 int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001179 std::scoped_lock _l(mLock);
1180
Chris Yee2b1e5c2021-03-10 22:45:12 -08001181 const auto infos = getLightInfoLocked(deviceId);
1182 auto lightIt = infos.find(lightId);
1183 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001184 return std::nullopt;
1185 }
1186
1187 auto ret =
1188 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1189
1190 if (!ret.has_value()) {
1191 return std::nullopt;
1192 }
1193 std::array<LightColor, COLOR_NUM> colors = ret.value();
1194
1195 std::string intensityStr;
1196 if (!base::ReadFileToString(lightIt->second.path /
1197 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY),
1198 &intensityStr)) {
1199 return std::nullopt;
1200 }
1201
1202 // Intensity node outputs 3 color values
1203 std::regex intensityPattern("([0-9]+)\\s([0-9]+)\\s([0-9]+)[\\n]");
1204 std::smatch results;
1205
1206 if (!std::regex_match(intensityStr, results, intensityPattern)) {
1207 return std::nullopt;
1208 }
1209 std::unordered_map<LightColor, int32_t> intensities;
1210 for (size_t i = 1; i < results.size(); i++) {
1211 int value = std::stoi(results[i].str());
1212 intensities.emplace(colors[i - 1], value);
1213 }
1214 return intensities;
1215}
1216
1217void EventHub::setLightBrightness(int32_t deviceId, int32_t lightId, int32_t brightness) {
1218 std::scoped_lock _l(mLock);
1219
Chris Yee2b1e5c2021-03-10 22:45:12 -08001220 const auto infos = getLightInfoLocked(deviceId);
1221 auto lightIt = infos.find(lightId);
1222 if (lightIt == infos.end()) {
1223 ALOGE("%s lightId %d not found ", __func__, lightId);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001224 return;
1225 }
1226
1227 if (!base::WriteStringToFile(std::to_string(brightness),
1228 lightIt->second.path /
1229 LIGHT_NODES.at(InputLightClass::BRIGHTNESS))) {
1230 ALOGE("Can not write to file, error: %s", strerror(errno));
1231 }
1232}
1233
1234void EventHub::setLightIntensities(int32_t deviceId, int32_t lightId,
1235 std::unordered_map<LightColor, int32_t> intensities) {
1236 std::scoped_lock _l(mLock);
1237
Chris Yee2b1e5c2021-03-10 22:45:12 -08001238 const auto infos = getLightInfoLocked(deviceId);
1239 auto lightIt = infos.find(lightId);
1240 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001241 ALOGE("Light Id %d does not exist.", lightId);
1242 return;
1243 }
1244
1245 auto ret =
1246 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1247
1248 if (!ret.has_value()) {
1249 return;
1250 }
1251 std::array<LightColor, COLOR_NUM> colors = ret.value();
1252
1253 std::string rgbStr;
1254 for (size_t i = 0; i < COLOR_NUM; i++) {
1255 auto it = intensities.find(colors[i]);
1256 if (it != intensities.end()) {
1257 rgbStr += std::to_string(it->second);
1258 // Insert space between colors
1259 if (i < COLOR_NUM - 1) {
1260 rgbStr += " ";
1261 }
1262 }
1263 }
1264 // Append new line
1265 rgbStr += "\n";
1266
1267 if (!base::WriteStringToFile(rgbStr,
1268 lightIt->second.path /
1269 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY))) {
1270 ALOGE("Can not write to file, error: %s", strerror(errno));
1271 }
1272}
1273
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001274InputDeviceCountryCode EventHub::getCountryCode(int32_t deviceId) const {
1275 std::scoped_lock _l(mLock);
1276 Device* device = getDeviceLocked(deviceId);
1277 if (device == nullptr || !device->associatedDevice) {
1278 return InputDeviceCountryCode::INVALID;
1279 }
1280 return device->associatedDevice->countryCode;
1281}
1282
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001283void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Chris Ye87143712020-11-10 05:05:58 +00001284 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001285
1286 mExcludedDevices = devices;
1287}
1288
1289bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
Chris Ye87143712020-11-10 05:05:58 +00001290 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001291 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001292 if (device != nullptr && scanCode >= 0 && scanCode <= KEY_MAX) {
1293 return device->keyBitmask.test(scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001294 }
1295 return false;
1296}
1297
Arthur Hungcb40a002021-08-03 14:31:01 +00001298bool EventHub::hasKeyCode(int32_t deviceId, int32_t keyCode) const {
1299 std::scoped_lock _l(mLock);
1300 Device* device = getDeviceLocked(deviceId);
1301 if (device != nullptr) {
1302 return device->hasKeycodeLocked(keyCode);
1303 }
1304 return false;
1305}
1306
Michael Wrightd02c5b62014-02-10 15:10:22 -08001307bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
Chris Ye87143712020-11-10 05:05:58 +00001308 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001309 Device* device = getDeviceLocked(deviceId);
1310 int32_t sc;
Chris Ye989bb932020-07-04 16:18:59 -07001311 if (device != nullptr && device->mapLed(led, &sc) == NO_ERROR) {
Chris Ye66fbac32020-07-06 20:36:43 -07001312 return device->ledBitmask.test(sc);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001313 }
1314 return false;
1315}
1316
1317void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
Chris Ye87143712020-11-10 05:05:58 +00001318 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001319 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -07001320 if (device != nullptr && device->hasValidFd()) {
1321 device->setLedStateLocked(led, on);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001322 }
1323}
1324
1325void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001326 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001327 outVirtualKeys.clear();
1328
Chris Ye87143712020-11-10 05:05:58 +00001329 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001330 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001331 if (device != nullptr && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001332 const std::vector<VirtualKeyDefinition> virtualKeys =
1333 device->virtualKeyMap->getVirtualKeys();
1334 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001335 }
1336}
1337
Chris Ye3a1e4462020-08-12 10:13:15 -07001338const std::shared_ptr<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001339 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001340 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001341 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001342 return device->getKeyCharacterMap();
1343 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001344 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001345}
1346
Chris Ye3a1e4462020-08-12 10:13:15 -07001347bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, std::shared_ptr<KeyCharacterMap> map) {
Chris Ye87143712020-11-10 05:05:58 +00001348 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001349 Device* device = getDeviceLocked(deviceId);
Philip Junker90bc9492021-12-10 18:39:42 +01001350 if (device == nullptr || map == nullptr || device->keyMap.keyCharacterMap == nullptr) {
1351 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001352 }
Philip Junker90bc9492021-12-10 18:39:42 +01001353 device->keyMap.keyCharacterMap->combine(*map);
1354 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001355}
1356
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001357static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
1358 std::string rawDescriptor;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001359 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001360 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001361 if (!identifier.uniqueId.empty()) {
1362 rawDescriptor += "uniqueId:";
1363 rawDescriptor += identifier.uniqueId;
Josh Bartel938632f2022-07-19 15:34:22 -05001364 }
1365 if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001366 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001367 }
1368
1369 if (identifier.vendor == 0 && identifier.product == 0) {
1370 // If we don't know the vendor and product id, then the device is probably
1371 // built-in so we need to rely on other information to uniquely identify
1372 // the input device. Usually we try to avoid relying on the device name or
1373 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001374 if (!identifier.name.empty()) {
1375 rawDescriptor += "name:";
1376 rawDescriptor += identifier.name;
1377 } else if (!identifier.location.empty()) {
1378 rawDescriptor += "location:";
1379 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001380 }
1381 }
1382 identifier.descriptor = sha1(rawDescriptor);
1383 return rawDescriptor;
1384}
1385
1386void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
1387 // Compute a device descriptor that uniquely identifies the device.
1388 // The descriptor is assumed to be a stable identifier. Its value should not
1389 // change between reboots, reconnections, firmware updates or new releases
1390 // of Android. In practice we sometimes get devices that cannot be uniquely
1391 // identified. In this case we enforce uniqueness between connected devices.
1392 // Ideally, we also want the descriptor to be short and relatively opaque.
Josh Bartel938632f2022-07-19 15:34:22 -05001393 // Note that we explicitly do not use the path or location for external devices
1394 // as their path or location will change as they are plugged/unplugged or moved
1395 // to different ports. We do fallback to using name and location in the case of
1396 // internal devices which are detected by the vendor and product being 0 in
1397 // generateDescriptor. If two identical descriptors are detected we will fallback
1398 // to using a 'nonce' and incrementing it until the new descriptor no longer has
1399 // a match with any existing descriptors.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001400
1401 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001402 std::string rawDescriptor = generateDescriptor(identifier);
Josh Bartel938632f2022-07-19 15:34:22 -05001403 // Enforce that the generated descriptor is unique.
1404 while (hasDeviceWithDescriptorLocked(identifier.descriptor)) {
1405 identifier.nonce++;
1406 rawDescriptor = generateDescriptor(identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001407 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001408 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001409 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001410}
1411
Prabir Pradhancb42b472022-08-23 16:01:19 +00001412std::shared_ptr<const EventHub::AssociatedDevice> EventHub::obtainAssociatedDeviceLocked(
1413 const std::filesystem::path& devicePath) const {
1414 const std::optional<std::filesystem::path> sysfsRootPathOpt =
1415 getSysfsRootPath(devicePath.c_str());
1416 if (!sysfsRootPathOpt) {
1417 return nullptr;
1418 }
1419
1420 const auto& path = *sysfsRootPathOpt;
1421 for (const auto& [id, dev] : mDevices) {
1422 if (dev->associatedDevice && dev->associatedDevice->sysfsRootPath == path) {
1423 return dev->associatedDevice;
1424 }
1425 }
1426
1427 return std::make_shared<AssociatedDevice>(
1428 AssociatedDevice{.sysfsRootPath = path,
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001429 .countryCode = readCountryCodeLocked(path),
Prabir Pradhancb42b472022-08-23 16:01:19 +00001430 .batteryInfos = readBatteryConfiguration(path),
1431 .lightInfos = readLightsConfiguration(path)});
1432}
1433
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001434void EventHub::vibrate(int32_t deviceId, const VibrationElement& element) {
Chris Ye87143712020-11-10 05:05:58 +00001435 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001436 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001437 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001438 ff_effect effect;
1439 memset(&effect, 0, sizeof(effect));
1440 effect.type = FF_RUMBLE;
1441 effect.id = device->ffEffectId;
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001442 // evdev FF_RUMBLE effect only supports two channels of vibration.
Chris Ye6393a262020-08-04 19:41:36 -07001443 effect.u.rumble.strong_magnitude = element.getMagnitude(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1444 effect.u.rumble.weak_magnitude = element.getMagnitude(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001445 effect.replay.length = element.duration.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001446 effect.replay.delay = 0;
1447 if (ioctl(device->fd, EVIOCSFF, &effect)) {
1448 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001449 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001450 return;
1451 }
1452 device->ffEffectId = effect.id;
1453
1454 struct input_event ev;
1455 ev.time.tv_sec = 0;
1456 ev.time.tv_usec = 0;
1457 ev.type = EV_FF;
1458 ev.code = device->ffEffectId;
1459 ev.value = 1;
1460 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1461 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001462 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001463 return;
1464 }
1465 device->ffEffectPlaying = true;
1466 }
1467}
1468
1469void EventHub::cancelVibrate(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001470 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001471 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001472 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001473 if (device->ffEffectPlaying) {
1474 device->ffEffectPlaying = false;
1475
1476 struct input_event ev;
1477 ev.time.tv_sec = 0;
1478 ev.time.tv_usec = 0;
1479 ev.type = EV_FF;
1480 ev.code = device->ffEffectId;
1481 ev.value = 0;
1482 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1483 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001484 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001485 return;
1486 }
1487 }
1488 }
1489}
1490
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001491std::vector<int32_t> EventHub::getVibratorIds(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001492 std::scoped_lock _l(mLock);
1493 std::vector<int32_t> vibrators;
1494 Device* device = getDeviceLocked(deviceId);
1495 if (device != nullptr && device->hasValidFd() &&
1496 device->classes.test(InputDeviceClass::VIBRATOR)) {
1497 vibrators.push_back(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1498 vibrators.push_back(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
1499 }
1500 return vibrators;
1501}
1502
Josh Bartel938632f2022-07-19 15:34:22 -05001503/**
1504 * Checks both mDevices and mOpeningDevices for a device with the descriptor passed.
1505 */
1506bool EventHub::hasDeviceWithDescriptorLocked(const std::string& descriptor) const {
1507 for (const auto& device : mOpeningDevices) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001508 if (descriptor == device->identifier.descriptor) {
Josh Bartel938632f2022-07-19 15:34:22 -05001509 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001510 }
1511 }
Josh Bartel938632f2022-07-19 15:34:22 -05001512
1513 for (const auto& [id, device] : mDevices) {
1514 if (descriptor == device->identifier.descriptor) {
1515 return true;
1516 }
1517 }
1518 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001519}
1520
1521EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001522 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001523 deviceId = mBuiltInKeyboardId;
1524 }
Chris Ye989bb932020-07-04 16:18:59 -07001525 const auto& it = mDevices.find(deviceId);
1526 return it != mDevices.end() ? it->second.get() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001527}
1528
Chris Ye8594e192020-07-14 10:34:06 -07001529EventHub::Device* EventHub::getDeviceByPathLocked(const std::string& devicePath) const {
Chris Ye989bb932020-07-04 16:18:59 -07001530 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001531 if (device->path == devicePath) {
Chris Ye989bb932020-07-04 16:18:59 -07001532 return device.get();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001533 }
1534 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001535 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001536}
1537
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001538/**
1539 * The file descriptor could be either input device, or a video device (associated with a
1540 * specific input device). Check both cases here, and return the device that this event
1541 * belongs to. Caller can compare the fd's once more to determine event type.
1542 * Looks through all input devices, and only attached video devices. Unattached video
1543 * devices are ignored.
1544 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001545EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
Chris Ye989bb932020-07-04 16:18:59 -07001546 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001547 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001548 // This is an input device event
Chris Ye989bb932020-07-04 16:18:59 -07001549 return device.get();
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001550 }
1551 if (device->videoDevice && device->videoDevice->getFd() == fd) {
1552 // This is a video device event
Chris Ye989bb932020-07-04 16:18:59 -07001553 return device.get();
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001554 }
1555 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001556 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
1557 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001558 return nullptr;
1559}
1560
Chris Yee2b1e5c2021-03-10 22:45:12 -08001561std::optional<int32_t> EventHub::getBatteryCapacity(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001562 std::filesystem::path batteryPath;
1563 {
1564 // Do not read the sysfs node to get the battery state while holding
1565 // the EventHub lock. For some peripheral devices, reading battery state
1566 // can be broken and take 5+ seconds. Holding the lock in this case would
1567 // block all other event processing during this time. For now, we assume this
1568 // call never happens on the InputReader thread and read the sysfs node outside
1569 // the lock to prevent event processing from being blocked by this call.
1570 std::scoped_lock _l(mLock);
Kim Low03ea0352020-11-06 12:45:07 -08001571
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001572 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001573 auto it = infos.find(batteryId);
1574 if (it == infos.end()) {
1575 return std::nullopt;
1576 }
1577 batteryPath = it->second.path;
1578 } // release lock
1579
Chris Yee2b1e5c2021-03-10 22:45:12 -08001580 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001581
1582 // Some devices report battery capacity as an integer through the "capacity" file
Andy Chenf9f1a022022-08-29 20:07:10 -04001583 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001584 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001585 return std::stoi(base::Trim(buffer));
Kim Low03ea0352020-11-06 12:45:07 -08001586 }
1587
1588 // Other devices report capacity as an enum value POWER_SUPPLY_CAPACITY_LEVEL_XXX
1589 // These values are taken from kernel source code include/linux/power_supply.h
Andy Chenf9f1a022022-08-29 20:07:10 -04001590 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY_LEVEL),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001591 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001592 // Remove any white space such as trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001593 const auto levelIt = BATTERY_LEVEL.find(base::Trim(buffer));
1594 if (levelIt != BATTERY_LEVEL.end()) {
1595 return levelIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001596 }
1597 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001598
Kim Low03ea0352020-11-06 12:45:07 -08001599 return std::nullopt;
1600}
1601
Chris Yee2b1e5c2021-03-10 22:45:12 -08001602std::optional<int32_t> EventHub::getBatteryStatus(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001603 std::filesystem::path batteryPath;
1604 {
1605 // Do not read the sysfs node to get the battery state while holding
1606 // the EventHub lock. For some peripheral devices, reading battery state
1607 // can be broken and take 5+ seconds. Holding the lock in this case would
1608 // block all other event processing during this time. For now, we assume this
1609 // call never happens on the InputReader thread and read the sysfs node outside
1610 // the lock to prevent event processing from being blocked by this call.
1611 std::scoped_lock _l(mLock);
1612
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001613 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001614 auto it = infos.find(batteryId);
1615 if (it == infos.end()) {
1616 return std::nullopt;
1617 }
1618 batteryPath = it->second.path;
1619 } // release lock
1620
Chris Yee2b1e5c2021-03-10 22:45:12 -08001621 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001622
Andy Chenf9f1a022022-08-29 20:07:10 -04001623 if (!base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::STATUS),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001624 &buffer)) {
Kim Low03ea0352020-11-06 12:45:07 -08001625 ALOGE("Failed to read sysfs battery info: %s", strerror(errno));
1626 return std::nullopt;
1627 }
1628
Chris Yed1936772021-02-22 10:30:40 -08001629 // Remove white space like trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001630 const auto statusIt = BATTERY_STATUS.find(base::Trim(buffer));
1631 if (statusIt != BATTERY_STATUS.end()) {
1632 return statusIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001633 }
1634
1635 return std::nullopt;
1636}
1637
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001638std::vector<RawEvent> EventHub::getEvents(int timeoutMillis) {
Chris Ye87143712020-11-10 05:05:58 +00001639 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001640
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001641 constexpr size_t bufferSize = EVENT_BUFFER_SIZE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001642 struct input_event readBuffer[bufferSize];
1643
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001644 std::vector<RawEvent> events;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001645 size_t capacity = bufferSize;
1646 bool awoken = false;
1647 for (;;) {
1648 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
1649
1650 // Reopen input devices if needed.
1651 if (mNeedToReopenDevices) {
1652 mNeedToReopenDevices = false;
1653
1654 ALOGI("Reopening all input devices due to a configuration change.");
1655
1656 closeAllDevicesLocked();
1657 mNeedToScanDevices = true;
1658 break; // return to the caller before we actually rescan
1659 }
1660
1661 // Report any devices that had last been added/removed.
Chris Ye989bb932020-07-04 16:18:59 -07001662 for (auto it = mClosingDevices.begin(); it != mClosingDevices.end();) {
1663 std::unique_ptr<Device> device = std::move(*it);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001664 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001665 const int32_t deviceId = (device->id == mBuiltInKeyboardId)
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001666 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
1667 : device->id;
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001668 events.push_back({
1669 .when = now,
1670 .deviceId = deviceId,
1671 .type = DEVICE_REMOVED,
1672 });
Chris Ye989bb932020-07-04 16:18:59 -07001673 it = mClosingDevices.erase(it);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001674 mNeedToSendFinishedDeviceScan = true;
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001675 if (events.size() == capacity) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001676 break;
1677 }
1678 }
1679
1680 if (mNeedToScanDevices) {
1681 mNeedToScanDevices = false;
1682 scanDevicesLocked();
1683 mNeedToSendFinishedDeviceScan = true;
1684 }
1685
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001686 while (!mOpeningDevices.empty()) {
1687 std::unique_ptr<Device> device = std::move(*mOpeningDevices.rbegin());
1688 mOpeningDevices.pop_back();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001689 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001690 const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1691 events.push_back({
1692 .when = now,
1693 .deviceId = deviceId,
1694 .type = DEVICE_ADDED,
1695 });
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001696
1697 // Try to find a matching video device by comparing device names
1698 for (auto it = mUnattachedVideoDevices.begin(); it != mUnattachedVideoDevices.end();
1699 it++) {
1700 std::unique_ptr<TouchVideoDevice>& videoDevice = *it;
Chris Yed3fef462021-03-07 17:10:08 -08001701 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001702 // videoDevice was transferred to 'device'
1703 it = mUnattachedVideoDevices.erase(it);
1704 break;
1705 }
1706 }
1707
1708 auto [dev_it, inserted] = mDevices.insert_or_assign(device->id, std::move(device));
1709 if (!inserted) {
Chris Ye989bb932020-07-04 16:18:59 -07001710 ALOGW("Device id %d exists, replaced.", device->id);
1711 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001712 mNeedToSendFinishedDeviceScan = true;
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001713 if (events.size() == capacity) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001714 break;
1715 }
1716 }
1717
1718 if (mNeedToSendFinishedDeviceScan) {
1719 mNeedToSendFinishedDeviceScan = false;
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001720 events.push_back({
1721 .when = now,
1722 .type = FINISHED_DEVICE_SCAN,
1723 });
1724 if (events.size() == capacity) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001725 break;
1726 }
1727 }
1728
1729 // Grab the next input event.
1730 bool deviceChanged = false;
1731 while (mPendingEventIndex < mPendingEventCount) {
1732 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001733 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001734 if (eventItem.events & EPOLLIN) {
1735 mPendingINotify = true;
1736 } else {
1737 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
1738 }
1739 continue;
1740 }
1741
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001742 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001743 if (eventItem.events & EPOLLIN) {
1744 ALOGV("awoken after wake()");
1745 awoken = true;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001746 char wakeReadBuffer[16];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001747 ssize_t nRead;
1748 do {
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001749 nRead = read(mWakeReadPipeFd, wakeReadBuffer, sizeof(wakeReadBuffer));
1750 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(wakeReadBuffer));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001751 } else {
1752 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001753 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001754 }
1755 continue;
1756 }
1757
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001758 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Chris Ye989bb932020-07-04 16:18:59 -07001759 if (device == nullptr) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001760 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
1761 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001762 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001763 continue;
1764 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001765 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
1766 if (eventItem.events & EPOLLIN) {
1767 size_t numFrames = device->videoDevice->readAndQueueFrames();
1768 if (numFrames == 0) {
1769 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001770 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001771 }
1772 } else if (eventItem.events & EPOLLHUP) {
1773 // TODO(b/121395353) - consider adding EPOLLRDHUP
1774 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001775 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001776 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1777 device->videoDevice = nullptr;
1778 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001779 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1780 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001781 ALOG_ASSERT(!DEBUG);
1782 }
1783 continue;
1784 }
1785 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -08001786 if (eventItem.events & EPOLLIN) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001787 int32_t readSize =
1788 read(device->fd, readBuffer, sizeof(struct input_event) * capacity);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001789 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
1790 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -07001791 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001792 " bufferSize: %zu capacity: %zu errno: %d)\n",
1793 device->fd, readSize, bufferSize, capacity, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001794 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001795 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001796 } else if (readSize < 0) {
1797 if (errno != EAGAIN && errno != EINTR) {
1798 ALOGW("could not get event (errno=%d)", errno);
1799 }
1800 } else if ((readSize % sizeof(struct input_event)) != 0) {
1801 ALOGE("could not get event (wrong size: %d)", readSize);
1802 } else {
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001803 const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001804
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001805 const size_t count = size_t(readSize) / sizeof(struct input_event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001806 for (size_t i = 0; i < count; i++) {
1807 struct input_event& iev = readBuffer[i];
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001808 events.push_back({
1809 .when = processEventTimestamp(iev),
1810 .readTime = systemTime(SYSTEM_TIME_MONOTONIC),
1811 .deviceId = deviceId,
1812 .type = iev.type,
1813 .code = iev.code,
1814 .value = iev.value,
1815 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08001816 }
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001817 if (events.size() >= capacity) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001818 // The result buffer is full. Reset the pending event index
1819 // so we will try to read the device again on the next iteration.
1820 mPendingEventIndex -= 1;
1821 break;
1822 }
1823 }
1824 } else if (eventItem.events & EPOLLHUP) {
1825 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001826 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001827 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001828 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001829 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001830 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1831 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001832 }
1833 }
1834
1835 // readNotify() will modify the list of devices so this must be done after
1836 // processing all other events to ensure that we read all remaining events
1837 // before closing the devices.
1838 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
1839 mPendingINotify = false;
Prabir Pradhan952e65b2022-06-23 17:49:55 +00001840 const auto res = readNotifyLocked();
1841 if (!res.ok()) {
1842 ALOGW("Failed to read from inotify: %s", res.error().message().c_str());
1843 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001844 deviceChanged = true;
1845 }
1846
1847 // Report added or removed devices immediately.
1848 if (deviceChanged) {
1849 continue;
1850 }
1851
1852 // Return now if we have collected any events or if we were explicitly awoken.
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001853 if (!events.empty() || awoken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001854 break;
1855 }
1856
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001857 // Poll for events.
1858 // When a device driver has pending (unread) events, it acquires
1859 // a kernel wake lock. Once the last pending event has been read, the device
1860 // driver will release the kernel wake lock, but the epoll will hold the wakelock,
1861 // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
1862 // is called again for the same fd that produced the event.
1863 // Thus the system can only sleep if there are no events pending or
1864 // currently being processed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001865 //
1866 // The timeout is advisory only. If the device is asleep, it will not wake just to
1867 // service the timeout.
1868 mPendingEventIndex = 0;
1869
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001870 mLock.unlock(); // release lock before poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001871
1872 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1873
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001874 mLock.lock(); // reacquire lock after poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001875
1876 if (pollResult == 0) {
1877 // Timed out.
1878 mPendingEventCount = 0;
1879 break;
1880 }
1881
1882 if (pollResult < 0) {
1883 // An error occurred.
1884 mPendingEventCount = 0;
1885
1886 // Sleep after errors to avoid locking up the system.
1887 // Hopefully the error is transient.
1888 if (errno != EINTR) {
1889 ALOGW("poll failed (errno=%d)\n", errno);
1890 usleep(100000);
1891 }
1892 } else {
1893 // Some events occurred.
1894 mPendingEventCount = size_t(pollResult);
1895 }
1896 }
1897
1898 // All done, return the number of events we read.
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001899 return events;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001900}
1901
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001902std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001903 std::scoped_lock _l(mLock);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001904
1905 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001906 if (device == nullptr || !device->videoDevice) {
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001907 return {};
1908 }
1909 return device->videoDevice->consumeFrames();
1910}
1911
Michael Wrightd02c5b62014-02-10 15:10:22 -08001912void EventHub::wake() {
1913 ALOGV("wake() called");
1914
1915 ssize_t nWrite;
1916 do {
1917 nWrite = write(mWakeWritePipeFd, "W", 1);
1918 } while (nWrite == -1 && errno == EINTR);
1919
1920 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001921 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001922 }
1923}
1924
1925void EventHub::scanDevicesLocked() {
Usama Arifb27c8e62021-06-03 16:44:09 +01001926 status_t result;
1927 std::error_code errorCode;
1928
1929 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
1930 result = scanDirLocked(DEVICE_INPUT_PATH);
1931 if (result < 0) {
1932 ALOGE("scan dir failed for %s", DEVICE_INPUT_PATH);
1933 }
1934 } else {
1935 if (errorCode) {
1936 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
1937 errorCode.message().c_str());
1938 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001939 }
Philip Quinn39b81682019-01-09 22:20:39 -08001940 if (isV4lScanningEnabled()) {
Usama Arifb27c8e62021-06-03 16:44:09 +01001941 result = scanVideoDirLocked(DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08001942 if (result != OK) {
Usama Arifb27c8e62021-06-03 16:44:09 +01001943 ALOGE("scan video dir failed for %s", DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08001944 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001945 }
Chris Ye989bb932020-07-04 16:18:59 -07001946 if (mDevices.find(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) == mDevices.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001947 createVirtualKeyboardLocked();
1948 }
1949}
1950
1951// ----------------------------------------------------------------------------
1952
Michael Wrightd02c5b62014-02-10 15:10:22 -08001953static const int32_t GAMEPAD_KEYCODES[] = {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001954 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C, //
1955 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z, //
1956 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1, //
1957 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2, //
1958 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR, //
1959 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE, //
Michael Wrightd02c5b62014-02-10 15:10:22 -08001960};
1961
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001962status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001963 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001964 struct epoll_event eventItem = {};
1965 eventItem.events = EPOLLIN | EPOLLWAKEUP;
1966 eventItem.data.fd = fd;
1967 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1968 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001969 return -errno;
1970 }
1971 return OK;
1972}
1973
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001974status_t EventHub::unregisterFdFromEpoll(int fd) {
1975 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
1976 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
1977 return -errno;
1978 }
1979 return OK;
1980}
1981
Chris Ye989bb932020-07-04 16:18:59 -07001982status_t EventHub::registerDeviceForEpollLocked(Device& device) {
1983 status_t result = registerFdForEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001984 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07001985 ALOGE("Could not add input device fd to epoll for device %" PRId32, device.id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001986 return result;
1987 }
Chris Ye989bb932020-07-04 16:18:59 -07001988 if (device.videoDevice) {
1989 registerVideoDeviceForEpollLocked(*device.videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001990 }
1991 return result;
1992}
1993
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001994void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
1995 status_t result = registerFdForEpoll(videoDevice.getFd());
1996 if (result != OK) {
1997 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
1998 }
1999}
2000
Chris Ye989bb932020-07-04 16:18:59 -07002001status_t EventHub::unregisterDeviceFromEpollLocked(Device& device) {
2002 if (device.hasValidFd()) {
2003 status_t result = unregisterFdFromEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002004 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07002005 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device.id);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002006 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002007 }
2008 }
Chris Ye989bb932020-07-04 16:18:59 -07002009 if (device.videoDevice) {
2010 unregisterVideoDeviceFromEpollLocked(*device.videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002011 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002012 return OK;
2013}
2014
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002015void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
2016 if (videoDevice.hasValidFd()) {
2017 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
2018 if (result != OK) {
2019 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002020 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002021 }
2022 }
2023}
2024
Chris Yed3fef462021-03-07 17:10:08 -08002025void EventHub::reportDeviceAddedForStatisticsLocked(const InputDeviceIdentifier& identifier,
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002026 ftl::Flags<InputDeviceClass> classes) {
Chris Ye657c2f02021-05-25 16:24:37 -07002027 SHA256_CTX ctx;
2028 SHA256_Init(&ctx);
2029 SHA256_Update(&ctx, reinterpret_cast<const uint8_t*>(identifier.uniqueId.c_str()),
2030 identifier.uniqueId.size());
2031 std::array<uint8_t, SHA256_DIGEST_LENGTH> digest;
2032 SHA256_Final(digest.data(), &ctx);
2033
2034 std::string obfuscatedId;
2035 for (size_t i = 0; i < OBFUSCATED_LENGTH; i++) {
2036 obfuscatedId += StringPrintf("%02x", digest[i]);
2037 }
2038
Chris Yed3fef462021-03-07 17:10:08 -08002039 android::util::stats_write(android::util::INPUTDEVICE_REGISTERED, identifier.name.c_str(),
2040 identifier.vendor, identifier.product, identifier.version,
Chris Ye657c2f02021-05-25 16:24:37 -07002041 identifier.bus, obfuscatedId.c_str(), classes.get());
Chris Yed3fef462021-03-07 17:10:08 -08002042}
2043
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002044void EventHub::openDeviceLocked(const std::string& devicePath) {
2045 // If an input device happens to register around the time when EventHub's constructor runs, it
2046 // is possible that the same input event node (for example, /dev/input/event3) will be noticed
2047 // in both 'inotify' callback and also in the 'scanDirLocked' pass. To prevent duplicate devices
2048 // from getting registered, ensure that this path is not already covered by an existing device.
2049 for (const auto& [deviceId, device] : mDevices) {
2050 if (device->path == devicePath) {
2051 return; // device was already registered
2052 }
2053 }
2054
Michael Wrightd02c5b62014-02-10 15:10:22 -08002055 char buffer[80];
2056
Chris Ye8594e192020-07-14 10:34:06 -07002057 ALOGV("Opening device: %s", devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002058
Chris Ye8594e192020-07-14 10:34:06 -07002059 int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002060 if (fd < 0) {
Chris Ye8594e192020-07-14 10:34:06 -07002061 ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002062 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002063 }
2064
2065 InputDeviceIdentifier identifier;
2066
2067 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002068 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Chris Ye8594e192020-07-14 10:34:06 -07002069 ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002070 } else {
2071 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002072 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002073 }
2074
2075 // Check to see if the device is on our excluded list
2076 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002077 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002078 if (identifier.name == item) {
Chris Ye8594e192020-07-14 10:34:06 -07002079 ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002080 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002081 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002082 }
2083 }
2084
2085 // Get device driver version.
2086 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002087 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Chris Ye8594e192020-07-14 10:34:06 -07002088 ALOGE("could not get driver version for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002089 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002090 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002091 }
2092
2093 // Get device identifier.
2094 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002095 if (ioctl(fd, EVIOCGID, &inputId)) {
Chris Ye8594e192020-07-14 10:34:06 -07002096 ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002097 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002098 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002099 }
2100 identifier.bus = inputId.bustype;
2101 identifier.product = inputId.product;
2102 identifier.vendor = inputId.vendor;
2103 identifier.version = inputId.version;
2104
2105 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002106 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
2107 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002108 } else {
2109 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002110 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002111 }
2112
2113 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002114 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
2115 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002116 } else {
2117 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002118 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002119 }
2120
2121 // Fill in the descriptor.
2122 assignDescriptorLocked(identifier);
2123
Michael Wrightd02c5b62014-02-10 15:10:22 -08002124 // Allocate device. (The device object takes ownership of the fd at this point.)
2125 int32_t deviceId = mNextDeviceId++;
Prabir Pradhancb42b472022-08-23 16:01:19 +00002126 std::unique_ptr<Device> device =
2127 std::make_unique<Device>(fd, deviceId, devicePath, identifier,
2128 obtainAssociatedDeviceLocked(devicePath));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002129
Chris Ye8594e192020-07-14 10:34:06 -07002130 ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002131 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002132 " vendor %04x\n"
2133 " product %04x\n"
2134 " version %04x\n",
2135 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002136 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
2137 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
2138 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
2139 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002140 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
2141 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002142
2143 // Load the configuration file for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002144 device->loadConfigurationLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002145
2146 // Figure out the kinds of events the device reports.
Chris Ye66fbac32020-07-06 20:36:43 -07002147 device->readDeviceBitMask(EVIOCGBIT(EV_KEY, 0), device->keyBitmask);
2148 device->readDeviceBitMask(EVIOCGBIT(EV_ABS, 0), device->absBitmask);
2149 device->readDeviceBitMask(EVIOCGBIT(EV_REL, 0), device->relBitmask);
2150 device->readDeviceBitMask(EVIOCGBIT(EV_SW, 0), device->swBitmask);
2151 device->readDeviceBitMask(EVIOCGBIT(EV_LED, 0), device->ledBitmask);
2152 device->readDeviceBitMask(EVIOCGBIT(EV_FF, 0), device->ffBitmask);
Chris Yef59a2f42020-10-16 12:55:26 -07002153 device->readDeviceBitMask(EVIOCGBIT(EV_MSC, 0), device->mscBitmask);
Chris Ye66fbac32020-07-06 20:36:43 -07002154 device->readDeviceBitMask(EVIOCGPROP(0), device->propBitmask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002155
2156 // See if this is a keyboard. Ignore everything in the button range except for
2157 // joystick and gamepad buttons which are handled like keyboards for the most part.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002158 bool haveKeyboardKeys =
Chris Ye66fbac32020-07-06 20:36:43 -07002159 device->keyBitmask.any(0, BTN_MISC) || device->keyBitmask.any(BTN_WHEEL, KEY_MAX + 1);
2160 bool haveGamepadButtons = device->keyBitmask.any(BTN_MISC, BTN_MOUSE) ||
2161 device->keyBitmask.any(BTN_JOYSTICK, BTN_DIGI);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002162 if (haveKeyboardKeys || haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002163 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002164 }
2165
2166 // See if this is a cursor device such as a trackball or mouse.
Chris Ye66fbac32020-07-06 20:36:43 -07002167 if (device->keyBitmask.test(BTN_MOUSE) && device->relBitmask.test(REL_X) &&
2168 device->relBitmask.test(REL_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002169 device->classes |= InputDeviceClass::CURSOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002170 }
2171
Prashant Malani1941ff52015-08-11 18:29:28 -07002172 // See if this is a rotary encoder type device.
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07002173 std::string deviceType;
2174 if (device->configuration && device->configuration->tryGetProperty("device.type", deviceType)) {
2175 if (deviceType == "rotaryEncoder") {
Chris Ye1b0c7342020-07-28 21:57:03 -07002176 device->classes |= InputDeviceClass::ROTARY_ENCODER;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002177 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002178 }
2179
Michael Wrightd02c5b62014-02-10 15:10:22 -08002180 // See if this is a touch pad.
2181 // Is this a new modern multi-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002182 if (device->absBitmask.test(ABS_MT_POSITION_X) && device->absBitmask.test(ABS_MT_POSITION_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002183 // Some joysticks such as the PS3 controller report axes that conflict
2184 // with the ABS_MT range. Try to confirm that the device really is
2185 // a touch screen.
Chris Ye66fbac32020-07-06 20:36:43 -07002186 if (device->keyBitmask.test(BTN_TOUCH) || !haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002187 device->classes |= (InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002188 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002189 // Is this an old style single-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002190 } else if (device->keyBitmask.test(BTN_TOUCH) && device->absBitmask.test(ABS_X) &&
2191 device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002192 device->classes |= InputDeviceClass::TOUCH;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002193 // Is this a BT stylus?
Chris Ye66fbac32020-07-06 20:36:43 -07002194 } else if ((device->absBitmask.test(ABS_PRESSURE) || device->keyBitmask.test(BTN_TOUCH)) &&
2195 !device->absBitmask.test(ABS_X) && !device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002196 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -07002197 // Keyboard will try to claim some of the buttons but we really want to reserve those so we
2198 // can fuse it with the touch screen data, so just take them back. Note this means an
2199 // external stylus cannot also be a keyboard device.
Chris Ye1b0c7342020-07-28 21:57:03 -07002200 device->classes &= ~InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002201 }
2202
2203 // See if this device is a joystick.
2204 // Assumes that joysticks always have gamepad buttons in order to distinguish them
2205 // from other devices such as accelerometers that also have absolute axes.
2206 if (haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002207 auto assumedClasses = device->classes | InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002208 for (int i = 0; i <= ABS_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002209 if (device->absBitmask.test(i) &&
Chris Ye1b0c7342020-07-28 21:57:03 -07002210 (getAbsAxisUsage(i, assumedClasses).test(InputDeviceClass::JOYSTICK))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002211 device->classes = assumedClasses;
2212 break;
2213 }
2214 }
2215 }
2216
Chris Yef59a2f42020-10-16 12:55:26 -07002217 // Check whether this device is an accelerometer.
2218 if (device->propBitmask.test(INPUT_PROP_ACCELEROMETER)) {
2219 device->classes |= InputDeviceClass::SENSOR;
2220 }
2221
Michael Wrightd02c5b62014-02-10 15:10:22 -08002222 // Check whether this device has switches.
2223 for (int i = 0; i <= SW_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002224 if (device->swBitmask.test(i)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002225 device->classes |= InputDeviceClass::SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002226 break;
2227 }
2228 }
2229
2230 // Check whether this device supports the vibrator.
Chris Ye66fbac32020-07-06 20:36:43 -07002231 if (device->ffBitmask.test(FF_RUMBLE)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002232 device->classes |= InputDeviceClass::VIBRATOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002233 }
2234
2235 // Configure virtual keys.
Chris Ye1b0c7342020-07-28 21:57:03 -07002236 if ((device->classes.test(InputDeviceClass::TOUCH))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002237 // Load the virtual keys for the touch screen, if any.
2238 // We do this now so that we can make sure to load the keymap if necessary.
Chris Ye989bb932020-07-04 16:18:59 -07002239 bool success = device->loadVirtualKeyMapLocked();
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06002240 if (success) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002241 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242 }
2243 }
2244
2245 // Load the key map.
Chris Yef59a2f42020-10-16 12:55:26 -07002246 // We need to do this for joysticks too because the key layout may specify axes, and for
2247 // sensor as well because the key layout may specify the axes to sensor data mapping.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002248 status_t keyMapStatus = NAME_NOT_FOUND;
Chris Yef59a2f42020-10-16 12:55:26 -07002249 if (device->classes.any(InputDeviceClass::KEYBOARD | InputDeviceClass::JOYSTICK |
2250 InputDeviceClass::SENSOR)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002251 // Load the keymap for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002252 keyMapStatus = device->loadKeyMapLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002253 }
2254
2255 // Configure the keyboard, gamepad or virtual keyboard.
Chris Ye1b0c7342020-07-28 21:57:03 -07002256 if (device->classes.test(InputDeviceClass::KEYBOARD)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002257 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002258 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002259 isEligibleBuiltInKeyboard(device->identifier, device->configuration.get(),
2260 &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002261 mBuiltInKeyboardId = device->id;
2262 }
2263
2264 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
Chris Ye989bb932020-07-04 16:18:59 -07002265 if (device->hasKeycodeLocked(AKEYCODE_Q)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002266 device->classes |= InputDeviceClass::ALPHAKEY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002267 }
2268
2269 // See if this device has a DPAD.
Chris Ye989bb932020-07-04 16:18:59 -07002270 if (device->hasKeycodeLocked(AKEYCODE_DPAD_UP) &&
2271 device->hasKeycodeLocked(AKEYCODE_DPAD_DOWN) &&
2272 device->hasKeycodeLocked(AKEYCODE_DPAD_LEFT) &&
2273 device->hasKeycodeLocked(AKEYCODE_DPAD_RIGHT) &&
2274 device->hasKeycodeLocked(AKEYCODE_DPAD_CENTER)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002275 device->classes |= InputDeviceClass::DPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002276 }
2277
2278 // See if this device has a gamepad.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002279 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES) / sizeof(GAMEPAD_KEYCODES[0]); i++) {
Chris Ye989bb932020-07-04 16:18:59 -07002280 if (device->hasKeycodeLocked(GAMEPAD_KEYCODES[i])) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002281 device->classes |= InputDeviceClass::GAMEPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002282 break;
2283 }
2284 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002285 }
2286
2287 // If the device isn't recognized as something we handle, don't monitor it.
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002288 if (device->classes == ftl::Flags<InputDeviceClass>(0)) {
Chris Ye8594e192020-07-14 10:34:06 -07002289 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002290 device->identifier.name.c_str());
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002291 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002292 }
2293
Chris Ye3fdbfef2021-01-06 18:45:18 -08002294 // Classify InputDeviceClass::BATTERY.
Prabir Pradhan51894782022-08-23 16:29:10 +00002295 if (device->associatedDevice && !device->associatedDevice->batteryInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002296 device->classes |= InputDeviceClass::BATTERY;
2297 }
Kim Low03ea0352020-11-06 12:45:07 -08002298
Chris Ye3fdbfef2021-01-06 18:45:18 -08002299 // Classify InputDeviceClass::LIGHT.
Prabir Pradhan51894782022-08-23 16:29:10 +00002300 if (device->associatedDevice && !device->associatedDevice->lightInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002301 device->classes |= InputDeviceClass::LIGHT;
Kim Low03ea0352020-11-06 12:45:07 -08002302 }
2303
Tim Kilbourn063ff532015-04-08 10:26:18 -07002304 // Determine whether the device has a mic.
Chris Ye989bb932020-07-04 16:18:59 -07002305 if (device->deviceHasMicLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002306 device->classes |= InputDeviceClass::MIC;
Tim Kilbourn063ff532015-04-08 10:26:18 -07002307 }
2308
Michael Wrightd02c5b62014-02-10 15:10:22 -08002309 // Determine whether the device is external or internal.
Chris Ye989bb932020-07-04 16:18:59 -07002310 if (device->isExternalDeviceLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002311 device->classes |= InputDeviceClass::EXTERNAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002312 }
2313
Chris Ye1b0c7342020-07-28 21:57:03 -07002314 if (device->classes.any(InputDeviceClass::JOYSTICK | InputDeviceClass::DPAD) &&
2315 device->classes.test(InputDeviceClass::GAMEPAD)) {
Chris Ye989bb932020-07-04 16:18:59 -07002316 device->controllerNumber = getNextControllerNumberLocked(device->identifier.name);
2317 device->setLedForControllerLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002318 }
2319
Chris Ye989bb932020-07-04 16:18:59 -07002320 if (registerDeviceForEpollLocked(*device) != OK) {
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002321 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002322 }
2323
Chris Ye989bb932020-07-04 16:18:59 -07002324 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002325
Chris Ye1b0c7342020-07-28 21:57:03 -07002326 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=%s, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002327 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Chris Ye1b0c7342020-07-28 21:57:03 -07002328 deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(),
2329 device->classes.string().c_str(), device->configurationFile.c_str(),
2330 device->keyMap.keyLayoutFile.c_str(), device->keyMap.keyCharacterMapFile.c_str(),
2331 toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002332
Chris Ye989bb932020-07-04 16:18:59 -07002333 addDeviceLocked(std::move(device));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002334}
2335
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002336void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
2337 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
2338 if (!videoDevice) {
2339 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
2340 return;
2341 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002342 // Transfer ownership of this video device to a matching input device
Chris Ye989bb932020-07-04 16:18:59 -07002343 for (const auto& [id, device] : mDevices) {
Chris Yed3fef462021-03-07 17:10:08 -08002344 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002345 return; // 'device' now owns 'videoDevice'
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002346 }
2347 }
2348
2349 // Couldn't find a matching input device, so just add it to a temporary holding queue.
2350 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002351 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002352 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002353 mUnattachedVideoDevices.push_back(std::move(videoDevice));
2354}
2355
Chris Yed3fef462021-03-07 17:10:08 -08002356bool EventHub::tryAddVideoDeviceLocked(EventHub::Device& device,
2357 std::unique_ptr<TouchVideoDevice>& videoDevice) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002358 if (videoDevice->getName() != device.identifier.name) {
2359 return false;
2360 }
2361 device.videoDevice = std::move(videoDevice);
2362 if (device.enabled) {
2363 registerVideoDeviceForEpollLocked(*device.videoDevice);
2364 }
2365 return true;
2366}
2367
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002368bool EventHub::isDeviceEnabled(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00002369 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002370 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002371 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002372 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2373 return false;
2374 }
2375 return device->enabled;
2376}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002377
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002378status_t EventHub::enableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002379 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002380 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002381 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002382 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2383 return BAD_VALUE;
2384 }
2385 if (device->enabled) {
2386 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
2387 return OK;
2388 }
2389 status_t result = device->enable();
2390 if (result != OK) {
2391 ALOGE("Failed to enable device %" PRId32, deviceId);
2392 return result;
2393 }
2394
Chris Ye989bb932020-07-04 16:18:59 -07002395 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002396
Chris Ye989bb932020-07-04 16:18:59 -07002397 return registerDeviceForEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002398}
2399
2400status_t EventHub::disableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002401 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002402 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002403 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002404 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2405 return BAD_VALUE;
2406 }
2407 if (!device->enabled) {
2408 ALOGW("Duplicate call to %s, input device already disabled", __func__);
2409 return OK;
2410 }
Chris Ye989bb932020-07-04 16:18:59 -07002411 unregisterDeviceFromEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002412 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002413}
2414
2415void EventHub::createVirtualKeyboardLocked() {
2416 InputDeviceIdentifier identifier;
2417 identifier.name = "Virtual";
2418 identifier.uniqueId = "<virtual>";
2419 assignDescriptorLocked(identifier);
2420
Chris Ye989bb932020-07-04 16:18:59 -07002421 std::unique_ptr<Device> device =
2422 std::make_unique<Device>(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
Prabir Pradhancb42b472022-08-23 16:01:19 +00002423 identifier, nullptr /*associatedDevice*/);
Chris Ye1b0c7342020-07-28 21:57:03 -07002424 device->classes = InputDeviceClass::KEYBOARD | InputDeviceClass::ALPHAKEY |
2425 InputDeviceClass::DPAD | InputDeviceClass::VIRTUAL;
Chris Ye989bb932020-07-04 16:18:59 -07002426 device->loadKeyMapLocked();
2427 addDeviceLocked(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002428}
2429
Chris Ye989bb932020-07-04 16:18:59 -07002430void EventHub::addDeviceLocked(std::unique_ptr<Device> device) {
Chris Yed3fef462021-03-07 17:10:08 -08002431 reportDeviceAddedForStatisticsLocked(device->identifier, device->classes);
Chris Ye989bb932020-07-04 16:18:59 -07002432 mOpeningDevices.push_back(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002433}
2434
Chris Ye989bb932020-07-04 16:18:59 -07002435int32_t EventHub::getNextControllerNumberLocked(const std::string& name) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002436 if (mControllerNumbers.isFull()) {
2437 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Chris Ye989bb932020-07-04 16:18:59 -07002438 name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002439 return 0;
2440 }
2441 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
2442 // one
2443 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
2444}
2445
Chris Ye989bb932020-07-04 16:18:59 -07002446void EventHub::releaseControllerNumberLocked(int32_t num) {
2447 if (num > 0) {
2448 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002449 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002450}
2451
Chris Ye8594e192020-07-14 10:34:06 -07002452void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002453 Device* device = getDeviceByPathLocked(devicePath);
Chris Ye989bb932020-07-04 16:18:59 -07002454 if (device != nullptr) {
2455 closeDeviceLocked(*device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002456 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002457 }
Chris Ye8594e192020-07-14 10:34:06 -07002458 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002459}
2460
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002461/**
2462 * Find the video device by filename, and close it.
2463 * The video device is closed by path during an inotify event, where we don't have the
2464 * additional context about the video device fd, or the associated input device.
2465 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002466void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002467 // A video device may be owned by an existing input device, or it may be stored in
2468 // the mUnattachedVideoDevices queue. Check both locations.
Chris Ye989bb932020-07-04 16:18:59 -07002469 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002470 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002471 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002472 device->videoDevice = nullptr;
2473 return;
2474 }
2475 }
Siarhei Vishniakouf47c339e2021-12-30 11:22:26 -08002476 std::erase_if(mUnattachedVideoDevices,
2477 [&devicePath](const std::unique_ptr<TouchVideoDevice>& videoDevice) {
2478 return videoDevice->getPath() == devicePath;
2479 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08002480}
2481
2482void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002483 mUnattachedVideoDevices.clear();
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002484 while (!mDevices.empty()) {
2485 closeDeviceLocked(*(mDevices.begin()->second));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002486 }
2487}
2488
Chris Ye989bb932020-07-04 16:18:59 -07002489void EventHub::closeDeviceLocked(Device& device) {
2490 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=%s", device.path.c_str(),
2491 device.identifier.name.c_str(), device.id, device.fd, device.classes.string().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002492
Chris Ye989bb932020-07-04 16:18:59 -07002493 if (device.id == mBuiltInKeyboardId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002494 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Chris Ye989bb932020-07-04 16:18:59 -07002495 device.path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002496 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
2497 }
2498
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002499 unregisterDeviceFromEpollLocked(device);
Chris Ye989bb932020-07-04 16:18:59 -07002500 if (device.videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002501 // This must be done after the video device is removed from epoll
Chris Ye989bb932020-07-04 16:18:59 -07002502 mUnattachedVideoDevices.push_back(std::move(device.videoDevice));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002503 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002504
Chris Ye989bb932020-07-04 16:18:59 -07002505 releaseControllerNumberLocked(device.controllerNumber);
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002506 device.controllerNumber = 0;
Chris Ye989bb932020-07-04 16:18:59 -07002507 device.close();
Chris Ye989bb932020-07-04 16:18:59 -07002508 mClosingDevices.push_back(std::move(mDevices[device.id]));
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002509
Chris Ye989bb932020-07-04 16:18:59 -07002510 mDevices.erase(device.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002511}
2512
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002513base::Result<void> EventHub::readNotifyLocked() {
2514 static constexpr auto EVENT_SIZE = static_cast<ssize_t>(sizeof(inotify_event));
2515 uint8_t eventBuffer[512];
2516 ssize_t sizeRead;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002517
2518 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002519 do {
2520 sizeRead = read(mINotifyFd, eventBuffer, sizeof(eventBuffer));
2521 } while (sizeRead < 0 && errno == EINTR);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002522
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002523 if (sizeRead < EVENT_SIZE) return Errorf("could not get event, %s", strerror(errno));
2524
2525 for (ssize_t eventPos = 0; sizeRead >= EVENT_SIZE;) {
2526 const inotify_event* event;
2527 event = (const inotify_event*)(eventBuffer + eventPos);
2528 if (event->len == 0) continue;
2529
2530 handleNotifyEventLocked(*event);
2531
2532 const ssize_t eventSize = EVENT_SIZE + event->len;
2533 sizeRead -= eventSize;
2534 eventPos += eventSize;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002535 }
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002536 return {};
2537}
2538
2539void EventHub::handleNotifyEventLocked(const inotify_event& event) {
2540 if (event.wd == mDeviceInputWd) {
2541 std::string filename = std::string(DEVICE_INPUT_PATH) + "/" + event.name;
2542 if (event.mask & IN_CREATE) {
2543 openDeviceLocked(filename);
2544 } else {
2545 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
2546 closeDeviceByPathLocked(filename);
2547 }
2548 } else if (event.wd == mDeviceWd) {
2549 if (isV4lTouchNode(event.name)) {
2550 std::string filename = std::string(DEVICE_PATH) + "/" + event.name;
2551 if (event.mask & IN_CREATE) {
2552 openVideoDeviceLocked(filename);
2553 } else {
2554 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
2555 closeVideoDeviceByPathLocked(filename);
2556 }
2557 } else if (strcmp(event.name, "input") == 0 && event.mask & IN_CREATE) {
2558 addDeviceInputInotify();
2559 }
2560 } else {
2561 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event.wd);
2562 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002563}
2564
Chris Ye8594e192020-07-14 10:34:06 -07002565status_t EventHub::scanDirLocked(const std::string& dirname) {
2566 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2567 openDeviceLocked(entry.path());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002568 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002569 return 0;
2570}
2571
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002572/**
2573 * Look for all dirname/v4l-touch* devices, and open them.
2574 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002575status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Chris Ye8594e192020-07-14 10:34:06 -07002576 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2577 if (isV4lTouchNode(entry.path())) {
2578 ALOGI("Found touch video device %s", entry.path().c_str());
2579 openVideoDeviceLocked(entry.path());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002580 }
2581 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002582 return OK;
2583}
2584
Michael Wrightd02c5b62014-02-10 15:10:22 -08002585void EventHub::requestReopenDevices() {
2586 ALOGV("requestReopenDevices() called");
2587
Chris Ye87143712020-11-10 05:05:58 +00002588 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002589 mNeedToReopenDevices = true;
2590}
2591
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002592void EventHub::dump(std::string& dump) const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002593 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002594
2595 { // acquire lock
Chris Ye87143712020-11-10 05:05:58 +00002596 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002597
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002598 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002599
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002600 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002601
Chris Ye989bb932020-07-04 16:18:59 -07002602 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002603 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002604 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002605 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002606 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002607 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002608 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002609 }
Chris Ye1b0c7342020-07-28 21:57:03 -07002610 dump += StringPrintf(INDENT3 "Classes: %s\n", device->classes.string().c_str());
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002611 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002612 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002613 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
2614 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002615 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002616 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002617 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002618 "product=0x%04x, version=0x%04x\n",
2619 device->identifier.bus, device->identifier.vendor,
2620 device->identifier.product, device->identifier.version);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002621 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002622 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002623 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002624 device->keyMap.keyCharacterMapFile.c_str());
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00002625 dump += StringPrintf(INDENT3 "CountryCode: %d\n",
2626 device->associatedDevice ? device->associatedDevice->countryCode
2627 : InputDeviceCountryCode::INVALID);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002628 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002629 device->configurationFile.c_str());
Prabir Pradhan51894782022-08-23 16:29:10 +00002630 dump += StringPrintf(INDENT3 "VideoDevice: %s\n",
2631 device->videoDevice ? device->videoDevice->dump().c_str()
2632 : "<none>");
2633 dump += StringPrintf(INDENT3 "SysfsDevicePath: %s\n",
2634 device->associatedDevice
2635 ? device->associatedDevice->sysfsRootPath.c_str()
2636 : "<none>");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002637 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002638
2639 dump += INDENT "Unattached video devices:\n";
2640 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
2641 dump += INDENT2 + videoDevice->dump() + "\n";
2642 }
2643 if (mUnattachedVideoDevices.empty()) {
2644 dump += INDENT2 "<none>\n";
2645 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002646 } // release lock
2647}
2648
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002649void EventHub::monitor() const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002650 // Acquire and release the lock to ensure that the event hub has not deadlocked.
Chris Ye1c2e0892020-11-30 21:41:44 -08002651 std::unique_lock<std::mutex> lock(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002652}
2653
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002654} // namespace android