blob: 336763c3c35788acddc20db135f49ae6ec1fc3e3 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2005 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070017#include <assert.h>
18#include <dirent.h>
19#include <errno.h>
20#include <fcntl.h>
21#include <inttypes.h>
22#include <memory.h>
23#include <stdint.h>
24#include <stdio.h>
25#include <stdlib.h>
26#include <string.h>
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +010027#include <sys/capability.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070028#include <sys/epoll.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070029#include <sys/inotify.h>
30#include <sys/ioctl.h>
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070031#include <sys/limits.h>
Kim Low03ea0352020-11-06 12:45:07 -080032#include <sys/stat.h>
33#include <sys/sysmacros.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070034#include <unistd.h>
35
Michael Wrightd02c5b62014-02-10 15:10:22 -080036#define LOG_TAG "EventHub"
37
38// #define LOG_NDEBUG 0
Kim Low03ea0352020-11-06 12:45:07 -080039#include <android-base/file.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080040#include <android-base/stringprintf.h>
Chris Yed3fef462021-03-07 17:10:08 -080041#include <android-base/strings.h>
Philip Quinn39b81682019-01-09 22:20:39 -080042#include <cutils/properties.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080043#include <ftl/enum.h>
Chris Ye8594e192020-07-14 10:34:06 -070044#include <input/KeyCharacterMap.h>
45#include <input/KeyLayoutMap.h>
46#include <input/VirtualKeyMap.h>
Dan Albert677d87e2014-06-16 17:31:28 -070047#include <openssl/sha.h>
Chris Yed3fef462021-03-07 17:10:08 -080048#include <statslog.h>
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070049#include <utils/Errors.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080050#include <utils/Log.h>
51#include <utils/Timers.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080052
Chris Ye8594e192020-07-14 10:34:06 -070053#include <filesystem>
Chris Ye3fdbfef2021-01-06 18:45:18 -080054#include <regex>
Prabir Pradhancb42b472022-08-23 16:01:19 +000055#include <utility>
Chris Ye8594e192020-07-14 10:34:06 -070056
57#include "EventHub.h"
Michael Wrightd02c5b62014-02-10 15:10:22 -080058
Michael Wrightd02c5b62014-02-10 15:10:22 -080059#define INDENT " "
60#define INDENT2 " "
61#define INDENT3 " "
62
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080063using android::base::StringPrintf;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +000064using android::hardware::input::InputDeviceCountryCode;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080065
Michael Wrightd02c5b62014-02-10 15:10:22 -080066namespace android {
67
Dominik Laskowski2f01d772022-03-23 16:01:29 -070068using namespace ftl::flag_operators;
69
Usama Arifb27c8e62021-06-03 16:44:09 +010070static const char* DEVICE_INPUT_PATH = "/dev/input";
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080071// v4l2 devices go directly into /dev
Usama Arifb27c8e62021-06-03 16:44:09 +010072static const char* DEVICE_PATH = "/dev";
Michael Wrightd02c5b62014-02-10 15:10:22 -080073
Chris Ye657c2f02021-05-25 16:24:37 -070074static constexpr size_t OBFUSCATED_LENGTH = 8;
75
Chris Ye87143712020-11-10 05:05:58 +000076static constexpr int32_t FF_STRONG_MAGNITUDE_CHANNEL_IDX = 0;
77static constexpr int32_t FF_WEAK_MAGNITUDE_CHANNEL_IDX = 1;
Chris Ye6393a262020-08-04 19:41:36 -070078
Chris Yee2b1e5c2021-03-10 22:45:12 -080079// Mapping for input battery class node IDs lookup.
80// https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
81static const std::unordered_map<std::string, InputBatteryClass> BATTERY_CLASSES =
82 {{"capacity", InputBatteryClass::CAPACITY},
83 {"capacity_level", InputBatteryClass::CAPACITY_LEVEL},
84 {"status", InputBatteryClass::STATUS}};
85
86// Mapping for input battery class node names lookup.
87// https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
88static const std::unordered_map<InputBatteryClass, std::string> BATTERY_NODES =
89 {{InputBatteryClass::CAPACITY, "capacity"},
90 {InputBatteryClass::CAPACITY_LEVEL, "capacity_level"},
91 {InputBatteryClass::STATUS, "status"}};
92
Kim Low03ea0352020-11-06 12:45:07 -080093// must be kept in sync with definitions in kernel /drivers/power/supply/power_supply_sysfs.c
94static const std::unordered_map<std::string, int32_t> BATTERY_STATUS =
95 {{"Unknown", BATTERY_STATUS_UNKNOWN},
96 {"Charging", BATTERY_STATUS_CHARGING},
97 {"Discharging", BATTERY_STATUS_DISCHARGING},
98 {"Not charging", BATTERY_STATUS_NOT_CHARGING},
99 {"Full", BATTERY_STATUS_FULL}};
100
101// Mapping taken from
102// https://gitlab.freedesktop.org/upower/upower/-/blob/master/src/linux/up-device-supply.c#L484
103static const std::unordered_map<std::string, int32_t> BATTERY_LEVEL = {{"Critical", 5},
104 {"Low", 10},
105 {"Normal", 55},
106 {"High", 70},
107 {"Full", 100},
108 {"Unknown", 50}};
109
Chris Ye3fdbfef2021-01-06 18:45:18 -0800110// Mapping for input led class node names lookup.
111// https://www.kernel.org/doc/html/latest/leds/leds-class.html
112static const std::unordered_map<std::string, InputLightClass> LIGHT_CLASSES =
113 {{"red", InputLightClass::RED},
114 {"green", InputLightClass::GREEN},
115 {"blue", InputLightClass::BLUE},
116 {"global", InputLightClass::GLOBAL},
117 {"brightness", InputLightClass::BRIGHTNESS},
118 {"multi_index", InputLightClass::MULTI_INDEX},
119 {"multi_intensity", InputLightClass::MULTI_INTENSITY},
120 {"max_brightness", InputLightClass::MAX_BRIGHTNESS}};
121
122// Mapping for input multicolor led class node names.
123// https://www.kernel.org/doc/html/latest/leds/leds-class-multicolor.html
124static const std::unordered_map<InputLightClass, std::string> LIGHT_NODES =
125 {{InputLightClass::BRIGHTNESS, "brightness"},
126 {InputLightClass::MULTI_INDEX, "multi_index"},
127 {InputLightClass::MULTI_INTENSITY, "multi_intensity"}};
128
129// Mapping for light color name and the light color
130const std::unordered_map<std::string, LightColor> LIGHT_COLORS = {{"red", LightColor::RED},
131 {"green", LightColor::GREEN},
132 {"blue", LightColor::BLUE}};
133
Michael Wrightd02c5b62014-02-10 15:10:22 -0800134static inline const char* toString(bool value) {
135 return value ? "true" : "false";
136}
137
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100138static std::string sha1(const std::string& in) {
Dan Albert677d87e2014-06-16 17:31:28 -0700139 SHA_CTX ctx;
140 SHA1_Init(&ctx);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100141 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
Dan Albert677d87e2014-06-16 17:31:28 -0700142 u_char digest[SHA_DIGEST_LENGTH];
143 SHA1_Final(digest, &ctx);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800144
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100145 std::string out;
Dan Albert677d87e2014-06-16 17:31:28 -0700146 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100147 out += StringPrintf("%02x", digest[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800148 }
149 return out;
150}
151
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800152/**
153 * Return true if name matches "v4l-touch*"
154 */
Chris Ye8594e192020-07-14 10:34:06 -0700155static bool isV4lTouchNode(std::string name) {
156 return name.find("v4l-touch") != std::string::npos;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800157}
158
Philip Quinn39b81682019-01-09 22:20:39 -0800159/**
160 * Returns true if V4L devices should be scanned.
161 *
162 * The system property ro.input.video_enabled can be used to control whether
163 * EventHub scans and opens V4L devices. As V4L does not support multiple
164 * clients, EventHub effectively blocks access to these devices when it opens
Siarhei Vishniakou29f88492019-04-05 14:11:43 -0700165 * them.
166 *
167 * Setting this to "false" would prevent any video devices from being discovered and
168 * associated with input devices.
169 *
170 * This property can be used as follows:
171 * 1. To turn off features that are dependent on video device presence.
172 * 2. During testing and development, to allow other clients to read video devices
173 * directly from /dev.
Philip Quinn39b81682019-01-09 22:20:39 -0800174 */
175static bool isV4lScanningEnabled() {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700176 return property_get_bool("ro.input.video_enabled", true /* default_value */);
Philip Quinn39b81682019-01-09 22:20:39 -0800177}
178
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800179static nsecs_t processEventTimestamp(const struct input_event& event) {
180 // Use the time specified in the event instead of the current time
181 // so that downstream code can get more accurate estimates of
182 // event dispatch latency from the time the event is enqueued onto
183 // the evdev client buffer.
184 //
185 // The event's timestamp fortuitously uses the same monotonic clock
186 // time base as the rest of Android. The kernel event device driver
187 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
188 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
189 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
190 // system call that also queries ktime_get_ts().
191
192 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.time.tv_sec) +
193 microseconds_to_nanoseconds(event.time.tv_usec);
194 return inputEventTime;
195}
196
Kim Low03ea0352020-11-06 12:45:07 -0800197/**
Prabir Pradhancb42b472022-08-23 16:01:19 +0000198 * Returns the sysfs root path of the input device.
Kim Low03ea0352020-11-06 12:45:07 -0800199 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800200static std::optional<std::filesystem::path> getSysfsRootPath(const char* devicePath) {
Kim Low03ea0352020-11-06 12:45:07 -0800201 std::error_code errorCode;
202
203 // Stat the device path to get the major and minor number of the character file
204 struct stat statbuf;
205 if (stat(devicePath, &statbuf) == -1) {
206 ALOGE("Could not stat device %s due to error: %s.", devicePath, std::strerror(errno));
Chris Ye3fdbfef2021-01-06 18:45:18 -0800207 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800208 }
209
210 unsigned int major_num = major(statbuf.st_rdev);
211 unsigned int minor_num = minor(statbuf.st_rdev);
212
213 // Realpath "/sys/dev/char/{major}:{minor}" to get the sysfs path to the input event
214 auto sysfsPath = std::filesystem::path("/sys/dev/char/");
215 sysfsPath /= std::to_string(major_num) + ":" + std::to_string(minor_num);
216 sysfsPath = std::filesystem::canonical(sysfsPath, errorCode);
217
218 // Make sure nothing went wrong in call to canonical()
219 if (errorCode) {
220 ALOGW("Could not run filesystem::canonical() due to error %d : %s.", errorCode.value(),
221 errorCode.message().c_str());
Chris Ye3fdbfef2021-01-06 18:45:18 -0800222 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800223 }
224
225 // Continue to go up a directory until we reach a directory named "input"
226 while (sysfsPath != "/" && sysfsPath.filename() != "input") {
227 sysfsPath = sysfsPath.parent_path();
228 }
229
230 // Then go up one more and you will be at the sysfs root of the device
231 sysfsPath = sysfsPath.parent_path();
232
233 // Make sure we didn't reach root path and that directory actually exists
234 if (sysfsPath == "/" || !std::filesystem::exists(sysfsPath, errorCode)) {
235 if (errorCode) {
236 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
237 errorCode.message().c_str());
238 }
239
240 // Not found
Chris Ye3fdbfef2021-01-06 18:45:18 -0800241 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800242 }
243
244 return sysfsPath;
245}
246
247/**
Chris Ye3fdbfef2021-01-06 18:45:18 -0800248 * Returns the list of files under a specified path.
Kim Low03ea0352020-11-06 12:45:07 -0800249 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800250static std::vector<std::filesystem::path> allFilesInPath(const std::filesystem::path& path) {
251 std::vector<std::filesystem::path> nodes;
252 std::error_code errorCode;
253 auto iter = std::filesystem::directory_iterator(path, errorCode);
254 while (!errorCode && iter != std::filesystem::directory_iterator()) {
255 nodes.push_back(iter->path());
256 iter++;
257 }
258 return nodes;
259}
260
261/**
262 * Returns the list of files under a specified directory in a sysfs path.
263 * Example:
264 * findSysfsNodes(sysfsRootPath, SysfsClass::LEDS) will return all led nodes under "leds" directory
265 * in the sysfs path.
266 */
267static std::vector<std::filesystem::path> findSysfsNodes(const std::filesystem::path& sysfsRoot,
268 SysfsClass clazz) {
Dominik Laskowski75788452021-02-09 18:51:25 -0800269 std::string nodeStr = ftl::enum_string(clazz);
Chris Ye3fdbfef2021-01-06 18:45:18 -0800270 std::for_each(nodeStr.begin(), nodeStr.end(),
271 [](char& c) { c = std::tolower(static_cast<unsigned char>(c)); });
272 std::vector<std::filesystem::path> nodes;
273 for (auto path = sysfsRoot; path != "/" && nodes.empty(); path = path.parent_path()) {
274 nodes = allFilesInPath(path / nodeStr);
275 }
276 return nodes;
277}
278
279static std::optional<std::array<LightColor, COLOR_NUM>> getColorIndexArray(
280 std::filesystem::path path) {
281 std::string indexStr;
282 if (!base::ReadFileToString(path, &indexStr)) {
283 return std::nullopt;
284 }
285
286 // Parse the multi color LED index file, refer to kernel docs
287 // leds/leds-class-multicolor.html
288 std::regex indexPattern("(red|green|blue)\\s(red|green|blue)\\s(red|green|blue)[\\n]");
289 std::smatch results;
290 std::array<LightColor, COLOR_NUM> colors;
291 if (!std::regex_match(indexStr, results, indexPattern)) {
292 return std::nullopt;
293 }
294
295 for (size_t i = 1; i < results.size(); i++) {
296 const auto it = LIGHT_COLORS.find(results[i].str());
297 if (it != LIGHT_COLORS.end()) {
298 // intensities.emplace(it->second, 0);
299 colors[i - 1] = it->second;
Kim Low03ea0352020-11-06 12:45:07 -0800300 }
301 }
Chris Ye3fdbfef2021-01-06 18:45:18 -0800302 return colors;
Kim Low03ea0352020-11-06 12:45:07 -0800303}
304
Prabir Pradhancb42b472022-08-23 16:01:19 +0000305/**
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000306 * Read country code information exposed through the sysfs path.
307 */
308static InputDeviceCountryCode readCountryCodeLocked(const std::filesystem::path& sysfsRootPath) {
309 // Check the sysfs root path
310 int hidCountryCode = static_cast<int>(InputDeviceCountryCode::INVALID);
311 std::string str;
312 if (base::ReadFileToString(sysfsRootPath / "country", &str)) {
313 hidCountryCode = std::stoi(str, nullptr, 16);
314 LOG_ALWAYS_FATAL_IF(hidCountryCode > 35 || hidCountryCode < 0,
315 "HID country code should be in range [0, 35]. Found country code "
316 "to be %d",
317 hidCountryCode);
318 }
319
320 return static_cast<InputDeviceCountryCode>(hidCountryCode);
321}
322
323/**
Prabir Pradhancb42b472022-08-23 16:01:19 +0000324 * Read information about batteries exposed through the sysfs path.
325 */
326static std::unordered_map<int32_t /*batteryId*/, RawBatteryInfo> readBatteryConfiguration(
327 const std::filesystem::path& sysfsRootPath) {
328 std::unordered_map<int32_t, RawBatteryInfo> batteryInfos;
329 int32_t nextBatteryId = 0;
330 // Check if device has any battery.
331 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::POWER_SUPPLY);
332 for (const auto& nodePath : paths) {
333 RawBatteryInfo info;
334 info.id = ++nextBatteryId;
335 info.path = nodePath;
336 info.name = nodePath.filename();
337
338 // Scan the path for all the files
339 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
340 const auto& files = allFilesInPath(nodePath);
341 for (const auto& file : files) {
342 const auto it = BATTERY_CLASSES.find(file.filename().string());
343 if (it != BATTERY_CLASSES.end()) {
344 info.flags |= it->second;
345 }
346 }
347 batteryInfos.insert_or_assign(info.id, info);
348 ALOGD("configureBatteryLocked rawBatteryId %d name %s", info.id, info.name.c_str());
349 }
350 return batteryInfos;
351}
352
353/**
354 * Read information about lights exposed through the sysfs path.
355 */
356static std::unordered_map<int32_t /*lightId*/, RawLightInfo> readLightsConfiguration(
357 const std::filesystem::path& sysfsRootPath) {
358 std::unordered_map<int32_t, RawLightInfo> lightInfos;
359 int32_t nextLightId = 0;
360 // Check if device has any lights.
361 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::LEDS);
362 for (const auto& nodePath : paths) {
363 RawLightInfo info;
364 info.id = ++nextLightId;
365 info.path = nodePath;
366 info.name = nodePath.filename();
367 info.maxBrightness = std::nullopt;
368 size_t nameStart = info.name.rfind(":");
369 if (nameStart != std::string::npos) {
370 // Trim the name to color name
371 info.name = info.name.substr(nameStart + 1);
372 // Set InputLightClass flag for colors
373 const auto it = LIGHT_CLASSES.find(info.name);
374 if (it != LIGHT_CLASSES.end()) {
375 info.flags |= it->second;
376 }
377 }
378 // Scan the path for all the files
379 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
380 const auto& files = allFilesInPath(nodePath);
381 for (const auto& file : files) {
382 const auto it = LIGHT_CLASSES.find(file.filename().string());
383 if (it != LIGHT_CLASSES.end()) {
384 info.flags |= it->second;
385 // If the node has maximum brightness, read it
386 if (it->second == InputLightClass::MAX_BRIGHTNESS) {
387 std::string str;
388 if (base::ReadFileToString(file, &str)) {
389 info.maxBrightness = std::stoi(str);
390 }
391 }
392 }
393 }
394 lightInfos.insert_or_assign(info.id, info);
395 ALOGD("configureLightsLocked rawLightId %d name %s", info.id, info.name.c_str());
396 }
397 return lightInfos;
398}
399
Michael Wrightd02c5b62014-02-10 15:10:22 -0800400// --- Global Functions ---
401
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700402ftl::Flags<InputDeviceClass> getAbsAxisUsage(int32_t axis,
403 ftl::Flags<InputDeviceClass> deviceClasses) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800404 // Touch devices get dibs on touch-related axes.
Chris Ye1b0c7342020-07-28 21:57:03 -0700405 if (deviceClasses.test(InputDeviceClass::TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800406 switch (axis) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700407 case ABS_X:
408 case ABS_Y:
409 case ABS_PRESSURE:
410 case ABS_TOOL_WIDTH:
411 case ABS_DISTANCE:
412 case ABS_TILT_X:
413 case ABS_TILT_Y:
414 case ABS_MT_SLOT:
415 case ABS_MT_TOUCH_MAJOR:
416 case ABS_MT_TOUCH_MINOR:
417 case ABS_MT_WIDTH_MAJOR:
418 case ABS_MT_WIDTH_MINOR:
419 case ABS_MT_ORIENTATION:
420 case ABS_MT_POSITION_X:
421 case ABS_MT_POSITION_Y:
422 case ABS_MT_TOOL_TYPE:
423 case ABS_MT_BLOB_ID:
424 case ABS_MT_TRACKING_ID:
425 case ABS_MT_PRESSURE:
426 case ABS_MT_DISTANCE:
Chris Ye1b0c7342020-07-28 21:57:03 -0700427 return InputDeviceClass::TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800428 }
429 }
430
Chris Yef59a2f42020-10-16 12:55:26 -0700431 if (deviceClasses.test(InputDeviceClass::SENSOR)) {
432 switch (axis) {
433 case ABS_X:
434 case ABS_Y:
435 case ABS_Z:
436 case ABS_RX:
437 case ABS_RY:
438 case ABS_RZ:
439 return InputDeviceClass::SENSOR;
440 }
441 }
442
Michael Wright842500e2015-03-13 17:32:02 -0700443 // External stylus gets the pressure axis
Chris Ye1b0c7342020-07-28 21:57:03 -0700444 if (deviceClasses.test(InputDeviceClass::EXTERNAL_STYLUS)) {
Michael Wright842500e2015-03-13 17:32:02 -0700445 if (axis == ABS_PRESSURE) {
Chris Ye1b0c7342020-07-28 21:57:03 -0700446 return InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -0700447 }
448 }
449
Michael Wrightd02c5b62014-02-10 15:10:22 -0800450 // Joystick devices get the rest.
Chris Ye1b0c7342020-07-28 21:57:03 -0700451 return deviceClasses & InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800452}
453
454// --- EventHub::Device ---
455
Prabir Pradhancb42b472022-08-23 16:01:19 +0000456EventHub::Device::Device(int fd, int32_t id, std::string path, InputDeviceIdentifier identifier,
457 std::shared_ptr<const AssociatedDevice> assocDev)
Chris Ye989bb932020-07-04 16:18:59 -0700458 : fd(fd),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700459 id(id),
Prabir Pradhancb42b472022-08-23 16:01:19 +0000460 path(std::move(path)),
461 identifier(std::move(identifier)),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700462 classes(0),
463 configuration(nullptr),
464 virtualKeyMap(nullptr),
465 ffEffectPlaying(false),
466 ffEffectId(-1),
Prabir Pradhancb42b472022-08-23 16:01:19 +0000467 associatedDevice(std::move(assocDev)),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700468 controllerNumber(0),
469 enabled(true),
Chris Ye66fbac32020-07-06 20:36:43 -0700470 isVirtual(fd < 0) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800471
472EventHub::Device::~Device() {
473 close();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800474}
475
476void EventHub::Device::close() {
477 if (fd >= 0) {
478 ::close(fd);
479 fd = -1;
480 }
481}
482
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700483status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100484 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700485 if (fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100486 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700487 return -errno;
488 }
489 enabled = true;
490 return OK;
491}
492
493status_t EventHub::Device::disable() {
494 close();
495 enabled = false;
496 return OK;
497}
498
Chris Ye989bb932020-07-04 16:18:59 -0700499bool EventHub::Device::hasValidFd() const {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700500 return !isVirtual && enabled;
501}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800502
Chris Ye3a1e4462020-08-12 10:13:15 -0700503const std::shared_ptr<KeyCharacterMap> EventHub::Device::getKeyCharacterMap() const {
Chris Ye989bb932020-07-04 16:18:59 -0700504 return keyMap.keyCharacterMap;
505}
506
507template <std::size_t N>
508status_t EventHub::Device::readDeviceBitMask(unsigned long ioctlCode, BitArray<N>& bitArray) {
509 if (!hasValidFd()) {
510 return BAD_VALUE;
511 }
512 if ((_IOC_SIZE(ioctlCode) == 0)) {
513 ioctlCode |= _IOC(0, 0, 0, bitArray.bytes());
514 }
515
516 typename BitArray<N>::Buffer buffer;
517 status_t ret = ioctl(fd, ioctlCode, buffer.data());
518 bitArray.loadFromBuffer(buffer);
519 return ret;
520}
521
522void EventHub::Device::configureFd() {
523 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
524 if (classes.test(InputDeviceClass::KEYBOARD)) {
525 // Disable kernel key repeat since we handle it ourselves
526 unsigned int repeatRate[] = {0, 0};
527 if (ioctl(fd, EVIOCSREP, repeatRate)) {
528 ALOGW("Unable to disable kernel key repeat for %s: %s", path.c_str(), strerror(errno));
529 }
530 }
531
532 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
533 // associated with input events. This is important because the input system
534 // uses the timestamps extensively and assumes they were recorded using the monotonic
535 // clock.
536 int clockId = CLOCK_MONOTONIC;
Chris Yef59a2f42020-10-16 12:55:26 -0700537 if (classes.test(InputDeviceClass::SENSOR)) {
538 // Each new sensor event should use the same time base as
539 // SystemClock.elapsedRealtimeNanos().
540 clockId = CLOCK_BOOTTIME;
541 }
Chris Ye989bb932020-07-04 16:18:59 -0700542 bool usingClockIoctl = !ioctl(fd, EVIOCSCLOCKID, &clockId);
543 ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
544}
545
546bool EventHub::Device::hasKeycodeLocked(int keycode) const {
547 if (!keyMap.haveKeyLayout()) {
548 return false;
549 }
550
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700551 std::vector<int32_t> scanCodes = keyMap.keyLayoutMap->findScanCodesForKey(keycode);
Chris Ye989bb932020-07-04 16:18:59 -0700552 const size_t N = scanCodes.size();
553 for (size_t i = 0; i < N && i <= KEY_MAX; i++) {
554 int32_t sc = scanCodes[i];
555 if (sc >= 0 && sc <= KEY_MAX && keyBitmask.test(sc)) {
556 return true;
557 }
558 }
559
560 return false;
561}
562
563void EventHub::Device::loadConfigurationLocked() {
564 configurationFile =
565 getInputDeviceConfigurationFilePathByDeviceIdentifier(identifier,
566 InputDeviceConfigurationFileType::
567 CONFIGURATION);
568 if (configurationFile.empty()) {
569 ALOGD("No input device configuration file found for device '%s'.", identifier.name.c_str());
570 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500571 android::base::Result<std::unique_ptr<PropertyMap>> propertyMap =
572 PropertyMap::load(configurationFile.c_str());
573 if (!propertyMap.ok()) {
Chris Ye989bb932020-07-04 16:18:59 -0700574 ALOGE("Error loading input device configuration file for device '%s'. "
575 "Using default configuration.",
576 identifier.name.c_str());
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500577 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500578 configuration = std::move(*propertyMap);
Chris Ye989bb932020-07-04 16:18:59 -0700579 }
580 }
581}
582
583bool EventHub::Device::loadVirtualKeyMapLocked() {
584 // The virtual key map is supplied by the kernel as a system board property file.
585 std::string propPath = "/sys/board_properties/virtualkeys.";
586 propPath += identifier.getCanonicalName();
587 if (access(propPath.c_str(), R_OK)) {
588 return false;
589 }
590 virtualKeyMap = VirtualKeyMap::load(propPath);
591 return virtualKeyMap != nullptr;
592}
593
594status_t EventHub::Device::loadKeyMapLocked() {
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500595 return keyMap.load(identifier, configuration.get());
Chris Ye989bb932020-07-04 16:18:59 -0700596}
597
598bool EventHub::Device::isExternalDeviceLocked() {
599 if (configuration) {
600 bool value;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700601 if (configuration->tryGetProperty("device.internal", value)) {
Chris Ye989bb932020-07-04 16:18:59 -0700602 return !value;
603 }
604 }
605 return identifier.bus == BUS_USB || identifier.bus == BUS_BLUETOOTH;
606}
607
608bool EventHub::Device::deviceHasMicLocked() {
609 if (configuration) {
610 bool value;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700611 if (configuration->tryGetProperty("audio.mic", value)) {
Chris Ye989bb932020-07-04 16:18:59 -0700612 return value;
613 }
614 }
615 return false;
616}
617
618void EventHub::Device::setLedStateLocked(int32_t led, bool on) {
619 int32_t sc;
620 if (hasValidFd() && mapLed(led, &sc) != NAME_NOT_FOUND) {
621 struct input_event ev;
622 ev.time.tv_sec = 0;
623 ev.time.tv_usec = 0;
624 ev.type = EV_LED;
625 ev.code = sc;
626 ev.value = on ? 1 : 0;
627
628 ssize_t nWrite;
629 do {
630 nWrite = write(fd, &ev, sizeof(struct input_event));
631 } while (nWrite == -1 && errno == EINTR);
632 }
633}
634
635void EventHub::Device::setLedForControllerLocked() {
636 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
637 setLedStateLocked(ALED_CONTROLLER_1 + i, controllerNumber == i + 1);
638 }
639}
640
641status_t EventHub::Device::mapLed(int32_t led, int32_t* outScanCode) const {
642 if (!keyMap.haveKeyLayout()) {
643 return NAME_NOT_FOUND;
644 }
645
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700646 std::optional<int32_t> scanCode = keyMap.keyLayoutMap->findScanCodeForLed(led);
647 if (scanCode.has_value()) {
648 if (*scanCode >= 0 && *scanCode <= LED_MAX && ledBitmask.test(*scanCode)) {
649 *outScanCode = *scanCode;
Chris Ye989bb932020-07-04 16:18:59 -0700650 return NO_ERROR;
651 }
652 }
653 return NAME_NOT_FOUND;
654}
655
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100656/**
657 * Get the capabilities for the current process.
658 * Crashes the system if unable to create / check / destroy the capabilities object.
659 */
660class Capabilities final {
661public:
662 explicit Capabilities() {
663 mCaps = cap_get_proc();
664 LOG_ALWAYS_FATAL_IF(mCaps == nullptr, "Could not get capabilities of the current process");
665 }
666
667 /**
668 * Check whether the current process has a specific capability
669 * in the set of effective capabilities.
670 * Return CAP_SET if the process has the requested capability
671 * Return CAP_CLEAR otherwise.
672 */
673 cap_flag_value_t checkEffectiveCapability(cap_value_t capability) {
674 cap_flag_value_t value;
675 const int result = cap_get_flag(mCaps, capability, CAP_EFFECTIVE, &value);
676 LOG_ALWAYS_FATAL_IF(result == -1, "Could not obtain the requested capability");
677 return value;
678 }
679
680 ~Capabilities() {
681 const int result = cap_free(mCaps);
682 LOG_ALWAYS_FATAL_IF(result == -1, "Could not release the capabilities structure");
683 }
684
685private:
686 cap_t mCaps;
687};
688
689static void ensureProcessCanBlockSuspend() {
690 Capabilities capabilities;
691 const bool canBlockSuspend =
692 capabilities.checkEffectiveCapability(CAP_BLOCK_SUSPEND) == CAP_SET;
693 LOG_ALWAYS_FATAL_IF(!canBlockSuspend,
694 "Input must be able to block suspend to properly process events");
695}
696
Michael Wrightd02c5b62014-02-10 15:10:22 -0800697// --- EventHub ---
698
Michael Wrightd02c5b62014-02-10 15:10:22 -0800699const int EventHub::EPOLL_MAX_EVENTS;
700
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700701EventHub::EventHub(void)
702 : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
703 mNextDeviceId(1),
704 mControllerNumbers(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800705 mNeedToSendFinishedDeviceScan(false),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700706 mNeedToReopenDevices(false),
707 mNeedToScanDevices(true),
708 mPendingEventCount(0),
709 mPendingEventIndex(0),
710 mPendingINotify(false) {
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100711 ensureProcessCanBlockSuspend();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800712
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800713 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800714 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800715
Michael Wright8e9a8562022-02-09 13:44:29 +0000716 mINotifyFd = inotify_init1(IN_CLOEXEC);
Prabir Pradhan952e65b2022-06-23 17:49:55 +0000717 LOG_ALWAYS_FATAL_IF(mINotifyFd < 0, "Could not create inotify instance: %s", strerror(errno));
Usama Arifb27c8e62021-06-03 16:44:09 +0100718
719 std::error_code errorCode;
720 bool isDeviceInotifyAdded = false;
721 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
722 addDeviceInputInotify();
Philip Quinn39b81682019-01-09 22:20:39 -0800723 } else {
Usama Arifb27c8e62021-06-03 16:44:09 +0100724 addDeviceInotify();
725 isDeviceInotifyAdded = true;
726 if (errorCode) {
727 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
728 errorCode.message().c_str());
729 }
730 }
731
732 if (isV4lScanningEnabled() && !isDeviceInotifyAdded) {
733 addDeviceInotify();
734 } else {
Philip Quinn39b81682019-01-09 22:20:39 -0800735 ALOGI("Video device scanning disabled");
736 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800737
Siarhei Vishniakou2d0e9482019-09-24 12:52:47 +0100738 struct epoll_event eventItem = {};
739 eventItem.events = EPOLLIN | EPOLLWAKEUP;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700740 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800741 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800742 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
743
744 int wakeFds[2];
Michael Wright8e9a8562022-02-09 13:44:29 +0000745 result = pipe2(wakeFds, O_CLOEXEC);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800746 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
747
748 mWakeReadPipeFd = wakeFds[0];
749 mWakeWritePipeFd = wakeFds[1];
750
751 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
752 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700753 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800754
755 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
756 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700757 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800758
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700759 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800760 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
761 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700762 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800763}
764
765EventHub::~EventHub(void) {
766 closeAllDevicesLocked();
767
Michael Wrightd02c5b62014-02-10 15:10:22 -0800768 ::close(mEpollFd);
769 ::close(mINotifyFd);
770 ::close(mWakeReadPipeFd);
771 ::close(mWakeWritePipeFd);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800772}
773
Usama Arifb27c8e62021-06-03 16:44:09 +0100774/**
775 * On devices that don't have any input devices (like some development boards), the /dev/input
776 * directory will be absent. However, the user may still plug in an input device at a later time.
777 * Add watch for contents of /dev/input only when /dev/input appears.
778 */
779void EventHub::addDeviceInputInotify() {
780 mDeviceInputWd = inotify_add_watch(mINotifyFd, DEVICE_INPUT_PATH, IN_DELETE | IN_CREATE);
781 LOG_ALWAYS_FATAL_IF(mDeviceInputWd < 0, "Could not register INotify for %s: %s",
782 DEVICE_INPUT_PATH, strerror(errno));
783}
784
785void EventHub::addDeviceInotify() {
786 mDeviceWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
787 LOG_ALWAYS_FATAL_IF(mDeviceWd < 0, "Could not register INotify for %s: %s", DEVICE_PATH,
788 strerror(errno));
789}
790
Michael Wrightd02c5b62014-02-10 15:10:22 -0800791InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000792 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800793 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700794 return device != nullptr ? device->identifier : InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800795}
796
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700797ftl::Flags<InputDeviceClass> EventHub::getDeviceClasses(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000798 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800799 Device* device = getDeviceLocked(deviceId);
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700800 return device != nullptr ? device->classes : ftl::Flags<InputDeviceClass>(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800801}
802
803int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000804 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800805 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700806 return device != nullptr ? device->controllerNumber : 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800807}
808
809void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
Chris Ye87143712020-11-10 05:05:58 +0000810 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800811 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700812 if (device != nullptr && device->configuration) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800813 *outConfiguration = *device->configuration;
814 } else {
815 outConfiguration->clear();
816 }
817}
818
819status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700820 RawAbsoluteAxisInfo* outAxisInfo) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800821 outAxisInfo->clear();
822
823 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000824 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800825
826 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700827 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800828 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700829 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
830 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
831 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800832 return -errno;
833 }
834
835 if (info.minimum != info.maximum) {
836 outAxisInfo->valid = true;
837 outAxisInfo->minValue = info.minimum;
838 outAxisInfo->maxValue = info.maximum;
839 outAxisInfo->flat = info.flat;
840 outAxisInfo->fuzz = info.fuzz;
841 outAxisInfo->resolution = info.resolution;
842 }
843 return OK;
844 }
845 }
846 return -1;
847}
848
849bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
850 if (axis >= 0 && axis <= REL_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000851 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800852 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700853 return device != nullptr ? device->relBitmask.test(axis) : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800854 }
855 return false;
856}
857
858bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
Chris Ye87143712020-11-10 05:05:58 +0000859 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800860
Chris Ye989bb932020-07-04 16:18:59 -0700861 Device* device = getDeviceLocked(deviceId);
862 return property >= 0 && property <= INPUT_PROP_MAX && device != nullptr
863 ? device->propBitmask.test(property)
864 : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800865}
866
Chris Yef59a2f42020-10-16 12:55:26 -0700867bool EventHub::hasMscEvent(int32_t deviceId, int mscEvent) const {
868 std::scoped_lock _l(mLock);
869
870 Device* device = getDeviceLocked(deviceId);
871 return mscEvent >= 0 && mscEvent <= MSC_MAX && device != nullptr
872 ? device->mscBitmask.test(mscEvent)
873 : false;
874}
875
Michael Wrightd02c5b62014-02-10 15:10:22 -0800876int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
877 if (scanCode >= 0 && scanCode <= KEY_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000878 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800879
880 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700881 if (device != nullptr && device->hasValidFd() && device->keyBitmask.test(scanCode)) {
882 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
883 return device->keyState.test(scanCode) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800884 }
885 }
886 }
887 return AKEY_STATE_UNKNOWN;
888}
889
890int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
Chris Ye87143712020-11-10 05:05:58 +0000891 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800892
893 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700894 if (device != nullptr && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700895 std::vector<int32_t> scanCodes = device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800896 if (scanCodes.size() != 0) {
Chris Ye66fbac32020-07-06 20:36:43 -0700897 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800898 for (size_t i = 0; i < scanCodes.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800899 int32_t sc = scanCodes[i];
Chris Ye66fbac32020-07-06 20:36:43 -0700900 if (sc >= 0 && sc <= KEY_MAX && device->keyState.test(sc)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800901 return AKEY_STATE_DOWN;
902 }
903 }
904 return AKEY_STATE_UP;
905 }
906 }
907 }
908 return AKEY_STATE_UNKNOWN;
909}
910
Philip Junker4af3b3d2021-12-14 10:36:55 +0100911int32_t EventHub::getKeyCodeForKeyLocation(int32_t deviceId, int32_t locationKeyCode) const {
912 std::scoped_lock _l(mLock);
913
914 Device* device = getDeviceLocked(deviceId);
915 if (device == nullptr || !device->hasValidFd() || device->keyMap.keyCharacterMap == nullptr ||
916 device->keyMap.keyLayoutMap == nullptr) {
917 return AKEYCODE_UNKNOWN;
918 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700919 std::vector<int32_t> scanCodes =
920 device->keyMap.keyLayoutMap->findScanCodesForKey(locationKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +0100921 if (scanCodes.empty()) {
922 ALOGW("Failed to get key code for key location: no scan code maps to key code %d for input"
923 "device %d",
924 locationKeyCode, deviceId);
925 return AKEYCODE_UNKNOWN;
926 }
927 if (scanCodes.size() > 1) {
928 ALOGW("Multiple scan codes map to the same key code %d, returning only the first match",
929 locationKeyCode);
930 }
931 int32_t outKeyCode;
932 status_t mapKeyRes =
933 device->getKeyCharacterMap()->mapKey(scanCodes[0], 0 /*usageCode*/, &outKeyCode);
934 switch (mapKeyRes) {
935 case OK:
936 return outKeyCode;
937 case NAME_NOT_FOUND:
938 // key character map doesn't re-map this scanCode, hence the keyCode remains the same
939 return locationKeyCode;
940 default:
941 ALOGW("Failed to get key code for key location: Key character map returned error %s",
942 statusToString(mapKeyRes).c_str());
943 return AKEYCODE_UNKNOWN;
944 }
945}
946
Michael Wrightd02c5b62014-02-10 15:10:22 -0800947int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
948 if (sw >= 0 && sw <= SW_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000949 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800950
951 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700952 if (device != nullptr && device->hasValidFd() && device->swBitmask.test(sw)) {
953 if (device->readDeviceBitMask(EVIOCGSW(0), device->swState) >= 0) {
954 return device->swState.test(sw) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800955 }
956 }
957 }
958 return AKEY_STATE_UNKNOWN;
959}
960
961status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
962 *outValue = 0;
963
964 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000965 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800966
967 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700968 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800969 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700970 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
971 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
972 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800973 return -errno;
974 }
975
976 *outValue = info.value;
977 return OK;
978 }
979 }
980 return -1;
981}
982
Siarhei Vishniakou74007942022-06-13 13:57:47 -0700983bool EventHub::markSupportedKeyCodes(int32_t deviceId, const std::vector<int32_t>& keyCodes,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700984 uint8_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +0000985 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800986
987 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700988 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -0700989 for (size_t codeIndex = 0; codeIndex < keyCodes.size(); codeIndex++) {
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700990 std::vector<int32_t> scanCodes =
991 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCodes[codeIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800992
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700993 // check the possible scan codes identified by the layout map against the
994 // map of codes actually emitted by the driver
Siarhei Vishniakou74007942022-06-13 13:57:47 -0700995 for (const int32_t scanCode : scanCodes) {
996 if (device->keyBitmask.test(scanCode)) {
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700997 outFlags[codeIndex] = 1;
998 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800999 }
1000 }
1001 }
1002 return true;
1003 }
1004 return false;
1005}
1006
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001007status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
1008 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +00001009 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001010 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001011 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001012
Chris Ye66fbac32020-07-06 20:36:43 -07001013 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001014 // Check the key character map first.
Chris Ye3a1e4462020-08-12 10:13:15 -07001015 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
1016 if (kcm) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001017 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
1018 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001019 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001020 }
1021 }
1022
1023 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001024 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -08001025 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001026 status = NO_ERROR;
1027 }
1028 }
1029
1030 if (status == NO_ERROR) {
Chris Ye3a1e4462020-08-12 10:13:15 -07001031 if (kcm) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001032 kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState);
1033 } else {
1034 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001035 }
1036 }
1037 }
1038
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001039 if (status != NO_ERROR) {
1040 *outKeycode = 0;
1041 *outFlags = 0;
1042 *outMetaState = metaState;
1043 }
1044
1045 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001046}
1047
1048status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
Chris Ye87143712020-11-10 05:05:58 +00001049 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001050 Device* device = getDeviceLocked(deviceId);
1051
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001052 if (device == nullptr || !device->keyMap.haveKeyLayout()) {
1053 return NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001054 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001055 std::optional<AxisInfo> info = device->keyMap.keyLayoutMap->mapAxis(scanCode);
1056 if (!info.has_value()) {
1057 return NAME_NOT_FOUND;
1058 }
1059 *outAxisInfo = *info;
1060 return NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001061}
1062
Chris Yef59a2f42020-10-16 12:55:26 -07001063base::Result<std::pair<InputDeviceSensorType, int32_t>> EventHub::mapSensor(int32_t deviceId,
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001064 int32_t absCode) const {
Chris Yef59a2f42020-10-16 12:55:26 -07001065 std::scoped_lock _l(mLock);
1066 Device* device = getDeviceLocked(deviceId);
1067
1068 if (device != nullptr && device->keyMap.haveKeyLayout()) {
1069 return device->keyMap.keyLayoutMap->mapSensor(absCode);
1070 }
1071 return Errorf("Device not found or device has no key layout.");
1072}
1073
Chris Yee2b1e5c2021-03-10 22:45:12 -08001074// Gets the battery info map from battery ID to RawBatteryInfo of the miscellaneous device
1075// associated with the device ID. Returns an empty map if no miscellaneous device found.
1076const std::unordered_map<int32_t, RawBatteryInfo>& EventHub::getBatteryInfoLocked(
1077 int32_t deviceId) const {
1078 static const std::unordered_map<int32_t, RawBatteryInfo> EMPTY_BATTERY_INFO = {};
1079 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001080 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001081 return EMPTY_BATTERY_INFO;
1082 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001083 return device->associatedDevice->batteryInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001084}
1085
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001086std::vector<int32_t> EventHub::getRawBatteryIds(int32_t deviceId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001087 std::scoped_lock _l(mLock);
1088 std::vector<int32_t> batteryIds;
1089
Prabir Pradhan51894782022-08-23 16:29:10 +00001090 for (const auto& [id, info] : getBatteryInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001091 batteryIds.push_back(id);
1092 }
1093
1094 return batteryIds;
1095}
1096
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001097std::optional<RawBatteryInfo> EventHub::getRawBatteryInfo(int32_t deviceId,
1098 int32_t batteryId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001099 std::scoped_lock _l(mLock);
1100
1101 const auto infos = getBatteryInfoLocked(deviceId);
1102
1103 auto it = infos.find(batteryId);
1104 if (it != infos.end()) {
1105 return it->second;
1106 }
1107
1108 return std::nullopt;
1109}
1110
1111// Gets the light info map from light ID to RawLightInfo of the miscellaneous device associated
Prabir Pradhan51894782022-08-23 16:29:10 +00001112// with the device ID. Returns an empty map if no miscellaneous device found.
Chris Yee2b1e5c2021-03-10 22:45:12 -08001113const std::unordered_map<int32_t, RawLightInfo>& EventHub::getLightInfoLocked(
1114 int32_t deviceId) const {
1115 static const std::unordered_map<int32_t, RawLightInfo> EMPTY_LIGHT_INFO = {};
1116 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001117 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001118 return EMPTY_LIGHT_INFO;
1119 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001120 return device->associatedDevice->lightInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001121}
1122
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001123std::vector<int32_t> EventHub::getRawLightIds(int32_t deviceId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001124 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001125 std::vector<int32_t> lightIds;
1126
Prabir Pradhan51894782022-08-23 16:29:10 +00001127 for (const auto& [id, info] : getLightInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001128 lightIds.push_back(id);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001129 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001130
Chris Ye3fdbfef2021-01-06 18:45:18 -08001131 return lightIds;
1132}
1133
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001134std::optional<RawLightInfo> EventHub::getRawLightInfo(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001135 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001136
Chris Yee2b1e5c2021-03-10 22:45:12 -08001137 const auto infos = getLightInfoLocked(deviceId);
1138
1139 auto it = infos.find(lightId);
1140 if (it != infos.end()) {
1141 return it->second;
Chris Ye3fdbfef2021-01-06 18:45:18 -08001142 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001143
Chris Ye3fdbfef2021-01-06 18:45:18 -08001144 return std::nullopt;
1145}
1146
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001147std::optional<int32_t> EventHub::getLightBrightness(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001148 std::scoped_lock _l(mLock);
1149
Chris Yee2b1e5c2021-03-10 22:45:12 -08001150 const auto infos = getLightInfoLocked(deviceId);
1151 auto it = infos.find(lightId);
1152 if (it == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001153 return std::nullopt;
1154 }
1155 std::string buffer;
1156 if (!base::ReadFileToString(it->second.path / LIGHT_NODES.at(InputLightClass::BRIGHTNESS),
1157 &buffer)) {
1158 return std::nullopt;
1159 }
1160 return std::stoi(buffer);
1161}
1162
1163std::optional<std::unordered_map<LightColor, int32_t>> EventHub::getLightIntensities(
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001164 int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001165 std::scoped_lock _l(mLock);
1166
Chris Yee2b1e5c2021-03-10 22:45:12 -08001167 const auto infos = getLightInfoLocked(deviceId);
1168 auto lightIt = infos.find(lightId);
1169 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001170 return std::nullopt;
1171 }
1172
1173 auto ret =
1174 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1175
1176 if (!ret.has_value()) {
1177 return std::nullopt;
1178 }
1179 std::array<LightColor, COLOR_NUM> colors = ret.value();
1180
1181 std::string intensityStr;
1182 if (!base::ReadFileToString(lightIt->second.path /
1183 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY),
1184 &intensityStr)) {
1185 return std::nullopt;
1186 }
1187
1188 // Intensity node outputs 3 color values
1189 std::regex intensityPattern("([0-9]+)\\s([0-9]+)\\s([0-9]+)[\\n]");
1190 std::smatch results;
1191
1192 if (!std::regex_match(intensityStr, results, intensityPattern)) {
1193 return std::nullopt;
1194 }
1195 std::unordered_map<LightColor, int32_t> intensities;
1196 for (size_t i = 1; i < results.size(); i++) {
1197 int value = std::stoi(results[i].str());
1198 intensities.emplace(colors[i - 1], value);
1199 }
1200 return intensities;
1201}
1202
1203void EventHub::setLightBrightness(int32_t deviceId, int32_t lightId, int32_t brightness) {
1204 std::scoped_lock _l(mLock);
1205
Chris Yee2b1e5c2021-03-10 22:45:12 -08001206 const auto infos = getLightInfoLocked(deviceId);
1207 auto lightIt = infos.find(lightId);
1208 if (lightIt == infos.end()) {
1209 ALOGE("%s lightId %d not found ", __func__, lightId);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001210 return;
1211 }
1212
1213 if (!base::WriteStringToFile(std::to_string(brightness),
1214 lightIt->second.path /
1215 LIGHT_NODES.at(InputLightClass::BRIGHTNESS))) {
1216 ALOGE("Can not write to file, error: %s", strerror(errno));
1217 }
1218}
1219
1220void EventHub::setLightIntensities(int32_t deviceId, int32_t lightId,
1221 std::unordered_map<LightColor, int32_t> intensities) {
1222 std::scoped_lock _l(mLock);
1223
Chris Yee2b1e5c2021-03-10 22:45:12 -08001224 const auto infos = getLightInfoLocked(deviceId);
1225 auto lightIt = infos.find(lightId);
1226 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001227 ALOGE("Light Id %d does not exist.", lightId);
1228 return;
1229 }
1230
1231 auto ret =
1232 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1233
1234 if (!ret.has_value()) {
1235 return;
1236 }
1237 std::array<LightColor, COLOR_NUM> colors = ret.value();
1238
1239 std::string rgbStr;
1240 for (size_t i = 0; i < COLOR_NUM; i++) {
1241 auto it = intensities.find(colors[i]);
1242 if (it != intensities.end()) {
1243 rgbStr += std::to_string(it->second);
1244 // Insert space between colors
1245 if (i < COLOR_NUM - 1) {
1246 rgbStr += " ";
1247 }
1248 }
1249 }
1250 // Append new line
1251 rgbStr += "\n";
1252
1253 if (!base::WriteStringToFile(rgbStr,
1254 lightIt->second.path /
1255 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY))) {
1256 ALOGE("Can not write to file, error: %s", strerror(errno));
1257 }
1258}
1259
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001260InputDeviceCountryCode EventHub::getCountryCode(int32_t deviceId) const {
1261 std::scoped_lock _l(mLock);
1262 Device* device = getDeviceLocked(deviceId);
1263 if (device == nullptr || !device->associatedDevice) {
1264 return InputDeviceCountryCode::INVALID;
1265 }
1266 return device->associatedDevice->countryCode;
1267}
1268
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001269void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Chris Ye87143712020-11-10 05:05:58 +00001270 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001271
1272 mExcludedDevices = devices;
1273}
1274
1275bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
Chris Ye87143712020-11-10 05:05:58 +00001276 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001277 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001278 if (device != nullptr && scanCode >= 0 && scanCode <= KEY_MAX) {
1279 return device->keyBitmask.test(scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001280 }
1281 return false;
1282}
1283
Arthur Hungcb40a002021-08-03 14:31:01 +00001284bool EventHub::hasKeyCode(int32_t deviceId, int32_t keyCode) const {
1285 std::scoped_lock _l(mLock);
1286 Device* device = getDeviceLocked(deviceId);
1287 if (device != nullptr) {
1288 return device->hasKeycodeLocked(keyCode);
1289 }
1290 return false;
1291}
1292
Michael Wrightd02c5b62014-02-10 15:10:22 -08001293bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
Chris Ye87143712020-11-10 05:05:58 +00001294 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001295 Device* device = getDeviceLocked(deviceId);
1296 int32_t sc;
Chris Ye989bb932020-07-04 16:18:59 -07001297 if (device != nullptr && device->mapLed(led, &sc) == NO_ERROR) {
Chris Ye66fbac32020-07-06 20:36:43 -07001298 return device->ledBitmask.test(sc);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001299 }
1300 return false;
1301}
1302
1303void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
Chris Ye87143712020-11-10 05:05:58 +00001304 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001305 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -07001306 if (device != nullptr && device->hasValidFd()) {
1307 device->setLedStateLocked(led, on);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001308 }
1309}
1310
1311void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001312 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001313 outVirtualKeys.clear();
1314
Chris Ye87143712020-11-10 05:05:58 +00001315 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001316 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001317 if (device != nullptr && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001318 const std::vector<VirtualKeyDefinition> virtualKeys =
1319 device->virtualKeyMap->getVirtualKeys();
1320 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001321 }
1322}
1323
Chris Ye3a1e4462020-08-12 10:13:15 -07001324const std::shared_ptr<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001325 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001326 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001327 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001328 return device->getKeyCharacterMap();
1329 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001330 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001331}
1332
Chris Ye3a1e4462020-08-12 10:13:15 -07001333bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, std::shared_ptr<KeyCharacterMap> map) {
Chris Ye87143712020-11-10 05:05:58 +00001334 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001335 Device* device = getDeviceLocked(deviceId);
Philip Junker90bc9492021-12-10 18:39:42 +01001336 if (device == nullptr || map == nullptr || device->keyMap.keyCharacterMap == nullptr) {
1337 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001338 }
Philip Junker90bc9492021-12-10 18:39:42 +01001339 device->keyMap.keyCharacterMap->combine(*map);
1340 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001341}
1342
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001343static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
1344 std::string rawDescriptor;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001345 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001346 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001347 if (!identifier.uniqueId.empty()) {
1348 rawDescriptor += "uniqueId:";
1349 rawDescriptor += identifier.uniqueId;
Josh Bartel938632f2022-07-19 15:34:22 -05001350 }
1351 if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001352 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001353 }
1354
1355 if (identifier.vendor == 0 && identifier.product == 0) {
1356 // If we don't know the vendor and product id, then the device is probably
1357 // built-in so we need to rely on other information to uniquely identify
1358 // the input device. Usually we try to avoid relying on the device name or
1359 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001360 if (!identifier.name.empty()) {
1361 rawDescriptor += "name:";
1362 rawDescriptor += identifier.name;
1363 } else if (!identifier.location.empty()) {
1364 rawDescriptor += "location:";
1365 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001366 }
1367 }
1368 identifier.descriptor = sha1(rawDescriptor);
1369 return rawDescriptor;
1370}
1371
1372void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
1373 // Compute a device descriptor that uniquely identifies the device.
1374 // The descriptor is assumed to be a stable identifier. Its value should not
1375 // change between reboots, reconnections, firmware updates or new releases
1376 // of Android. In practice we sometimes get devices that cannot be uniquely
1377 // identified. In this case we enforce uniqueness between connected devices.
1378 // Ideally, we also want the descriptor to be short and relatively opaque.
Josh Bartel938632f2022-07-19 15:34:22 -05001379 // Note that we explicitly do not use the path or location for external devices
1380 // as their path or location will change as they are plugged/unplugged or moved
1381 // to different ports. We do fallback to using name and location in the case of
1382 // internal devices which are detected by the vendor and product being 0 in
1383 // generateDescriptor. If two identical descriptors are detected we will fallback
1384 // to using a 'nonce' and incrementing it until the new descriptor no longer has
1385 // a match with any existing descriptors.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001386
1387 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001388 std::string rawDescriptor = generateDescriptor(identifier);
Josh Bartel938632f2022-07-19 15:34:22 -05001389 // Enforce that the generated descriptor is unique.
1390 while (hasDeviceWithDescriptorLocked(identifier.descriptor)) {
1391 identifier.nonce++;
1392 rawDescriptor = generateDescriptor(identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001393 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001394 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001395 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001396}
1397
Prabir Pradhancb42b472022-08-23 16:01:19 +00001398std::shared_ptr<const EventHub::AssociatedDevice> EventHub::obtainAssociatedDeviceLocked(
1399 const std::filesystem::path& devicePath) const {
1400 const std::optional<std::filesystem::path> sysfsRootPathOpt =
1401 getSysfsRootPath(devicePath.c_str());
1402 if (!sysfsRootPathOpt) {
1403 return nullptr;
1404 }
1405
1406 const auto& path = *sysfsRootPathOpt;
1407 for (const auto& [id, dev] : mDevices) {
1408 if (dev->associatedDevice && dev->associatedDevice->sysfsRootPath == path) {
1409 return dev->associatedDevice;
1410 }
1411 }
1412
1413 return std::make_shared<AssociatedDevice>(
1414 AssociatedDevice{.sysfsRootPath = path,
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001415 .countryCode = readCountryCodeLocked(path),
Prabir Pradhancb42b472022-08-23 16:01:19 +00001416 .batteryInfos = readBatteryConfiguration(path),
1417 .lightInfos = readLightsConfiguration(path)});
1418}
1419
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001420void EventHub::vibrate(int32_t deviceId, const VibrationElement& element) {
Chris Ye87143712020-11-10 05:05:58 +00001421 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001422 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001423 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001424 ff_effect effect;
1425 memset(&effect, 0, sizeof(effect));
1426 effect.type = FF_RUMBLE;
1427 effect.id = device->ffEffectId;
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001428 // evdev FF_RUMBLE effect only supports two channels of vibration.
Chris Ye6393a262020-08-04 19:41:36 -07001429 effect.u.rumble.strong_magnitude = element.getMagnitude(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1430 effect.u.rumble.weak_magnitude = element.getMagnitude(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001431 effect.replay.length = element.duration.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001432 effect.replay.delay = 0;
1433 if (ioctl(device->fd, EVIOCSFF, &effect)) {
1434 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001435 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001436 return;
1437 }
1438 device->ffEffectId = effect.id;
1439
1440 struct input_event ev;
1441 ev.time.tv_sec = 0;
1442 ev.time.tv_usec = 0;
1443 ev.type = EV_FF;
1444 ev.code = device->ffEffectId;
1445 ev.value = 1;
1446 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1447 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001448 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001449 return;
1450 }
1451 device->ffEffectPlaying = true;
1452 }
1453}
1454
1455void EventHub::cancelVibrate(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001456 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001457 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001458 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001459 if (device->ffEffectPlaying) {
1460 device->ffEffectPlaying = false;
1461
1462 struct input_event ev;
1463 ev.time.tv_sec = 0;
1464 ev.time.tv_usec = 0;
1465 ev.type = EV_FF;
1466 ev.code = device->ffEffectId;
1467 ev.value = 0;
1468 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1469 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001470 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001471 return;
1472 }
1473 }
1474 }
1475}
1476
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001477std::vector<int32_t> EventHub::getVibratorIds(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001478 std::scoped_lock _l(mLock);
1479 std::vector<int32_t> vibrators;
1480 Device* device = getDeviceLocked(deviceId);
1481 if (device != nullptr && device->hasValidFd() &&
1482 device->classes.test(InputDeviceClass::VIBRATOR)) {
1483 vibrators.push_back(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1484 vibrators.push_back(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
1485 }
1486 return vibrators;
1487}
1488
Josh Bartel938632f2022-07-19 15:34:22 -05001489/**
1490 * Checks both mDevices and mOpeningDevices for a device with the descriptor passed.
1491 */
1492bool EventHub::hasDeviceWithDescriptorLocked(const std::string& descriptor) const {
1493 for (const auto& device : mOpeningDevices) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001494 if (descriptor == device->identifier.descriptor) {
Josh Bartel938632f2022-07-19 15:34:22 -05001495 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001496 }
1497 }
Josh Bartel938632f2022-07-19 15:34:22 -05001498
1499 for (const auto& [id, device] : mDevices) {
1500 if (descriptor == device->identifier.descriptor) {
1501 return true;
1502 }
1503 }
1504 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001505}
1506
1507EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001508 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001509 deviceId = mBuiltInKeyboardId;
1510 }
Chris Ye989bb932020-07-04 16:18:59 -07001511 const auto& it = mDevices.find(deviceId);
1512 return it != mDevices.end() ? it->second.get() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001513}
1514
Chris Ye8594e192020-07-14 10:34:06 -07001515EventHub::Device* EventHub::getDeviceByPathLocked(const std::string& devicePath) const {
Chris Ye989bb932020-07-04 16:18:59 -07001516 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001517 if (device->path == devicePath) {
Chris Ye989bb932020-07-04 16:18:59 -07001518 return device.get();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001519 }
1520 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001521 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001522}
1523
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001524/**
1525 * The file descriptor could be either input device, or a video device (associated with a
1526 * specific input device). Check both cases here, and return the device that this event
1527 * belongs to. Caller can compare the fd's once more to determine event type.
1528 * Looks through all input devices, and only attached video devices. Unattached video
1529 * devices are ignored.
1530 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001531EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
Chris Ye989bb932020-07-04 16:18:59 -07001532 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001533 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001534 // This is an input device event
Chris Ye989bb932020-07-04 16:18:59 -07001535 return device.get();
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001536 }
1537 if (device->videoDevice && device->videoDevice->getFd() == fd) {
1538 // This is a video device event
Chris Ye989bb932020-07-04 16:18:59 -07001539 return device.get();
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001540 }
1541 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001542 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
1543 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001544 return nullptr;
1545}
1546
Chris Yee2b1e5c2021-03-10 22:45:12 -08001547std::optional<int32_t> EventHub::getBatteryCapacity(int32_t deviceId, int32_t batteryId) const {
Kim Low03ea0352020-11-06 12:45:07 -08001548 std::scoped_lock _l(mLock);
Kim Low03ea0352020-11-06 12:45:07 -08001549
Chris Yee2b1e5c2021-03-10 22:45:12 -08001550 const auto infos = getBatteryInfoLocked(deviceId);
1551 auto it = infos.find(batteryId);
1552 if (it == infos.end()) {
Kim Low03ea0352020-11-06 12:45:07 -08001553 return std::nullopt;
1554 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001555 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001556
1557 // Some devices report battery capacity as an integer through the "capacity" file
Chris Yee2b1e5c2021-03-10 22:45:12 -08001558 if (base::ReadFileToString(it->second.path / BATTERY_NODES.at(InputBatteryClass::CAPACITY),
1559 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001560 return std::stoi(base::Trim(buffer));
Kim Low03ea0352020-11-06 12:45:07 -08001561 }
1562
1563 // Other devices report capacity as an enum value POWER_SUPPLY_CAPACITY_LEVEL_XXX
1564 // These values are taken from kernel source code include/linux/power_supply.h
Chris Yee2b1e5c2021-03-10 22:45:12 -08001565 if (base::ReadFileToString(it->second.path /
1566 BATTERY_NODES.at(InputBatteryClass::CAPACITY_LEVEL),
1567 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001568 // Remove any white space such as trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001569 const auto levelIt = BATTERY_LEVEL.find(base::Trim(buffer));
1570 if (levelIt != BATTERY_LEVEL.end()) {
1571 return levelIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001572 }
1573 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001574
Kim Low03ea0352020-11-06 12:45:07 -08001575 return std::nullopt;
1576}
1577
Chris Yee2b1e5c2021-03-10 22:45:12 -08001578std::optional<int32_t> EventHub::getBatteryStatus(int32_t deviceId, int32_t batteryId) const {
Kim Low03ea0352020-11-06 12:45:07 -08001579 std::scoped_lock _l(mLock);
Chris Yee2b1e5c2021-03-10 22:45:12 -08001580 const auto infos = getBatteryInfoLocked(deviceId);
1581 auto it = infos.find(batteryId);
1582 if (it == infos.end()) {
Kim Low03ea0352020-11-06 12:45:07 -08001583 return std::nullopt;
1584 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001585 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001586
Chris Yee2b1e5c2021-03-10 22:45:12 -08001587 if (!base::ReadFileToString(it->second.path / BATTERY_NODES.at(InputBatteryClass::STATUS),
1588 &buffer)) {
Kim Low03ea0352020-11-06 12:45:07 -08001589 ALOGE("Failed to read sysfs battery info: %s", strerror(errno));
1590 return std::nullopt;
1591 }
1592
Chris Yed1936772021-02-22 10:30:40 -08001593 // Remove white space like trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001594 const auto statusIt = BATTERY_STATUS.find(base::Trim(buffer));
1595 if (statusIt != BATTERY_STATUS.end()) {
1596 return statusIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001597 }
1598
1599 return std::nullopt;
1600}
1601
Michael Wrightd02c5b62014-02-10 15:10:22 -08001602size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
1603 ALOG_ASSERT(bufferSize >= 1);
1604
Chris Ye87143712020-11-10 05:05:58 +00001605 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001606
1607 struct input_event readBuffer[bufferSize];
1608
1609 RawEvent* event = buffer;
1610 size_t capacity = bufferSize;
1611 bool awoken = false;
1612 for (;;) {
1613 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
1614
1615 // Reopen input devices if needed.
1616 if (mNeedToReopenDevices) {
1617 mNeedToReopenDevices = false;
1618
1619 ALOGI("Reopening all input devices due to a configuration change.");
1620
1621 closeAllDevicesLocked();
1622 mNeedToScanDevices = true;
1623 break; // return to the caller before we actually rescan
1624 }
1625
1626 // Report any devices that had last been added/removed.
Chris Ye989bb932020-07-04 16:18:59 -07001627 for (auto it = mClosingDevices.begin(); it != mClosingDevices.end();) {
1628 std::unique_ptr<Device> device = std::move(*it);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001629 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001630 event->when = now;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001631 event->deviceId = (device->id == mBuiltInKeyboardId)
1632 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
1633 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001634 event->type = DEVICE_REMOVED;
1635 event += 1;
Chris Ye989bb932020-07-04 16:18:59 -07001636 it = mClosingDevices.erase(it);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001637 mNeedToSendFinishedDeviceScan = true;
1638 if (--capacity == 0) {
1639 break;
1640 }
1641 }
1642
1643 if (mNeedToScanDevices) {
1644 mNeedToScanDevices = false;
1645 scanDevicesLocked();
1646 mNeedToSendFinishedDeviceScan = true;
1647 }
1648
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001649 while (!mOpeningDevices.empty()) {
1650 std::unique_ptr<Device> device = std::move(*mOpeningDevices.rbegin());
1651 mOpeningDevices.pop_back();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001652 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001653 event->when = now;
1654 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1655 event->type = DEVICE_ADDED;
1656 event += 1;
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001657
1658 // Try to find a matching video device by comparing device names
1659 for (auto it = mUnattachedVideoDevices.begin(); it != mUnattachedVideoDevices.end();
1660 it++) {
1661 std::unique_ptr<TouchVideoDevice>& videoDevice = *it;
Chris Yed3fef462021-03-07 17:10:08 -08001662 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001663 // videoDevice was transferred to 'device'
1664 it = mUnattachedVideoDevices.erase(it);
1665 break;
1666 }
1667 }
1668
1669 auto [dev_it, inserted] = mDevices.insert_or_assign(device->id, std::move(device));
1670 if (!inserted) {
Chris Ye989bb932020-07-04 16:18:59 -07001671 ALOGW("Device id %d exists, replaced.", device->id);
1672 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001673 mNeedToSendFinishedDeviceScan = true;
1674 if (--capacity == 0) {
1675 break;
1676 }
1677 }
1678
1679 if (mNeedToSendFinishedDeviceScan) {
1680 mNeedToSendFinishedDeviceScan = false;
1681 event->when = now;
1682 event->type = FINISHED_DEVICE_SCAN;
1683 event += 1;
1684 if (--capacity == 0) {
1685 break;
1686 }
1687 }
1688
1689 // Grab the next input event.
1690 bool deviceChanged = false;
1691 while (mPendingEventIndex < mPendingEventCount) {
1692 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001693 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001694 if (eventItem.events & EPOLLIN) {
1695 mPendingINotify = true;
1696 } else {
1697 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
1698 }
1699 continue;
1700 }
1701
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001702 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001703 if (eventItem.events & EPOLLIN) {
1704 ALOGV("awoken after wake()");
1705 awoken = true;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001706 char wakeReadBuffer[16];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001707 ssize_t nRead;
1708 do {
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001709 nRead = read(mWakeReadPipeFd, wakeReadBuffer, sizeof(wakeReadBuffer));
1710 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(wakeReadBuffer));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001711 } else {
1712 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001713 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001714 }
1715 continue;
1716 }
1717
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001718 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Chris Ye989bb932020-07-04 16:18:59 -07001719 if (device == nullptr) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001720 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
1721 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001722 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001723 continue;
1724 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001725 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
1726 if (eventItem.events & EPOLLIN) {
1727 size_t numFrames = device->videoDevice->readAndQueueFrames();
1728 if (numFrames == 0) {
1729 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001730 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001731 }
1732 } else if (eventItem.events & EPOLLHUP) {
1733 // TODO(b/121395353) - consider adding EPOLLRDHUP
1734 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001735 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001736 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1737 device->videoDevice = nullptr;
1738 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001739 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1740 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001741 ALOG_ASSERT(!DEBUG);
1742 }
1743 continue;
1744 }
1745 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -08001746 if (eventItem.events & EPOLLIN) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001747 int32_t readSize =
1748 read(device->fd, readBuffer, sizeof(struct input_event) * capacity);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001749 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
1750 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -07001751 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001752 " bufferSize: %zu capacity: %zu errno: %d)\n",
1753 device->fd, readSize, bufferSize, capacity, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001754 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001755 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001756 } else if (readSize < 0) {
1757 if (errno != EAGAIN && errno != EINTR) {
1758 ALOGW("could not get event (errno=%d)", errno);
1759 }
1760 } else if ((readSize % sizeof(struct input_event)) != 0) {
1761 ALOGE("could not get event (wrong size: %d)", readSize);
1762 } else {
1763 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1764
1765 size_t count = size_t(readSize) / sizeof(struct input_event);
1766 for (size_t i = 0; i < count; i++) {
1767 struct input_event& iev = readBuffer[i];
Siarhei Vishniakou592bac22018-11-08 19:42:38 -08001768 event->when = processEventTimestamp(iev);
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001769 event->readTime = systemTime(SYSTEM_TIME_MONOTONIC);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001770 event->deviceId = deviceId;
1771 event->type = iev.type;
1772 event->code = iev.code;
1773 event->value = iev.value;
1774 event += 1;
1775 capacity -= 1;
1776 }
1777 if (capacity == 0) {
1778 // The result buffer is full. Reset the pending event index
1779 // so we will try to read the device again on the next iteration.
1780 mPendingEventIndex -= 1;
1781 break;
1782 }
1783 }
1784 } else if (eventItem.events & EPOLLHUP) {
1785 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001786 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001787 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001788 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001789 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001790 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1791 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001792 }
1793 }
1794
1795 // readNotify() will modify the list of devices so this must be done after
1796 // processing all other events to ensure that we read all remaining events
1797 // before closing the devices.
1798 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
1799 mPendingINotify = false;
Prabir Pradhan952e65b2022-06-23 17:49:55 +00001800 const auto res = readNotifyLocked();
1801 if (!res.ok()) {
1802 ALOGW("Failed to read from inotify: %s", res.error().message().c_str());
1803 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001804 deviceChanged = true;
1805 }
1806
1807 // Report added or removed devices immediately.
1808 if (deviceChanged) {
1809 continue;
1810 }
1811
1812 // Return now if we have collected any events or if we were explicitly awoken.
1813 if (event != buffer || awoken) {
1814 break;
1815 }
1816
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001817 // Poll for events.
1818 // When a device driver has pending (unread) events, it acquires
1819 // a kernel wake lock. Once the last pending event has been read, the device
1820 // driver will release the kernel wake lock, but the epoll will hold the wakelock,
1821 // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
1822 // is called again for the same fd that produced the event.
1823 // Thus the system can only sleep if there are no events pending or
1824 // currently being processed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001825 //
1826 // The timeout is advisory only. If the device is asleep, it will not wake just to
1827 // service the timeout.
1828 mPendingEventIndex = 0;
1829
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001830 mLock.unlock(); // release lock before poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001831
1832 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1833
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001834 mLock.lock(); // reacquire lock after poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001835
1836 if (pollResult == 0) {
1837 // Timed out.
1838 mPendingEventCount = 0;
1839 break;
1840 }
1841
1842 if (pollResult < 0) {
1843 // An error occurred.
1844 mPendingEventCount = 0;
1845
1846 // Sleep after errors to avoid locking up the system.
1847 // Hopefully the error is transient.
1848 if (errno != EINTR) {
1849 ALOGW("poll failed (errno=%d)\n", errno);
1850 usleep(100000);
1851 }
1852 } else {
1853 // Some events occurred.
1854 mPendingEventCount = size_t(pollResult);
1855 }
1856 }
1857
1858 // All done, return the number of events we read.
1859 return event - buffer;
1860}
1861
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001862std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001863 std::scoped_lock _l(mLock);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001864
1865 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001866 if (device == nullptr || !device->videoDevice) {
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001867 return {};
1868 }
1869 return device->videoDevice->consumeFrames();
1870}
1871
Michael Wrightd02c5b62014-02-10 15:10:22 -08001872void EventHub::wake() {
1873 ALOGV("wake() called");
1874
1875 ssize_t nWrite;
1876 do {
1877 nWrite = write(mWakeWritePipeFd, "W", 1);
1878 } while (nWrite == -1 && errno == EINTR);
1879
1880 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001881 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001882 }
1883}
1884
1885void EventHub::scanDevicesLocked() {
Usama Arifb27c8e62021-06-03 16:44:09 +01001886 status_t result;
1887 std::error_code errorCode;
1888
1889 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
1890 result = scanDirLocked(DEVICE_INPUT_PATH);
1891 if (result < 0) {
1892 ALOGE("scan dir failed for %s", DEVICE_INPUT_PATH);
1893 }
1894 } else {
1895 if (errorCode) {
1896 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
1897 errorCode.message().c_str());
1898 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001899 }
Philip Quinn39b81682019-01-09 22:20:39 -08001900 if (isV4lScanningEnabled()) {
Usama Arifb27c8e62021-06-03 16:44:09 +01001901 result = scanVideoDirLocked(DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08001902 if (result != OK) {
Usama Arifb27c8e62021-06-03 16:44:09 +01001903 ALOGE("scan video dir failed for %s", DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08001904 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001905 }
Chris Ye989bb932020-07-04 16:18:59 -07001906 if (mDevices.find(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) == mDevices.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001907 createVirtualKeyboardLocked();
1908 }
1909}
1910
1911// ----------------------------------------------------------------------------
1912
Michael Wrightd02c5b62014-02-10 15:10:22 -08001913static const int32_t GAMEPAD_KEYCODES[] = {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001914 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C, //
1915 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z, //
1916 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1, //
1917 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2, //
1918 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR, //
1919 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE, //
Michael Wrightd02c5b62014-02-10 15:10:22 -08001920};
1921
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001922status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001923 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001924 struct epoll_event eventItem = {};
1925 eventItem.events = EPOLLIN | EPOLLWAKEUP;
1926 eventItem.data.fd = fd;
1927 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1928 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001929 return -errno;
1930 }
1931 return OK;
1932}
1933
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001934status_t EventHub::unregisterFdFromEpoll(int fd) {
1935 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
1936 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
1937 return -errno;
1938 }
1939 return OK;
1940}
1941
Chris Ye989bb932020-07-04 16:18:59 -07001942status_t EventHub::registerDeviceForEpollLocked(Device& device) {
1943 status_t result = registerFdForEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001944 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07001945 ALOGE("Could not add input device fd to epoll for device %" PRId32, device.id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001946 return result;
1947 }
Chris Ye989bb932020-07-04 16:18:59 -07001948 if (device.videoDevice) {
1949 registerVideoDeviceForEpollLocked(*device.videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001950 }
1951 return result;
1952}
1953
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001954void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
1955 status_t result = registerFdForEpoll(videoDevice.getFd());
1956 if (result != OK) {
1957 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
1958 }
1959}
1960
Chris Ye989bb932020-07-04 16:18:59 -07001961status_t EventHub::unregisterDeviceFromEpollLocked(Device& device) {
1962 if (device.hasValidFd()) {
1963 status_t result = unregisterFdFromEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001964 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07001965 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device.id);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001966 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001967 }
1968 }
Chris Ye989bb932020-07-04 16:18:59 -07001969 if (device.videoDevice) {
1970 unregisterVideoDeviceFromEpollLocked(*device.videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001971 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001972 return OK;
1973}
1974
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001975void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
1976 if (videoDevice.hasValidFd()) {
1977 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
1978 if (result != OK) {
1979 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001980 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001981 }
1982 }
1983}
1984
Chris Yed3fef462021-03-07 17:10:08 -08001985void EventHub::reportDeviceAddedForStatisticsLocked(const InputDeviceIdentifier& identifier,
Dominik Laskowski2f01d772022-03-23 16:01:29 -07001986 ftl::Flags<InputDeviceClass> classes) {
Chris Ye657c2f02021-05-25 16:24:37 -07001987 SHA256_CTX ctx;
1988 SHA256_Init(&ctx);
1989 SHA256_Update(&ctx, reinterpret_cast<const uint8_t*>(identifier.uniqueId.c_str()),
1990 identifier.uniqueId.size());
1991 std::array<uint8_t, SHA256_DIGEST_LENGTH> digest;
1992 SHA256_Final(digest.data(), &ctx);
1993
1994 std::string obfuscatedId;
1995 for (size_t i = 0; i < OBFUSCATED_LENGTH; i++) {
1996 obfuscatedId += StringPrintf("%02x", digest[i]);
1997 }
1998
Chris Yed3fef462021-03-07 17:10:08 -08001999 android::util::stats_write(android::util::INPUTDEVICE_REGISTERED, identifier.name.c_str(),
2000 identifier.vendor, identifier.product, identifier.version,
Chris Ye657c2f02021-05-25 16:24:37 -07002001 identifier.bus, obfuscatedId.c_str(), classes.get());
Chris Yed3fef462021-03-07 17:10:08 -08002002}
2003
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002004void EventHub::openDeviceLocked(const std::string& devicePath) {
2005 // If an input device happens to register around the time when EventHub's constructor runs, it
2006 // is possible that the same input event node (for example, /dev/input/event3) will be noticed
2007 // in both 'inotify' callback and also in the 'scanDirLocked' pass. To prevent duplicate devices
2008 // from getting registered, ensure that this path is not already covered by an existing device.
2009 for (const auto& [deviceId, device] : mDevices) {
2010 if (device->path == devicePath) {
2011 return; // device was already registered
2012 }
2013 }
2014
Michael Wrightd02c5b62014-02-10 15:10:22 -08002015 char buffer[80];
2016
Chris Ye8594e192020-07-14 10:34:06 -07002017 ALOGV("Opening device: %s", devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002018
Chris Ye8594e192020-07-14 10:34:06 -07002019 int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002020 if (fd < 0) {
Chris Ye8594e192020-07-14 10:34:06 -07002021 ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002022 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002023 }
2024
2025 InputDeviceIdentifier identifier;
2026
2027 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002028 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Chris Ye8594e192020-07-14 10:34:06 -07002029 ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002030 } else {
2031 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002032 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002033 }
2034
2035 // Check to see if the device is on our excluded list
2036 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002037 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002038 if (identifier.name == item) {
Chris Ye8594e192020-07-14 10:34:06 -07002039 ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002040 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002041 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002042 }
2043 }
2044
2045 // Get device driver version.
2046 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002047 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Chris Ye8594e192020-07-14 10:34:06 -07002048 ALOGE("could not get driver version for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002049 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002050 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002051 }
2052
2053 // Get device identifier.
2054 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002055 if (ioctl(fd, EVIOCGID, &inputId)) {
Chris Ye8594e192020-07-14 10:34:06 -07002056 ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002057 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002058 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002059 }
2060 identifier.bus = inputId.bustype;
2061 identifier.product = inputId.product;
2062 identifier.vendor = inputId.vendor;
2063 identifier.version = inputId.version;
2064
2065 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002066 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
2067 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002068 } else {
2069 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002070 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002071 }
2072
2073 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002074 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
2075 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002076 } else {
2077 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002078 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002079 }
2080
2081 // Fill in the descriptor.
2082 assignDescriptorLocked(identifier);
2083
Michael Wrightd02c5b62014-02-10 15:10:22 -08002084 // Allocate device. (The device object takes ownership of the fd at this point.)
2085 int32_t deviceId = mNextDeviceId++;
Prabir Pradhancb42b472022-08-23 16:01:19 +00002086 std::unique_ptr<Device> device =
2087 std::make_unique<Device>(fd, deviceId, devicePath, identifier,
2088 obtainAssociatedDeviceLocked(devicePath));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002089
Chris Ye8594e192020-07-14 10:34:06 -07002090 ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002091 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002092 " vendor %04x\n"
2093 " product %04x\n"
2094 " version %04x\n",
2095 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002096 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
2097 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
2098 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
2099 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002100 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
2101 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002102
2103 // Load the configuration file for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002104 device->loadConfigurationLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002105
2106 // Figure out the kinds of events the device reports.
Chris Ye66fbac32020-07-06 20:36:43 -07002107 device->readDeviceBitMask(EVIOCGBIT(EV_KEY, 0), device->keyBitmask);
2108 device->readDeviceBitMask(EVIOCGBIT(EV_ABS, 0), device->absBitmask);
2109 device->readDeviceBitMask(EVIOCGBIT(EV_REL, 0), device->relBitmask);
2110 device->readDeviceBitMask(EVIOCGBIT(EV_SW, 0), device->swBitmask);
2111 device->readDeviceBitMask(EVIOCGBIT(EV_LED, 0), device->ledBitmask);
2112 device->readDeviceBitMask(EVIOCGBIT(EV_FF, 0), device->ffBitmask);
Chris Yef59a2f42020-10-16 12:55:26 -07002113 device->readDeviceBitMask(EVIOCGBIT(EV_MSC, 0), device->mscBitmask);
Chris Ye66fbac32020-07-06 20:36:43 -07002114 device->readDeviceBitMask(EVIOCGPROP(0), device->propBitmask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002115
2116 // See if this is a keyboard. Ignore everything in the button range except for
2117 // joystick and gamepad buttons which are handled like keyboards for the most part.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002118 bool haveKeyboardKeys =
Chris Ye66fbac32020-07-06 20:36:43 -07002119 device->keyBitmask.any(0, BTN_MISC) || device->keyBitmask.any(BTN_WHEEL, KEY_MAX + 1);
2120 bool haveGamepadButtons = device->keyBitmask.any(BTN_MISC, BTN_MOUSE) ||
2121 device->keyBitmask.any(BTN_JOYSTICK, BTN_DIGI);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002122 if (haveKeyboardKeys || haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002123 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002124 }
2125
2126 // See if this is a cursor device such as a trackball or mouse.
Chris Ye66fbac32020-07-06 20:36:43 -07002127 if (device->keyBitmask.test(BTN_MOUSE) && device->relBitmask.test(REL_X) &&
2128 device->relBitmask.test(REL_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002129 device->classes |= InputDeviceClass::CURSOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002130 }
2131
Prashant Malani1941ff52015-08-11 18:29:28 -07002132 // See if this is a rotary encoder type device.
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07002133 std::string deviceType;
2134 if (device->configuration && device->configuration->tryGetProperty("device.type", deviceType)) {
2135 if (deviceType == "rotaryEncoder") {
Chris Ye1b0c7342020-07-28 21:57:03 -07002136 device->classes |= InputDeviceClass::ROTARY_ENCODER;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002137 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002138 }
2139
Michael Wrightd02c5b62014-02-10 15:10:22 -08002140 // See if this is a touch pad.
2141 // Is this a new modern multi-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002142 if (device->absBitmask.test(ABS_MT_POSITION_X) && device->absBitmask.test(ABS_MT_POSITION_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002143 // Some joysticks such as the PS3 controller report axes that conflict
2144 // with the ABS_MT range. Try to confirm that the device really is
2145 // a touch screen.
Chris Ye66fbac32020-07-06 20:36:43 -07002146 if (device->keyBitmask.test(BTN_TOUCH) || !haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002147 device->classes |= (InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002148 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002149 // Is this an old style single-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002150 } else if (device->keyBitmask.test(BTN_TOUCH) && device->absBitmask.test(ABS_X) &&
2151 device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002152 device->classes |= InputDeviceClass::TOUCH;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002153 // Is this a BT stylus?
Chris Ye66fbac32020-07-06 20:36:43 -07002154 } else if ((device->absBitmask.test(ABS_PRESSURE) || device->keyBitmask.test(BTN_TOUCH)) &&
2155 !device->absBitmask.test(ABS_X) && !device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002156 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -07002157 // Keyboard will try to claim some of the buttons but we really want to reserve those so we
2158 // can fuse it with the touch screen data, so just take them back. Note this means an
2159 // external stylus cannot also be a keyboard device.
Chris Ye1b0c7342020-07-28 21:57:03 -07002160 device->classes &= ~InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002161 }
2162
2163 // See if this device is a joystick.
2164 // Assumes that joysticks always have gamepad buttons in order to distinguish them
2165 // from other devices such as accelerometers that also have absolute axes.
2166 if (haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002167 auto assumedClasses = device->classes | InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002168 for (int i = 0; i <= ABS_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002169 if (device->absBitmask.test(i) &&
Chris Ye1b0c7342020-07-28 21:57:03 -07002170 (getAbsAxisUsage(i, assumedClasses).test(InputDeviceClass::JOYSTICK))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002171 device->classes = assumedClasses;
2172 break;
2173 }
2174 }
2175 }
2176
Chris Yef59a2f42020-10-16 12:55:26 -07002177 // Check whether this device is an accelerometer.
2178 if (device->propBitmask.test(INPUT_PROP_ACCELEROMETER)) {
2179 device->classes |= InputDeviceClass::SENSOR;
2180 }
2181
Michael Wrightd02c5b62014-02-10 15:10:22 -08002182 // Check whether this device has switches.
2183 for (int i = 0; i <= SW_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002184 if (device->swBitmask.test(i)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002185 device->classes |= InputDeviceClass::SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002186 break;
2187 }
2188 }
2189
2190 // Check whether this device supports the vibrator.
Chris Ye66fbac32020-07-06 20:36:43 -07002191 if (device->ffBitmask.test(FF_RUMBLE)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002192 device->classes |= InputDeviceClass::VIBRATOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002193 }
2194
2195 // Configure virtual keys.
Chris Ye1b0c7342020-07-28 21:57:03 -07002196 if ((device->classes.test(InputDeviceClass::TOUCH))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002197 // Load the virtual keys for the touch screen, if any.
2198 // We do this now so that we can make sure to load the keymap if necessary.
Chris Ye989bb932020-07-04 16:18:59 -07002199 bool success = device->loadVirtualKeyMapLocked();
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06002200 if (success) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002201 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002202 }
2203 }
2204
2205 // Load the key map.
Chris Yef59a2f42020-10-16 12:55:26 -07002206 // We need to do this for joysticks too because the key layout may specify axes, and for
2207 // sensor as well because the key layout may specify the axes to sensor data mapping.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002208 status_t keyMapStatus = NAME_NOT_FOUND;
Chris Yef59a2f42020-10-16 12:55:26 -07002209 if (device->classes.any(InputDeviceClass::KEYBOARD | InputDeviceClass::JOYSTICK |
2210 InputDeviceClass::SENSOR)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002211 // Load the keymap for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002212 keyMapStatus = device->loadKeyMapLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002213 }
2214
2215 // Configure the keyboard, gamepad or virtual keyboard.
Chris Ye1b0c7342020-07-28 21:57:03 -07002216 if (device->classes.test(InputDeviceClass::KEYBOARD)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002217 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002218 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002219 isEligibleBuiltInKeyboard(device->identifier, device->configuration.get(),
2220 &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002221 mBuiltInKeyboardId = device->id;
2222 }
2223
2224 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
Chris Ye989bb932020-07-04 16:18:59 -07002225 if (device->hasKeycodeLocked(AKEYCODE_Q)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002226 device->classes |= InputDeviceClass::ALPHAKEY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002227 }
2228
2229 // See if this device has a DPAD.
Chris Ye989bb932020-07-04 16:18:59 -07002230 if (device->hasKeycodeLocked(AKEYCODE_DPAD_UP) &&
2231 device->hasKeycodeLocked(AKEYCODE_DPAD_DOWN) &&
2232 device->hasKeycodeLocked(AKEYCODE_DPAD_LEFT) &&
2233 device->hasKeycodeLocked(AKEYCODE_DPAD_RIGHT) &&
2234 device->hasKeycodeLocked(AKEYCODE_DPAD_CENTER)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002235 device->classes |= InputDeviceClass::DPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002236 }
2237
2238 // See if this device has a gamepad.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002239 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES) / sizeof(GAMEPAD_KEYCODES[0]); i++) {
Chris Ye989bb932020-07-04 16:18:59 -07002240 if (device->hasKeycodeLocked(GAMEPAD_KEYCODES[i])) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002241 device->classes |= InputDeviceClass::GAMEPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242 break;
2243 }
2244 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002245 }
2246
2247 // If the device isn't recognized as something we handle, don't monitor it.
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002248 if (device->classes == ftl::Flags<InputDeviceClass>(0)) {
Chris Ye8594e192020-07-14 10:34:06 -07002249 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002250 device->identifier.name.c_str());
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002251 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002252 }
2253
Chris Ye3fdbfef2021-01-06 18:45:18 -08002254 // Classify InputDeviceClass::BATTERY.
Prabir Pradhan51894782022-08-23 16:29:10 +00002255 if (device->associatedDevice && !device->associatedDevice->batteryInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002256 device->classes |= InputDeviceClass::BATTERY;
2257 }
Kim Low03ea0352020-11-06 12:45:07 -08002258
Chris Ye3fdbfef2021-01-06 18:45:18 -08002259 // Classify InputDeviceClass::LIGHT.
Prabir Pradhan51894782022-08-23 16:29:10 +00002260 if (device->associatedDevice && !device->associatedDevice->lightInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002261 device->classes |= InputDeviceClass::LIGHT;
Kim Low03ea0352020-11-06 12:45:07 -08002262 }
2263
Tim Kilbourn063ff532015-04-08 10:26:18 -07002264 // Determine whether the device has a mic.
Chris Ye989bb932020-07-04 16:18:59 -07002265 if (device->deviceHasMicLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002266 device->classes |= InputDeviceClass::MIC;
Tim Kilbourn063ff532015-04-08 10:26:18 -07002267 }
2268
Michael Wrightd02c5b62014-02-10 15:10:22 -08002269 // Determine whether the device is external or internal.
Chris Ye989bb932020-07-04 16:18:59 -07002270 if (device->isExternalDeviceLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002271 device->classes |= InputDeviceClass::EXTERNAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002272 }
2273
Chris Ye1b0c7342020-07-28 21:57:03 -07002274 if (device->classes.any(InputDeviceClass::JOYSTICK | InputDeviceClass::DPAD) &&
2275 device->classes.test(InputDeviceClass::GAMEPAD)) {
Chris Ye989bb932020-07-04 16:18:59 -07002276 device->controllerNumber = getNextControllerNumberLocked(device->identifier.name);
2277 device->setLedForControllerLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002278 }
2279
Chris Ye989bb932020-07-04 16:18:59 -07002280 if (registerDeviceForEpollLocked(*device) != OK) {
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002281 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002282 }
2283
Chris Ye989bb932020-07-04 16:18:59 -07002284 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002285
Chris Ye1b0c7342020-07-28 21:57:03 -07002286 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=%s, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002287 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Chris Ye1b0c7342020-07-28 21:57:03 -07002288 deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(),
2289 device->classes.string().c_str(), device->configurationFile.c_str(),
2290 device->keyMap.keyLayoutFile.c_str(), device->keyMap.keyCharacterMapFile.c_str(),
2291 toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002292
Chris Ye989bb932020-07-04 16:18:59 -07002293 addDeviceLocked(std::move(device));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002294}
2295
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002296void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
2297 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
2298 if (!videoDevice) {
2299 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
2300 return;
2301 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002302 // Transfer ownership of this video device to a matching input device
Chris Ye989bb932020-07-04 16:18:59 -07002303 for (const auto& [id, device] : mDevices) {
Chris Yed3fef462021-03-07 17:10:08 -08002304 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002305 return; // 'device' now owns 'videoDevice'
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002306 }
2307 }
2308
2309 // Couldn't find a matching input device, so just add it to a temporary holding queue.
2310 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002311 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002312 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002313 mUnattachedVideoDevices.push_back(std::move(videoDevice));
2314}
2315
Chris Yed3fef462021-03-07 17:10:08 -08002316bool EventHub::tryAddVideoDeviceLocked(EventHub::Device& device,
2317 std::unique_ptr<TouchVideoDevice>& videoDevice) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002318 if (videoDevice->getName() != device.identifier.name) {
2319 return false;
2320 }
2321 device.videoDevice = std::move(videoDevice);
2322 if (device.enabled) {
2323 registerVideoDeviceForEpollLocked(*device.videoDevice);
2324 }
2325 return true;
2326}
2327
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002328bool EventHub::isDeviceEnabled(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00002329 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002330 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002331 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002332 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2333 return false;
2334 }
2335 return device->enabled;
2336}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002337
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002338status_t EventHub::enableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002339 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002340 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002341 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002342 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2343 return BAD_VALUE;
2344 }
2345 if (device->enabled) {
2346 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
2347 return OK;
2348 }
2349 status_t result = device->enable();
2350 if (result != OK) {
2351 ALOGE("Failed to enable device %" PRId32, deviceId);
2352 return result;
2353 }
2354
Chris Ye989bb932020-07-04 16:18:59 -07002355 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002356
Chris Ye989bb932020-07-04 16:18:59 -07002357 return registerDeviceForEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002358}
2359
2360status_t EventHub::disableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002361 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002362 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002363 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002364 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2365 return BAD_VALUE;
2366 }
2367 if (!device->enabled) {
2368 ALOGW("Duplicate call to %s, input device already disabled", __func__);
2369 return OK;
2370 }
Chris Ye989bb932020-07-04 16:18:59 -07002371 unregisterDeviceFromEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002372 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002373}
2374
2375void EventHub::createVirtualKeyboardLocked() {
2376 InputDeviceIdentifier identifier;
2377 identifier.name = "Virtual";
2378 identifier.uniqueId = "<virtual>";
2379 assignDescriptorLocked(identifier);
2380
Chris Ye989bb932020-07-04 16:18:59 -07002381 std::unique_ptr<Device> device =
2382 std::make_unique<Device>(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
Prabir Pradhancb42b472022-08-23 16:01:19 +00002383 identifier, nullptr /*associatedDevice*/);
Chris Ye1b0c7342020-07-28 21:57:03 -07002384 device->classes = InputDeviceClass::KEYBOARD | InputDeviceClass::ALPHAKEY |
2385 InputDeviceClass::DPAD | InputDeviceClass::VIRTUAL;
Chris Ye989bb932020-07-04 16:18:59 -07002386 device->loadKeyMapLocked();
2387 addDeviceLocked(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002388}
2389
Chris Ye989bb932020-07-04 16:18:59 -07002390void EventHub::addDeviceLocked(std::unique_ptr<Device> device) {
Chris Yed3fef462021-03-07 17:10:08 -08002391 reportDeviceAddedForStatisticsLocked(device->identifier, device->classes);
Chris Ye989bb932020-07-04 16:18:59 -07002392 mOpeningDevices.push_back(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002393}
2394
Chris Ye989bb932020-07-04 16:18:59 -07002395int32_t EventHub::getNextControllerNumberLocked(const std::string& name) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002396 if (mControllerNumbers.isFull()) {
2397 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Chris Ye989bb932020-07-04 16:18:59 -07002398 name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002399 return 0;
2400 }
2401 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
2402 // one
2403 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
2404}
2405
Chris Ye989bb932020-07-04 16:18:59 -07002406void EventHub::releaseControllerNumberLocked(int32_t num) {
2407 if (num > 0) {
2408 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002409 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002410}
2411
Chris Ye8594e192020-07-14 10:34:06 -07002412void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002413 Device* device = getDeviceByPathLocked(devicePath);
Chris Ye989bb932020-07-04 16:18:59 -07002414 if (device != nullptr) {
2415 closeDeviceLocked(*device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002416 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002417 }
Chris Ye8594e192020-07-14 10:34:06 -07002418 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002419}
2420
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002421/**
2422 * Find the video device by filename, and close it.
2423 * The video device is closed by path during an inotify event, where we don't have the
2424 * additional context about the video device fd, or the associated input device.
2425 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002426void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002427 // A video device may be owned by an existing input device, or it may be stored in
2428 // the mUnattachedVideoDevices queue. Check both locations.
Chris Ye989bb932020-07-04 16:18:59 -07002429 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002430 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002431 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002432 device->videoDevice = nullptr;
2433 return;
2434 }
2435 }
Siarhei Vishniakouf47c339e2021-12-30 11:22:26 -08002436 std::erase_if(mUnattachedVideoDevices,
2437 [&devicePath](const std::unique_ptr<TouchVideoDevice>& videoDevice) {
2438 return videoDevice->getPath() == devicePath;
2439 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08002440}
2441
2442void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002443 mUnattachedVideoDevices.clear();
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002444 while (!mDevices.empty()) {
2445 closeDeviceLocked(*(mDevices.begin()->second));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002446 }
2447}
2448
Chris Ye989bb932020-07-04 16:18:59 -07002449void EventHub::closeDeviceLocked(Device& device) {
2450 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=%s", device.path.c_str(),
2451 device.identifier.name.c_str(), device.id, device.fd, device.classes.string().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002452
Chris Ye989bb932020-07-04 16:18:59 -07002453 if (device.id == mBuiltInKeyboardId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002454 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Chris Ye989bb932020-07-04 16:18:59 -07002455 device.path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002456 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
2457 }
2458
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002459 unregisterDeviceFromEpollLocked(device);
Chris Ye989bb932020-07-04 16:18:59 -07002460 if (device.videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002461 // This must be done after the video device is removed from epoll
Chris Ye989bb932020-07-04 16:18:59 -07002462 mUnattachedVideoDevices.push_back(std::move(device.videoDevice));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002463 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002464
Chris Ye989bb932020-07-04 16:18:59 -07002465 releaseControllerNumberLocked(device.controllerNumber);
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002466 device.controllerNumber = 0;
Chris Ye989bb932020-07-04 16:18:59 -07002467 device.close();
Chris Ye989bb932020-07-04 16:18:59 -07002468 mClosingDevices.push_back(std::move(mDevices[device.id]));
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002469
Chris Ye989bb932020-07-04 16:18:59 -07002470 mDevices.erase(device.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002471}
2472
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002473base::Result<void> EventHub::readNotifyLocked() {
2474 static constexpr auto EVENT_SIZE = static_cast<ssize_t>(sizeof(inotify_event));
2475 uint8_t eventBuffer[512];
2476 ssize_t sizeRead;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002477
2478 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002479 do {
2480 sizeRead = read(mINotifyFd, eventBuffer, sizeof(eventBuffer));
2481 } while (sizeRead < 0 && errno == EINTR);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002482
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002483 if (sizeRead < EVENT_SIZE) return Errorf("could not get event, %s", strerror(errno));
2484
2485 for (ssize_t eventPos = 0; sizeRead >= EVENT_SIZE;) {
2486 const inotify_event* event;
2487 event = (const inotify_event*)(eventBuffer + eventPos);
2488 if (event->len == 0) continue;
2489
2490 handleNotifyEventLocked(*event);
2491
2492 const ssize_t eventSize = EVENT_SIZE + event->len;
2493 sizeRead -= eventSize;
2494 eventPos += eventSize;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002495 }
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002496 return {};
2497}
2498
2499void EventHub::handleNotifyEventLocked(const inotify_event& event) {
2500 if (event.wd == mDeviceInputWd) {
2501 std::string filename = std::string(DEVICE_INPUT_PATH) + "/" + event.name;
2502 if (event.mask & IN_CREATE) {
2503 openDeviceLocked(filename);
2504 } else {
2505 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
2506 closeDeviceByPathLocked(filename);
2507 }
2508 } else if (event.wd == mDeviceWd) {
2509 if (isV4lTouchNode(event.name)) {
2510 std::string filename = std::string(DEVICE_PATH) + "/" + event.name;
2511 if (event.mask & IN_CREATE) {
2512 openVideoDeviceLocked(filename);
2513 } else {
2514 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
2515 closeVideoDeviceByPathLocked(filename);
2516 }
2517 } else if (strcmp(event.name, "input") == 0 && event.mask & IN_CREATE) {
2518 addDeviceInputInotify();
2519 }
2520 } else {
2521 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event.wd);
2522 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002523}
2524
Chris Ye8594e192020-07-14 10:34:06 -07002525status_t EventHub::scanDirLocked(const std::string& dirname) {
2526 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2527 openDeviceLocked(entry.path());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002528 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002529 return 0;
2530}
2531
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002532/**
2533 * Look for all dirname/v4l-touch* devices, and open them.
2534 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002535status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Chris Ye8594e192020-07-14 10:34:06 -07002536 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2537 if (isV4lTouchNode(entry.path())) {
2538 ALOGI("Found touch video device %s", entry.path().c_str());
2539 openVideoDeviceLocked(entry.path());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002540 }
2541 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002542 return OK;
2543}
2544
Michael Wrightd02c5b62014-02-10 15:10:22 -08002545void EventHub::requestReopenDevices() {
2546 ALOGV("requestReopenDevices() called");
2547
Chris Ye87143712020-11-10 05:05:58 +00002548 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002549 mNeedToReopenDevices = true;
2550}
2551
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002552void EventHub::dump(std::string& dump) const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002553 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002554
2555 { // acquire lock
Chris Ye87143712020-11-10 05:05:58 +00002556 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002557
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002558 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002559
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002560 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002561
Chris Ye989bb932020-07-04 16:18:59 -07002562 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002563 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002564 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002565 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002566 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002567 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002568 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002569 }
Chris Ye1b0c7342020-07-28 21:57:03 -07002570 dump += StringPrintf(INDENT3 "Classes: %s\n", device->classes.string().c_str());
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002571 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002572 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002573 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
2574 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002575 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002576 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002577 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002578 "product=0x%04x, version=0x%04x\n",
2579 device->identifier.bus, device->identifier.vendor,
2580 device->identifier.product, device->identifier.version);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002581 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002582 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002583 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002584 device->keyMap.keyCharacterMapFile.c_str());
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00002585 dump += StringPrintf(INDENT3 "CountryCode: %d\n",
2586 device->associatedDevice ? device->associatedDevice->countryCode
2587 : InputDeviceCountryCode::INVALID);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002588 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002589 device->configurationFile.c_str());
Prabir Pradhan51894782022-08-23 16:29:10 +00002590 dump += StringPrintf(INDENT3 "VideoDevice: %s\n",
2591 device->videoDevice ? device->videoDevice->dump().c_str()
2592 : "<none>");
2593 dump += StringPrintf(INDENT3 "SysfsDevicePath: %s\n",
2594 device->associatedDevice
2595 ? device->associatedDevice->sysfsRootPath.c_str()
2596 : "<none>");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002597 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002598
2599 dump += INDENT "Unattached video devices:\n";
2600 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
2601 dump += INDENT2 + videoDevice->dump() + "\n";
2602 }
2603 if (mUnattachedVideoDevices.empty()) {
2604 dump += INDENT2 "<none>\n";
2605 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002606 } // release lock
2607}
2608
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002609void EventHub::monitor() const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002610 // Acquire and release the lock to ensure that the event hub has not deadlocked.
Chris Ye1c2e0892020-11-30 21:41:44 -08002611 std::unique_lock<std::mutex> lock(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002612}
2613
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002614} // namespace android