blob: 2f594d649b9ca4f6971971c51b7a55d109d2c294 [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;
64
Michael Wrightd02c5b62014-02-10 15:10:22 -080065namespace android {
66
Dominik Laskowski2f01d772022-03-23 16:01:29 -070067using namespace ftl::flag_operators;
68
Usama Arifb27c8e62021-06-03 16:44:09 +010069static const char* DEVICE_INPUT_PATH = "/dev/input";
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080070// v4l2 devices go directly into /dev
Usama Arifb27c8e62021-06-03 16:44:09 +010071static const char* DEVICE_PATH = "/dev";
Michael Wrightd02c5b62014-02-10 15:10:22 -080072
Chris Ye657c2f02021-05-25 16:24:37 -070073static constexpr size_t OBFUSCATED_LENGTH = 8;
74
Chris Ye87143712020-11-10 05:05:58 +000075static constexpr int32_t FF_STRONG_MAGNITUDE_CHANNEL_IDX = 0;
76static constexpr int32_t FF_WEAK_MAGNITUDE_CHANNEL_IDX = 1;
Chris Ye6393a262020-08-04 19:41:36 -070077
Chris Yee2b1e5c2021-03-10 22:45:12 -080078// Mapping for input battery class node IDs lookup.
79// https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
80static const std::unordered_map<std::string, InputBatteryClass> BATTERY_CLASSES =
81 {{"capacity", InputBatteryClass::CAPACITY},
82 {"capacity_level", InputBatteryClass::CAPACITY_LEVEL},
83 {"status", InputBatteryClass::STATUS}};
84
85// Mapping for input battery class node names lookup.
86// https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
87static const std::unordered_map<InputBatteryClass, std::string> BATTERY_NODES =
88 {{InputBatteryClass::CAPACITY, "capacity"},
89 {InputBatteryClass::CAPACITY_LEVEL, "capacity_level"},
90 {InputBatteryClass::STATUS, "status"}};
91
Kim Low03ea0352020-11-06 12:45:07 -080092// must be kept in sync with definitions in kernel /drivers/power/supply/power_supply_sysfs.c
93static const std::unordered_map<std::string, int32_t> BATTERY_STATUS =
94 {{"Unknown", BATTERY_STATUS_UNKNOWN},
95 {"Charging", BATTERY_STATUS_CHARGING},
96 {"Discharging", BATTERY_STATUS_DISCHARGING},
97 {"Not charging", BATTERY_STATUS_NOT_CHARGING},
98 {"Full", BATTERY_STATUS_FULL}};
99
100// Mapping taken from
101// https://gitlab.freedesktop.org/upower/upower/-/blob/master/src/linux/up-device-supply.c#L484
102static const std::unordered_map<std::string, int32_t> BATTERY_LEVEL = {{"Critical", 5},
103 {"Low", 10},
104 {"Normal", 55},
105 {"High", 70},
106 {"Full", 100},
107 {"Unknown", 50}};
108
Chris Ye3fdbfef2021-01-06 18:45:18 -0800109// Mapping for input led class node names lookup.
110// https://www.kernel.org/doc/html/latest/leds/leds-class.html
111static const std::unordered_map<std::string, InputLightClass> LIGHT_CLASSES =
112 {{"red", InputLightClass::RED},
113 {"green", InputLightClass::GREEN},
114 {"blue", InputLightClass::BLUE},
115 {"global", InputLightClass::GLOBAL},
116 {"brightness", InputLightClass::BRIGHTNESS},
117 {"multi_index", InputLightClass::MULTI_INDEX},
118 {"multi_intensity", InputLightClass::MULTI_INTENSITY},
119 {"max_brightness", InputLightClass::MAX_BRIGHTNESS}};
120
121// Mapping for input multicolor led class node names.
122// https://www.kernel.org/doc/html/latest/leds/leds-class-multicolor.html
123static const std::unordered_map<InputLightClass, std::string> LIGHT_NODES =
124 {{InputLightClass::BRIGHTNESS, "brightness"},
125 {InputLightClass::MULTI_INDEX, "multi_index"},
126 {InputLightClass::MULTI_INTENSITY, "multi_intensity"}};
127
128// Mapping for light color name and the light color
129const std::unordered_map<std::string, LightColor> LIGHT_COLORS = {{"red", LightColor::RED},
130 {"green", LightColor::GREEN},
131 {"blue", LightColor::BLUE}};
132
Michael Wrightd02c5b62014-02-10 15:10:22 -0800133static inline const char* toString(bool value) {
134 return value ? "true" : "false";
135}
136
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100137static std::string sha1(const std::string& in) {
Dan Albert677d87e2014-06-16 17:31:28 -0700138 SHA_CTX ctx;
139 SHA1_Init(&ctx);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100140 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
Dan Albert677d87e2014-06-16 17:31:28 -0700141 u_char digest[SHA_DIGEST_LENGTH];
142 SHA1_Final(digest, &ctx);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800143
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100144 std::string out;
Dan Albert677d87e2014-06-16 17:31:28 -0700145 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100146 out += StringPrintf("%02x", digest[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800147 }
148 return out;
149}
150
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800151/**
152 * Return true if name matches "v4l-touch*"
153 */
Chris Ye8594e192020-07-14 10:34:06 -0700154static bool isV4lTouchNode(std::string name) {
155 return name.find("v4l-touch") != std::string::npos;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800156}
157
Philip Quinn39b81682019-01-09 22:20:39 -0800158/**
159 * Returns true if V4L devices should be scanned.
160 *
161 * The system property ro.input.video_enabled can be used to control whether
162 * EventHub scans and opens V4L devices. As V4L does not support multiple
163 * clients, EventHub effectively blocks access to these devices when it opens
Siarhei Vishniakou29f88492019-04-05 14:11:43 -0700164 * them.
165 *
166 * Setting this to "false" would prevent any video devices from being discovered and
167 * associated with input devices.
168 *
169 * This property can be used as follows:
170 * 1. To turn off features that are dependent on video device presence.
171 * 2. During testing and development, to allow other clients to read video devices
172 * directly from /dev.
Philip Quinn39b81682019-01-09 22:20:39 -0800173 */
174static bool isV4lScanningEnabled() {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700175 return property_get_bool("ro.input.video_enabled", true /* default_value */);
Philip Quinn39b81682019-01-09 22:20:39 -0800176}
177
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800178static nsecs_t processEventTimestamp(const struct input_event& event) {
179 // Use the time specified in the event instead of the current time
180 // so that downstream code can get more accurate estimates of
181 // event dispatch latency from the time the event is enqueued onto
182 // the evdev client buffer.
183 //
184 // The event's timestamp fortuitously uses the same monotonic clock
185 // time base as the rest of Android. The kernel event device driver
186 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
187 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
188 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
189 // system call that also queries ktime_get_ts().
190
191 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.time.tv_sec) +
192 microseconds_to_nanoseconds(event.time.tv_usec);
193 return inputEventTime;
194}
195
Kim Low03ea0352020-11-06 12:45:07 -0800196/**
Prabir Pradhancb42b472022-08-23 16:01:19 +0000197 * Returns the sysfs root path of the input device.
Kim Low03ea0352020-11-06 12:45:07 -0800198 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800199static std::optional<std::filesystem::path> getSysfsRootPath(const char* devicePath) {
Kim Low03ea0352020-11-06 12:45:07 -0800200 std::error_code errorCode;
201
202 // Stat the device path to get the major and minor number of the character file
203 struct stat statbuf;
204 if (stat(devicePath, &statbuf) == -1) {
205 ALOGE("Could not stat device %s due to error: %s.", devicePath, std::strerror(errno));
Chris Ye3fdbfef2021-01-06 18:45:18 -0800206 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800207 }
208
209 unsigned int major_num = major(statbuf.st_rdev);
210 unsigned int minor_num = minor(statbuf.st_rdev);
211
212 // Realpath "/sys/dev/char/{major}:{minor}" to get the sysfs path to the input event
213 auto sysfsPath = std::filesystem::path("/sys/dev/char/");
214 sysfsPath /= std::to_string(major_num) + ":" + std::to_string(minor_num);
215 sysfsPath = std::filesystem::canonical(sysfsPath, errorCode);
216
217 // Make sure nothing went wrong in call to canonical()
218 if (errorCode) {
219 ALOGW("Could not run filesystem::canonical() due to error %d : %s.", errorCode.value(),
220 errorCode.message().c_str());
Chris Ye3fdbfef2021-01-06 18:45:18 -0800221 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800222 }
223
224 // Continue to go up a directory until we reach a directory named "input"
225 while (sysfsPath != "/" && sysfsPath.filename() != "input") {
226 sysfsPath = sysfsPath.parent_path();
227 }
228
229 // Then go up one more and you will be at the sysfs root of the device
230 sysfsPath = sysfsPath.parent_path();
231
232 // Make sure we didn't reach root path and that directory actually exists
233 if (sysfsPath == "/" || !std::filesystem::exists(sysfsPath, errorCode)) {
234 if (errorCode) {
235 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
236 errorCode.message().c_str());
237 }
238
239 // Not found
Chris Ye3fdbfef2021-01-06 18:45:18 -0800240 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800241 }
242
243 return sysfsPath;
244}
245
246/**
Chris Ye3fdbfef2021-01-06 18:45:18 -0800247 * Returns the list of files under a specified path.
Kim Low03ea0352020-11-06 12:45:07 -0800248 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800249static std::vector<std::filesystem::path> allFilesInPath(const std::filesystem::path& path) {
250 std::vector<std::filesystem::path> nodes;
251 std::error_code errorCode;
252 auto iter = std::filesystem::directory_iterator(path, errorCode);
253 while (!errorCode && iter != std::filesystem::directory_iterator()) {
254 nodes.push_back(iter->path());
255 iter++;
256 }
257 return nodes;
258}
259
260/**
261 * Returns the list of files under a specified directory in a sysfs path.
262 * Example:
263 * findSysfsNodes(sysfsRootPath, SysfsClass::LEDS) will return all led nodes under "leds" directory
264 * in the sysfs path.
265 */
266static std::vector<std::filesystem::path> findSysfsNodes(const std::filesystem::path& sysfsRoot,
267 SysfsClass clazz) {
Dominik Laskowski75788452021-02-09 18:51:25 -0800268 std::string nodeStr = ftl::enum_string(clazz);
Chris Ye3fdbfef2021-01-06 18:45:18 -0800269 std::for_each(nodeStr.begin(), nodeStr.end(),
270 [](char& c) { c = std::tolower(static_cast<unsigned char>(c)); });
271 std::vector<std::filesystem::path> nodes;
272 for (auto path = sysfsRoot; path != "/" && nodes.empty(); path = path.parent_path()) {
273 nodes = allFilesInPath(path / nodeStr);
274 }
275 return nodes;
276}
277
278static std::optional<std::array<LightColor, COLOR_NUM>> getColorIndexArray(
279 std::filesystem::path path) {
280 std::string indexStr;
281 if (!base::ReadFileToString(path, &indexStr)) {
282 return std::nullopt;
283 }
284
285 // Parse the multi color LED index file, refer to kernel docs
286 // leds/leds-class-multicolor.html
287 std::regex indexPattern("(red|green|blue)\\s(red|green|blue)\\s(red|green|blue)[\\n]");
288 std::smatch results;
289 std::array<LightColor, COLOR_NUM> colors;
290 if (!std::regex_match(indexStr, results, indexPattern)) {
291 return std::nullopt;
292 }
293
294 for (size_t i = 1; i < results.size(); i++) {
295 const auto it = LIGHT_COLORS.find(results[i].str());
296 if (it != LIGHT_COLORS.end()) {
297 // intensities.emplace(it->second, 0);
298 colors[i - 1] = it->second;
Kim Low03ea0352020-11-06 12:45:07 -0800299 }
300 }
Chris Ye3fdbfef2021-01-06 18:45:18 -0800301 return colors;
Kim Low03ea0352020-11-06 12:45:07 -0800302}
303
Prabir Pradhancb42b472022-08-23 16:01:19 +0000304/**
305 * Read information about batteries exposed through the sysfs path.
306 */
307static std::unordered_map<int32_t /*batteryId*/, RawBatteryInfo> readBatteryConfiguration(
308 const std::filesystem::path& sysfsRootPath) {
309 std::unordered_map<int32_t, RawBatteryInfo> batteryInfos;
310 int32_t nextBatteryId = 0;
311 // Check if device has any battery.
312 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::POWER_SUPPLY);
313 for (const auto& nodePath : paths) {
314 RawBatteryInfo info;
315 info.id = ++nextBatteryId;
316 info.path = nodePath;
317 info.name = nodePath.filename();
318
319 // Scan the path for all the files
320 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
321 const auto& files = allFilesInPath(nodePath);
322 for (const auto& file : files) {
323 const auto it = BATTERY_CLASSES.find(file.filename().string());
324 if (it != BATTERY_CLASSES.end()) {
325 info.flags |= it->second;
326 }
327 }
328 batteryInfos.insert_or_assign(info.id, info);
329 ALOGD("configureBatteryLocked rawBatteryId %d name %s", info.id, info.name.c_str());
330 }
331 return batteryInfos;
332}
333
334/**
335 * Read information about lights exposed through the sysfs path.
336 */
337static std::unordered_map<int32_t /*lightId*/, RawLightInfo> readLightsConfiguration(
338 const std::filesystem::path& sysfsRootPath) {
339 std::unordered_map<int32_t, RawLightInfo> lightInfos;
340 int32_t nextLightId = 0;
341 // Check if device has any lights.
342 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::LEDS);
343 for (const auto& nodePath : paths) {
344 RawLightInfo info;
345 info.id = ++nextLightId;
346 info.path = nodePath;
347 info.name = nodePath.filename();
348 info.maxBrightness = std::nullopt;
349 size_t nameStart = info.name.rfind(":");
350 if (nameStart != std::string::npos) {
351 // Trim the name to color name
352 info.name = info.name.substr(nameStart + 1);
353 // Set InputLightClass flag for colors
354 const auto it = LIGHT_CLASSES.find(info.name);
355 if (it != LIGHT_CLASSES.end()) {
356 info.flags |= it->second;
357 }
358 }
359 // Scan the path for all the files
360 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
361 const auto& files = allFilesInPath(nodePath);
362 for (const auto& file : files) {
363 const auto it = LIGHT_CLASSES.find(file.filename().string());
364 if (it != LIGHT_CLASSES.end()) {
365 info.flags |= it->second;
366 // If the node has maximum brightness, read it
367 if (it->second == InputLightClass::MAX_BRIGHTNESS) {
368 std::string str;
369 if (base::ReadFileToString(file, &str)) {
370 info.maxBrightness = std::stoi(str);
371 }
372 }
373 }
374 }
375 lightInfos.insert_or_assign(info.id, info);
376 ALOGD("configureLightsLocked rawLightId %d name %s", info.id, info.name.c_str());
377 }
378 return lightInfos;
379}
380
Michael Wrightd02c5b62014-02-10 15:10:22 -0800381// --- Global Functions ---
382
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700383ftl::Flags<InputDeviceClass> getAbsAxisUsage(int32_t axis,
384 ftl::Flags<InputDeviceClass> deviceClasses) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800385 // Touch devices get dibs on touch-related axes.
Chris Ye1b0c7342020-07-28 21:57:03 -0700386 if (deviceClasses.test(InputDeviceClass::TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800387 switch (axis) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700388 case ABS_X:
389 case ABS_Y:
390 case ABS_PRESSURE:
391 case ABS_TOOL_WIDTH:
392 case ABS_DISTANCE:
393 case ABS_TILT_X:
394 case ABS_TILT_Y:
395 case ABS_MT_SLOT:
396 case ABS_MT_TOUCH_MAJOR:
397 case ABS_MT_TOUCH_MINOR:
398 case ABS_MT_WIDTH_MAJOR:
399 case ABS_MT_WIDTH_MINOR:
400 case ABS_MT_ORIENTATION:
401 case ABS_MT_POSITION_X:
402 case ABS_MT_POSITION_Y:
403 case ABS_MT_TOOL_TYPE:
404 case ABS_MT_BLOB_ID:
405 case ABS_MT_TRACKING_ID:
406 case ABS_MT_PRESSURE:
407 case ABS_MT_DISTANCE:
Chris Ye1b0c7342020-07-28 21:57:03 -0700408 return InputDeviceClass::TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800409 }
410 }
411
Chris Yef59a2f42020-10-16 12:55:26 -0700412 if (deviceClasses.test(InputDeviceClass::SENSOR)) {
413 switch (axis) {
414 case ABS_X:
415 case ABS_Y:
416 case ABS_Z:
417 case ABS_RX:
418 case ABS_RY:
419 case ABS_RZ:
420 return InputDeviceClass::SENSOR;
421 }
422 }
423
Michael Wright842500e2015-03-13 17:32:02 -0700424 // External stylus gets the pressure axis
Chris Ye1b0c7342020-07-28 21:57:03 -0700425 if (deviceClasses.test(InputDeviceClass::EXTERNAL_STYLUS)) {
Michael Wright842500e2015-03-13 17:32:02 -0700426 if (axis == ABS_PRESSURE) {
Chris Ye1b0c7342020-07-28 21:57:03 -0700427 return InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -0700428 }
429 }
430
Michael Wrightd02c5b62014-02-10 15:10:22 -0800431 // Joystick devices get the rest.
Chris Ye1b0c7342020-07-28 21:57:03 -0700432 return deviceClasses & InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800433}
434
435// --- EventHub::Device ---
436
Prabir Pradhancb42b472022-08-23 16:01:19 +0000437EventHub::Device::Device(int fd, int32_t id, std::string path, InputDeviceIdentifier identifier,
438 std::shared_ptr<const AssociatedDevice> assocDev)
Chris Ye989bb932020-07-04 16:18:59 -0700439 : fd(fd),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700440 id(id),
Prabir Pradhancb42b472022-08-23 16:01:19 +0000441 path(std::move(path)),
442 identifier(std::move(identifier)),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700443 classes(0),
444 configuration(nullptr),
445 virtualKeyMap(nullptr),
446 ffEffectPlaying(false),
447 ffEffectId(-1),
Prabir Pradhancb42b472022-08-23 16:01:19 +0000448 associatedDevice(std::move(assocDev)),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700449 controllerNumber(0),
450 enabled(true),
Chris Ye66fbac32020-07-06 20:36:43 -0700451 isVirtual(fd < 0) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800452
453EventHub::Device::~Device() {
454 close();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800455}
456
457void EventHub::Device::close() {
458 if (fd >= 0) {
459 ::close(fd);
460 fd = -1;
461 }
462}
463
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700464status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100465 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700466 if (fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100467 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700468 return -errno;
469 }
470 enabled = true;
471 return OK;
472}
473
474status_t EventHub::Device::disable() {
475 close();
476 enabled = false;
477 return OK;
478}
479
Chris Ye989bb932020-07-04 16:18:59 -0700480bool EventHub::Device::hasValidFd() const {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700481 return !isVirtual && enabled;
482}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800483
Chris Ye3a1e4462020-08-12 10:13:15 -0700484const std::shared_ptr<KeyCharacterMap> EventHub::Device::getKeyCharacterMap() const {
Chris Ye989bb932020-07-04 16:18:59 -0700485 return keyMap.keyCharacterMap;
486}
487
488template <std::size_t N>
489status_t EventHub::Device::readDeviceBitMask(unsigned long ioctlCode, BitArray<N>& bitArray) {
490 if (!hasValidFd()) {
491 return BAD_VALUE;
492 }
493 if ((_IOC_SIZE(ioctlCode) == 0)) {
494 ioctlCode |= _IOC(0, 0, 0, bitArray.bytes());
495 }
496
497 typename BitArray<N>::Buffer buffer;
498 status_t ret = ioctl(fd, ioctlCode, buffer.data());
499 bitArray.loadFromBuffer(buffer);
500 return ret;
501}
502
503void EventHub::Device::configureFd() {
504 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
505 if (classes.test(InputDeviceClass::KEYBOARD)) {
506 // Disable kernel key repeat since we handle it ourselves
507 unsigned int repeatRate[] = {0, 0};
508 if (ioctl(fd, EVIOCSREP, repeatRate)) {
509 ALOGW("Unable to disable kernel key repeat for %s: %s", path.c_str(), strerror(errno));
510 }
511 }
512
513 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
514 // associated with input events. This is important because the input system
515 // uses the timestamps extensively and assumes they were recorded using the monotonic
516 // clock.
517 int clockId = CLOCK_MONOTONIC;
Chris Yef59a2f42020-10-16 12:55:26 -0700518 if (classes.test(InputDeviceClass::SENSOR)) {
519 // Each new sensor event should use the same time base as
520 // SystemClock.elapsedRealtimeNanos().
521 clockId = CLOCK_BOOTTIME;
522 }
Chris Ye989bb932020-07-04 16:18:59 -0700523 bool usingClockIoctl = !ioctl(fd, EVIOCSCLOCKID, &clockId);
524 ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
525}
526
527bool EventHub::Device::hasKeycodeLocked(int keycode) const {
528 if (!keyMap.haveKeyLayout()) {
529 return false;
530 }
531
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700532 std::vector<int32_t> scanCodes = keyMap.keyLayoutMap->findScanCodesForKey(keycode);
Chris Ye989bb932020-07-04 16:18:59 -0700533 const size_t N = scanCodes.size();
534 for (size_t i = 0; i < N && i <= KEY_MAX; i++) {
535 int32_t sc = scanCodes[i];
536 if (sc >= 0 && sc <= KEY_MAX && keyBitmask.test(sc)) {
537 return true;
538 }
539 }
540
541 return false;
542}
543
544void EventHub::Device::loadConfigurationLocked() {
545 configurationFile =
546 getInputDeviceConfigurationFilePathByDeviceIdentifier(identifier,
547 InputDeviceConfigurationFileType::
548 CONFIGURATION);
549 if (configurationFile.empty()) {
550 ALOGD("No input device configuration file found for device '%s'.", identifier.name.c_str());
551 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500552 android::base::Result<std::unique_ptr<PropertyMap>> propertyMap =
553 PropertyMap::load(configurationFile.c_str());
554 if (!propertyMap.ok()) {
Chris Ye989bb932020-07-04 16:18:59 -0700555 ALOGE("Error loading input device configuration file for device '%s'. "
556 "Using default configuration.",
557 identifier.name.c_str());
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500558 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500559 configuration = std::move(*propertyMap);
Chris Ye989bb932020-07-04 16:18:59 -0700560 }
561 }
562}
563
564bool EventHub::Device::loadVirtualKeyMapLocked() {
565 // The virtual key map is supplied by the kernel as a system board property file.
566 std::string propPath = "/sys/board_properties/virtualkeys.";
567 propPath += identifier.getCanonicalName();
568 if (access(propPath.c_str(), R_OK)) {
569 return false;
570 }
571 virtualKeyMap = VirtualKeyMap::load(propPath);
572 return virtualKeyMap != nullptr;
573}
574
575status_t EventHub::Device::loadKeyMapLocked() {
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500576 return keyMap.load(identifier, configuration.get());
Chris Ye989bb932020-07-04 16:18:59 -0700577}
578
579bool EventHub::Device::isExternalDeviceLocked() {
580 if (configuration) {
581 bool value;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700582 if (configuration->tryGetProperty("device.internal", value)) {
Chris Ye989bb932020-07-04 16:18:59 -0700583 return !value;
584 }
585 }
586 return identifier.bus == BUS_USB || identifier.bus == BUS_BLUETOOTH;
587}
588
589bool EventHub::Device::deviceHasMicLocked() {
590 if (configuration) {
591 bool value;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700592 if (configuration->tryGetProperty("audio.mic", value)) {
Chris Ye989bb932020-07-04 16:18:59 -0700593 return value;
594 }
595 }
596 return false;
597}
598
599void EventHub::Device::setLedStateLocked(int32_t led, bool on) {
600 int32_t sc;
601 if (hasValidFd() && mapLed(led, &sc) != NAME_NOT_FOUND) {
602 struct input_event ev;
603 ev.time.tv_sec = 0;
604 ev.time.tv_usec = 0;
605 ev.type = EV_LED;
606 ev.code = sc;
607 ev.value = on ? 1 : 0;
608
609 ssize_t nWrite;
610 do {
611 nWrite = write(fd, &ev, sizeof(struct input_event));
612 } while (nWrite == -1 && errno == EINTR);
613 }
614}
615
616void EventHub::Device::setLedForControllerLocked() {
617 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
618 setLedStateLocked(ALED_CONTROLLER_1 + i, controllerNumber == i + 1);
619 }
620}
621
622status_t EventHub::Device::mapLed(int32_t led, int32_t* outScanCode) const {
623 if (!keyMap.haveKeyLayout()) {
624 return NAME_NOT_FOUND;
625 }
626
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700627 std::optional<int32_t> scanCode = keyMap.keyLayoutMap->findScanCodeForLed(led);
628 if (scanCode.has_value()) {
629 if (*scanCode >= 0 && *scanCode <= LED_MAX && ledBitmask.test(*scanCode)) {
630 *outScanCode = *scanCode;
Chris Ye989bb932020-07-04 16:18:59 -0700631 return NO_ERROR;
632 }
633 }
634 return NAME_NOT_FOUND;
635}
636
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100637/**
638 * Get the capabilities for the current process.
639 * Crashes the system if unable to create / check / destroy the capabilities object.
640 */
641class Capabilities final {
642public:
643 explicit Capabilities() {
644 mCaps = cap_get_proc();
645 LOG_ALWAYS_FATAL_IF(mCaps == nullptr, "Could not get capabilities of the current process");
646 }
647
648 /**
649 * Check whether the current process has a specific capability
650 * in the set of effective capabilities.
651 * Return CAP_SET if the process has the requested capability
652 * Return CAP_CLEAR otherwise.
653 */
654 cap_flag_value_t checkEffectiveCapability(cap_value_t capability) {
655 cap_flag_value_t value;
656 const int result = cap_get_flag(mCaps, capability, CAP_EFFECTIVE, &value);
657 LOG_ALWAYS_FATAL_IF(result == -1, "Could not obtain the requested capability");
658 return value;
659 }
660
661 ~Capabilities() {
662 const int result = cap_free(mCaps);
663 LOG_ALWAYS_FATAL_IF(result == -1, "Could not release the capabilities structure");
664 }
665
666private:
667 cap_t mCaps;
668};
669
670static void ensureProcessCanBlockSuspend() {
671 Capabilities capabilities;
672 const bool canBlockSuspend =
673 capabilities.checkEffectiveCapability(CAP_BLOCK_SUSPEND) == CAP_SET;
674 LOG_ALWAYS_FATAL_IF(!canBlockSuspend,
675 "Input must be able to block suspend to properly process events");
676}
677
Michael Wrightd02c5b62014-02-10 15:10:22 -0800678// --- EventHub ---
679
Michael Wrightd02c5b62014-02-10 15:10:22 -0800680const int EventHub::EPOLL_MAX_EVENTS;
681
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700682EventHub::EventHub(void)
683 : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
684 mNextDeviceId(1),
685 mControllerNumbers(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800686 mNeedToSendFinishedDeviceScan(false),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700687 mNeedToReopenDevices(false),
688 mNeedToScanDevices(true),
689 mPendingEventCount(0),
690 mPendingEventIndex(0),
691 mPendingINotify(false) {
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100692 ensureProcessCanBlockSuspend();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800693
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800694 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800695 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800696
Michael Wright8e9a8562022-02-09 13:44:29 +0000697 mINotifyFd = inotify_init1(IN_CLOEXEC);
Prabir Pradhan952e65b2022-06-23 17:49:55 +0000698 LOG_ALWAYS_FATAL_IF(mINotifyFd < 0, "Could not create inotify instance: %s", strerror(errno));
Usama Arifb27c8e62021-06-03 16:44:09 +0100699
700 std::error_code errorCode;
701 bool isDeviceInotifyAdded = false;
702 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
703 addDeviceInputInotify();
Philip Quinn39b81682019-01-09 22:20:39 -0800704 } else {
Usama Arifb27c8e62021-06-03 16:44:09 +0100705 addDeviceInotify();
706 isDeviceInotifyAdded = true;
707 if (errorCode) {
708 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
709 errorCode.message().c_str());
710 }
711 }
712
713 if (isV4lScanningEnabled() && !isDeviceInotifyAdded) {
714 addDeviceInotify();
715 } else {
Philip Quinn39b81682019-01-09 22:20:39 -0800716 ALOGI("Video device scanning disabled");
717 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800718
Siarhei Vishniakou2d0e9482019-09-24 12:52:47 +0100719 struct epoll_event eventItem = {};
720 eventItem.events = EPOLLIN | EPOLLWAKEUP;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700721 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800722 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800723 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
724
725 int wakeFds[2];
Michael Wright8e9a8562022-02-09 13:44:29 +0000726 result = pipe2(wakeFds, O_CLOEXEC);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800727 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
728
729 mWakeReadPipeFd = wakeFds[0];
730 mWakeWritePipeFd = wakeFds[1];
731
732 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
733 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700734 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800735
736 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
737 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700738 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800739
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700740 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800741 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
742 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700743 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800744}
745
746EventHub::~EventHub(void) {
747 closeAllDevicesLocked();
748
Michael Wrightd02c5b62014-02-10 15:10:22 -0800749 ::close(mEpollFd);
750 ::close(mINotifyFd);
751 ::close(mWakeReadPipeFd);
752 ::close(mWakeWritePipeFd);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800753}
754
Usama Arifb27c8e62021-06-03 16:44:09 +0100755/**
756 * On devices that don't have any input devices (like some development boards), the /dev/input
757 * directory will be absent. However, the user may still plug in an input device at a later time.
758 * Add watch for contents of /dev/input only when /dev/input appears.
759 */
760void EventHub::addDeviceInputInotify() {
761 mDeviceInputWd = inotify_add_watch(mINotifyFd, DEVICE_INPUT_PATH, IN_DELETE | IN_CREATE);
762 LOG_ALWAYS_FATAL_IF(mDeviceInputWd < 0, "Could not register INotify for %s: %s",
763 DEVICE_INPUT_PATH, strerror(errno));
764}
765
766void EventHub::addDeviceInotify() {
767 mDeviceWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
768 LOG_ALWAYS_FATAL_IF(mDeviceWd < 0, "Could not register INotify for %s: %s", DEVICE_PATH,
769 strerror(errno));
770}
771
Michael Wrightd02c5b62014-02-10 15:10:22 -0800772InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000773 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800774 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700775 return device != nullptr ? device->identifier : InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800776}
777
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700778ftl::Flags<InputDeviceClass> EventHub::getDeviceClasses(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000779 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800780 Device* device = getDeviceLocked(deviceId);
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700781 return device != nullptr ? device->classes : ftl::Flags<InputDeviceClass>(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800782}
783
784int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000785 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800786 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700787 return device != nullptr ? device->controllerNumber : 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788}
789
790void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
Chris Ye87143712020-11-10 05:05:58 +0000791 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800792 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700793 if (device != nullptr && device->configuration) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800794 *outConfiguration = *device->configuration;
795 } else {
796 outConfiguration->clear();
797 }
798}
799
800status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700801 RawAbsoluteAxisInfo* outAxisInfo) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800802 outAxisInfo->clear();
803
804 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000805 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800806
807 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700808 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800809 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700810 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
811 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
812 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800813 return -errno;
814 }
815
816 if (info.minimum != info.maximum) {
817 outAxisInfo->valid = true;
818 outAxisInfo->minValue = info.minimum;
819 outAxisInfo->maxValue = info.maximum;
820 outAxisInfo->flat = info.flat;
821 outAxisInfo->fuzz = info.fuzz;
822 outAxisInfo->resolution = info.resolution;
823 }
824 return OK;
825 }
826 }
827 return -1;
828}
829
830bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
831 if (axis >= 0 && axis <= REL_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000832 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800833 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700834 return device != nullptr ? device->relBitmask.test(axis) : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800835 }
836 return false;
837}
838
839bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
Chris Ye87143712020-11-10 05:05:58 +0000840 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800841
Chris Ye989bb932020-07-04 16:18:59 -0700842 Device* device = getDeviceLocked(deviceId);
843 return property >= 0 && property <= INPUT_PROP_MAX && device != nullptr
844 ? device->propBitmask.test(property)
845 : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800846}
847
Chris Yef59a2f42020-10-16 12:55:26 -0700848bool EventHub::hasMscEvent(int32_t deviceId, int mscEvent) const {
849 std::scoped_lock _l(mLock);
850
851 Device* device = getDeviceLocked(deviceId);
852 return mscEvent >= 0 && mscEvent <= MSC_MAX && device != nullptr
853 ? device->mscBitmask.test(mscEvent)
854 : false;
855}
856
Michael Wrightd02c5b62014-02-10 15:10:22 -0800857int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
858 if (scanCode >= 0 && scanCode <= KEY_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000859 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800860
861 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700862 if (device != nullptr && device->hasValidFd() && device->keyBitmask.test(scanCode)) {
863 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
864 return device->keyState.test(scanCode) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800865 }
866 }
867 }
868 return AKEY_STATE_UNKNOWN;
869}
870
871int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
Chris Ye87143712020-11-10 05:05:58 +0000872 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800873
874 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700875 if (device != nullptr && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700876 std::vector<int32_t> scanCodes = device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800877 if (scanCodes.size() != 0) {
Chris Ye66fbac32020-07-06 20:36:43 -0700878 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800879 for (size_t i = 0; i < scanCodes.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800880 int32_t sc = scanCodes[i];
Chris Ye66fbac32020-07-06 20:36:43 -0700881 if (sc >= 0 && sc <= KEY_MAX && device->keyState.test(sc)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800882 return AKEY_STATE_DOWN;
883 }
884 }
885 return AKEY_STATE_UP;
886 }
887 }
888 }
889 return AKEY_STATE_UNKNOWN;
890}
891
Philip Junker4af3b3d2021-12-14 10:36:55 +0100892int32_t EventHub::getKeyCodeForKeyLocation(int32_t deviceId, int32_t locationKeyCode) const {
893 std::scoped_lock _l(mLock);
894
895 Device* device = getDeviceLocked(deviceId);
896 if (device == nullptr || !device->hasValidFd() || device->keyMap.keyCharacterMap == nullptr ||
897 device->keyMap.keyLayoutMap == nullptr) {
898 return AKEYCODE_UNKNOWN;
899 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700900 std::vector<int32_t> scanCodes =
901 device->keyMap.keyLayoutMap->findScanCodesForKey(locationKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +0100902 if (scanCodes.empty()) {
903 ALOGW("Failed to get key code for key location: no scan code maps to key code %d for input"
904 "device %d",
905 locationKeyCode, deviceId);
906 return AKEYCODE_UNKNOWN;
907 }
908 if (scanCodes.size() > 1) {
909 ALOGW("Multiple scan codes map to the same key code %d, returning only the first match",
910 locationKeyCode);
911 }
912 int32_t outKeyCode;
913 status_t mapKeyRes =
914 device->getKeyCharacterMap()->mapKey(scanCodes[0], 0 /*usageCode*/, &outKeyCode);
915 switch (mapKeyRes) {
916 case OK:
917 return outKeyCode;
918 case NAME_NOT_FOUND:
919 // key character map doesn't re-map this scanCode, hence the keyCode remains the same
920 return locationKeyCode;
921 default:
922 ALOGW("Failed to get key code for key location: Key character map returned error %s",
923 statusToString(mapKeyRes).c_str());
924 return AKEYCODE_UNKNOWN;
925 }
926}
927
Michael Wrightd02c5b62014-02-10 15:10:22 -0800928int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
929 if (sw >= 0 && sw <= SW_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000930 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800931
932 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700933 if (device != nullptr && device->hasValidFd() && device->swBitmask.test(sw)) {
934 if (device->readDeviceBitMask(EVIOCGSW(0), device->swState) >= 0) {
935 return device->swState.test(sw) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800936 }
937 }
938 }
939 return AKEY_STATE_UNKNOWN;
940}
941
942status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
943 *outValue = 0;
944
945 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000946 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800947
948 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700949 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800950 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700951 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
952 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
953 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800954 return -errno;
955 }
956
957 *outValue = info.value;
958 return OK;
959 }
960 }
961 return -1;
962}
963
Siarhei Vishniakou74007942022-06-13 13:57:47 -0700964bool EventHub::markSupportedKeyCodes(int32_t deviceId, const std::vector<int32_t>& keyCodes,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700965 uint8_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +0000966 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800967
968 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700969 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -0700970 for (size_t codeIndex = 0; codeIndex < keyCodes.size(); codeIndex++) {
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700971 std::vector<int32_t> scanCodes =
972 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCodes[codeIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800973
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700974 // check the possible scan codes identified by the layout map against the
975 // map of codes actually emitted by the driver
Siarhei Vishniakou74007942022-06-13 13:57:47 -0700976 for (const int32_t scanCode : scanCodes) {
977 if (device->keyBitmask.test(scanCode)) {
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700978 outFlags[codeIndex] = 1;
979 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800980 }
981 }
982 }
983 return true;
984 }
985 return false;
986}
987
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700988status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
989 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +0000990 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800991 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700992 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800993
Chris Ye66fbac32020-07-06 20:36:43 -0700994 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800995 // Check the key character map first.
Chris Ye3a1e4462020-08-12 10:13:15 -0700996 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
997 if (kcm) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800998 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
999 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001000 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001001 }
1002 }
1003
1004 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001005 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -08001006 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001007 status = NO_ERROR;
1008 }
1009 }
1010
1011 if (status == NO_ERROR) {
Chris Ye3a1e4462020-08-12 10:13:15 -07001012 if (kcm) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001013 kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState);
1014 } else {
1015 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001016 }
1017 }
1018 }
1019
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001020 if (status != NO_ERROR) {
1021 *outKeycode = 0;
1022 *outFlags = 0;
1023 *outMetaState = metaState;
1024 }
1025
1026 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001027}
1028
1029status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
Chris Ye87143712020-11-10 05:05:58 +00001030 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001031 Device* device = getDeviceLocked(deviceId);
1032
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001033 if (device == nullptr || !device->keyMap.haveKeyLayout()) {
1034 return NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001035 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001036 std::optional<AxisInfo> info = device->keyMap.keyLayoutMap->mapAxis(scanCode);
1037 if (!info.has_value()) {
1038 return NAME_NOT_FOUND;
1039 }
1040 *outAxisInfo = *info;
1041 return NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001042}
1043
Chris Yef59a2f42020-10-16 12:55:26 -07001044base::Result<std::pair<InputDeviceSensorType, int32_t>> EventHub::mapSensor(int32_t deviceId,
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001045 int32_t absCode) const {
Chris Yef59a2f42020-10-16 12:55:26 -07001046 std::scoped_lock _l(mLock);
1047 Device* device = getDeviceLocked(deviceId);
1048
1049 if (device != nullptr && device->keyMap.haveKeyLayout()) {
1050 return device->keyMap.keyLayoutMap->mapSensor(absCode);
1051 }
1052 return Errorf("Device not found or device has no key layout.");
1053}
1054
Chris Yee2b1e5c2021-03-10 22:45:12 -08001055// Gets the battery info map from battery ID to RawBatteryInfo of the miscellaneous device
1056// associated with the device ID. Returns an empty map if no miscellaneous device found.
1057const std::unordered_map<int32_t, RawBatteryInfo>& EventHub::getBatteryInfoLocked(
1058 int32_t deviceId) const {
1059 static const std::unordered_map<int32_t, RawBatteryInfo> EMPTY_BATTERY_INFO = {};
1060 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001061 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001062 return EMPTY_BATTERY_INFO;
1063 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001064 return device->associatedDevice->batteryInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001065}
1066
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001067std::vector<int32_t> EventHub::getRawBatteryIds(int32_t deviceId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001068 std::scoped_lock _l(mLock);
1069 std::vector<int32_t> batteryIds;
1070
Prabir Pradhan51894782022-08-23 16:29:10 +00001071 for (const auto& [id, info] : getBatteryInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001072 batteryIds.push_back(id);
1073 }
1074
1075 return batteryIds;
1076}
1077
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001078std::optional<RawBatteryInfo> EventHub::getRawBatteryInfo(int32_t deviceId,
1079 int32_t batteryId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001080 std::scoped_lock _l(mLock);
1081
1082 const auto infos = getBatteryInfoLocked(deviceId);
1083
1084 auto it = infos.find(batteryId);
1085 if (it != infos.end()) {
1086 return it->second;
1087 }
1088
1089 return std::nullopt;
1090}
1091
1092// Gets the light info map from light ID to RawLightInfo of the miscellaneous device associated
Prabir Pradhan51894782022-08-23 16:29:10 +00001093// with the device ID. Returns an empty map if no miscellaneous device found.
Chris Yee2b1e5c2021-03-10 22:45:12 -08001094const std::unordered_map<int32_t, RawLightInfo>& EventHub::getLightInfoLocked(
1095 int32_t deviceId) const {
1096 static const std::unordered_map<int32_t, RawLightInfo> EMPTY_LIGHT_INFO = {};
1097 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001098 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001099 return EMPTY_LIGHT_INFO;
1100 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001101 return device->associatedDevice->lightInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001102}
1103
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001104std::vector<int32_t> EventHub::getRawLightIds(int32_t deviceId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001105 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001106 std::vector<int32_t> lightIds;
1107
Prabir Pradhan51894782022-08-23 16:29:10 +00001108 for (const auto& [id, info] : getLightInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001109 lightIds.push_back(id);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001110 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001111
Chris Ye3fdbfef2021-01-06 18:45:18 -08001112 return lightIds;
1113}
1114
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001115std::optional<RawLightInfo> EventHub::getRawLightInfo(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001116 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001117
Chris Yee2b1e5c2021-03-10 22:45:12 -08001118 const auto infos = getLightInfoLocked(deviceId);
1119
1120 auto it = infos.find(lightId);
1121 if (it != infos.end()) {
1122 return it->second;
Chris Ye3fdbfef2021-01-06 18:45:18 -08001123 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001124
Chris Ye3fdbfef2021-01-06 18:45:18 -08001125 return std::nullopt;
1126}
1127
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001128std::optional<int32_t> EventHub::getLightBrightness(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001129 std::scoped_lock _l(mLock);
1130
Chris Yee2b1e5c2021-03-10 22:45:12 -08001131 const auto infos = getLightInfoLocked(deviceId);
1132 auto it = infos.find(lightId);
1133 if (it == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001134 return std::nullopt;
1135 }
1136 std::string buffer;
1137 if (!base::ReadFileToString(it->second.path / LIGHT_NODES.at(InputLightClass::BRIGHTNESS),
1138 &buffer)) {
1139 return std::nullopt;
1140 }
1141 return std::stoi(buffer);
1142}
1143
1144std::optional<std::unordered_map<LightColor, int32_t>> EventHub::getLightIntensities(
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001145 int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001146 std::scoped_lock _l(mLock);
1147
Chris Yee2b1e5c2021-03-10 22:45:12 -08001148 const auto infos = getLightInfoLocked(deviceId);
1149 auto lightIt = infos.find(lightId);
1150 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001151 return std::nullopt;
1152 }
1153
1154 auto ret =
1155 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1156
1157 if (!ret.has_value()) {
1158 return std::nullopt;
1159 }
1160 std::array<LightColor, COLOR_NUM> colors = ret.value();
1161
1162 std::string intensityStr;
1163 if (!base::ReadFileToString(lightIt->second.path /
1164 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY),
1165 &intensityStr)) {
1166 return std::nullopt;
1167 }
1168
1169 // Intensity node outputs 3 color values
1170 std::regex intensityPattern("([0-9]+)\\s([0-9]+)\\s([0-9]+)[\\n]");
1171 std::smatch results;
1172
1173 if (!std::regex_match(intensityStr, results, intensityPattern)) {
1174 return std::nullopt;
1175 }
1176 std::unordered_map<LightColor, int32_t> intensities;
1177 for (size_t i = 1; i < results.size(); i++) {
1178 int value = std::stoi(results[i].str());
1179 intensities.emplace(colors[i - 1], value);
1180 }
1181 return intensities;
1182}
1183
1184void EventHub::setLightBrightness(int32_t deviceId, int32_t lightId, int32_t brightness) {
1185 std::scoped_lock _l(mLock);
1186
Chris Yee2b1e5c2021-03-10 22:45:12 -08001187 const auto infos = getLightInfoLocked(deviceId);
1188 auto lightIt = infos.find(lightId);
1189 if (lightIt == infos.end()) {
1190 ALOGE("%s lightId %d not found ", __func__, lightId);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001191 return;
1192 }
1193
1194 if (!base::WriteStringToFile(std::to_string(brightness),
1195 lightIt->second.path /
1196 LIGHT_NODES.at(InputLightClass::BRIGHTNESS))) {
1197 ALOGE("Can not write to file, error: %s", strerror(errno));
1198 }
1199}
1200
1201void EventHub::setLightIntensities(int32_t deviceId, int32_t lightId,
1202 std::unordered_map<LightColor, int32_t> intensities) {
1203 std::scoped_lock _l(mLock);
1204
Chris Yee2b1e5c2021-03-10 22:45:12 -08001205 const auto infos = getLightInfoLocked(deviceId);
1206 auto lightIt = infos.find(lightId);
1207 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001208 ALOGE("Light Id %d does not exist.", lightId);
1209 return;
1210 }
1211
1212 auto ret =
1213 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1214
1215 if (!ret.has_value()) {
1216 return;
1217 }
1218 std::array<LightColor, COLOR_NUM> colors = ret.value();
1219
1220 std::string rgbStr;
1221 for (size_t i = 0; i < COLOR_NUM; i++) {
1222 auto it = intensities.find(colors[i]);
1223 if (it != intensities.end()) {
1224 rgbStr += std::to_string(it->second);
1225 // Insert space between colors
1226 if (i < COLOR_NUM - 1) {
1227 rgbStr += " ";
1228 }
1229 }
1230 }
1231 // Append new line
1232 rgbStr += "\n";
1233
1234 if (!base::WriteStringToFile(rgbStr,
1235 lightIt->second.path /
1236 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY))) {
1237 ALOGE("Can not write to file, error: %s", strerror(errno));
1238 }
1239}
1240
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001241void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Chris Ye87143712020-11-10 05:05:58 +00001242 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243
1244 mExcludedDevices = devices;
1245}
1246
1247bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
Chris Ye87143712020-11-10 05:05:58 +00001248 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001249 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001250 if (device != nullptr && scanCode >= 0 && scanCode <= KEY_MAX) {
1251 return device->keyBitmask.test(scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001252 }
1253 return false;
1254}
1255
Arthur Hungcb40a002021-08-03 14:31:01 +00001256bool EventHub::hasKeyCode(int32_t deviceId, int32_t keyCode) const {
1257 std::scoped_lock _l(mLock);
1258 Device* device = getDeviceLocked(deviceId);
1259 if (device != nullptr) {
1260 return device->hasKeycodeLocked(keyCode);
1261 }
1262 return false;
1263}
1264
Michael Wrightd02c5b62014-02-10 15:10:22 -08001265bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
Chris Ye87143712020-11-10 05:05:58 +00001266 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001267 Device* device = getDeviceLocked(deviceId);
1268 int32_t sc;
Chris Ye989bb932020-07-04 16:18:59 -07001269 if (device != nullptr && device->mapLed(led, &sc) == NO_ERROR) {
Chris Ye66fbac32020-07-06 20:36:43 -07001270 return device->ledBitmask.test(sc);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001271 }
1272 return false;
1273}
1274
1275void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
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 Ye989bb932020-07-04 16:18:59 -07001278 if (device != nullptr && device->hasValidFd()) {
1279 device->setLedStateLocked(led, on);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001280 }
1281}
1282
1283void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001284 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001285 outVirtualKeys.clear();
1286
Chris Ye87143712020-11-10 05:05:58 +00001287 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001288 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001289 if (device != nullptr && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001290 const std::vector<VirtualKeyDefinition> virtualKeys =
1291 device->virtualKeyMap->getVirtualKeys();
1292 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001293 }
1294}
1295
Chris Ye3a1e4462020-08-12 10:13:15 -07001296const std::shared_ptr<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001297 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001298 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001299 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001300 return device->getKeyCharacterMap();
1301 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001302 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001303}
1304
Chris Ye3a1e4462020-08-12 10:13:15 -07001305bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, std::shared_ptr<KeyCharacterMap> map) {
Chris Ye87143712020-11-10 05:05:58 +00001306 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001307 Device* device = getDeviceLocked(deviceId);
Philip Junker90bc9492021-12-10 18:39:42 +01001308 if (device == nullptr || map == nullptr || device->keyMap.keyCharacterMap == nullptr) {
1309 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001310 }
Philip Junker90bc9492021-12-10 18:39:42 +01001311 device->keyMap.keyCharacterMap->combine(*map);
1312 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001313}
1314
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001315static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
1316 std::string rawDescriptor;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001317 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001318 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001319 if (!identifier.uniqueId.empty()) {
1320 rawDescriptor += "uniqueId:";
1321 rawDescriptor += identifier.uniqueId;
Josh Bartel938632f2022-07-19 15:34:22 -05001322 }
1323 if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001324 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001325 }
1326
1327 if (identifier.vendor == 0 && identifier.product == 0) {
1328 // If we don't know the vendor and product id, then the device is probably
1329 // built-in so we need to rely on other information to uniquely identify
1330 // the input device. Usually we try to avoid relying on the device name or
1331 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001332 if (!identifier.name.empty()) {
1333 rawDescriptor += "name:";
1334 rawDescriptor += identifier.name;
1335 } else if (!identifier.location.empty()) {
1336 rawDescriptor += "location:";
1337 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001338 }
1339 }
1340 identifier.descriptor = sha1(rawDescriptor);
1341 return rawDescriptor;
1342}
1343
1344void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
1345 // Compute a device descriptor that uniquely identifies the device.
1346 // The descriptor is assumed to be a stable identifier. Its value should not
1347 // change between reboots, reconnections, firmware updates or new releases
1348 // of Android. In practice we sometimes get devices that cannot be uniquely
1349 // identified. In this case we enforce uniqueness between connected devices.
1350 // Ideally, we also want the descriptor to be short and relatively opaque.
Josh Bartel938632f2022-07-19 15:34:22 -05001351 // Note that we explicitly do not use the path or location for external devices
1352 // as their path or location will change as they are plugged/unplugged or moved
1353 // to different ports. We do fallback to using name and location in the case of
1354 // internal devices which are detected by the vendor and product being 0 in
1355 // generateDescriptor. If two identical descriptors are detected we will fallback
1356 // to using a 'nonce' and incrementing it until the new descriptor no longer has
1357 // a match with any existing descriptors.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001358
1359 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001360 std::string rawDescriptor = generateDescriptor(identifier);
Josh Bartel938632f2022-07-19 15:34:22 -05001361 // Enforce that the generated descriptor is unique.
1362 while (hasDeviceWithDescriptorLocked(identifier.descriptor)) {
1363 identifier.nonce++;
1364 rawDescriptor = generateDescriptor(identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001365 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001366 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001367 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001368}
1369
Prabir Pradhancb42b472022-08-23 16:01:19 +00001370std::shared_ptr<const EventHub::AssociatedDevice> EventHub::obtainAssociatedDeviceLocked(
1371 const std::filesystem::path& devicePath) const {
1372 const std::optional<std::filesystem::path> sysfsRootPathOpt =
1373 getSysfsRootPath(devicePath.c_str());
1374 if (!sysfsRootPathOpt) {
1375 return nullptr;
1376 }
1377
1378 const auto& path = *sysfsRootPathOpt;
1379 for (const auto& [id, dev] : mDevices) {
1380 if (dev->associatedDevice && dev->associatedDevice->sysfsRootPath == path) {
1381 return dev->associatedDevice;
1382 }
1383 }
1384
1385 return std::make_shared<AssociatedDevice>(
1386 AssociatedDevice{.sysfsRootPath = path,
1387 .batteryInfos = readBatteryConfiguration(path),
1388 .lightInfos = readLightsConfiguration(path)});
1389}
1390
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001391void EventHub::vibrate(int32_t deviceId, const VibrationElement& element) {
Chris Ye87143712020-11-10 05:05:58 +00001392 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001393 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001394 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001395 ff_effect effect;
1396 memset(&effect, 0, sizeof(effect));
1397 effect.type = FF_RUMBLE;
1398 effect.id = device->ffEffectId;
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001399 // evdev FF_RUMBLE effect only supports two channels of vibration.
Chris Ye6393a262020-08-04 19:41:36 -07001400 effect.u.rumble.strong_magnitude = element.getMagnitude(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1401 effect.u.rumble.weak_magnitude = element.getMagnitude(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001402 effect.replay.length = element.duration.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001403 effect.replay.delay = 0;
1404 if (ioctl(device->fd, EVIOCSFF, &effect)) {
1405 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001406 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001407 return;
1408 }
1409 device->ffEffectId = effect.id;
1410
1411 struct input_event ev;
1412 ev.time.tv_sec = 0;
1413 ev.time.tv_usec = 0;
1414 ev.type = EV_FF;
1415 ev.code = device->ffEffectId;
1416 ev.value = 1;
1417 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1418 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001419 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001420 return;
1421 }
1422 device->ffEffectPlaying = true;
1423 }
1424}
1425
1426void EventHub::cancelVibrate(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001427 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001428 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001429 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001430 if (device->ffEffectPlaying) {
1431 device->ffEffectPlaying = false;
1432
1433 struct input_event ev;
1434 ev.time.tv_sec = 0;
1435 ev.time.tv_usec = 0;
1436 ev.type = EV_FF;
1437 ev.code = device->ffEffectId;
1438 ev.value = 0;
1439 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1440 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001441 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001442 return;
1443 }
1444 }
1445 }
1446}
1447
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001448std::vector<int32_t> EventHub::getVibratorIds(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001449 std::scoped_lock _l(mLock);
1450 std::vector<int32_t> vibrators;
1451 Device* device = getDeviceLocked(deviceId);
1452 if (device != nullptr && device->hasValidFd() &&
1453 device->classes.test(InputDeviceClass::VIBRATOR)) {
1454 vibrators.push_back(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1455 vibrators.push_back(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
1456 }
1457 return vibrators;
1458}
1459
Josh Bartel938632f2022-07-19 15:34:22 -05001460/**
1461 * Checks both mDevices and mOpeningDevices for a device with the descriptor passed.
1462 */
1463bool EventHub::hasDeviceWithDescriptorLocked(const std::string& descriptor) const {
1464 for (const auto& device : mOpeningDevices) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001465 if (descriptor == device->identifier.descriptor) {
Josh Bartel938632f2022-07-19 15:34:22 -05001466 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001467 }
1468 }
Josh Bartel938632f2022-07-19 15:34:22 -05001469
1470 for (const auto& [id, device] : mDevices) {
1471 if (descriptor == device->identifier.descriptor) {
1472 return true;
1473 }
1474 }
1475 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001476}
1477
1478EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001479 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480 deviceId = mBuiltInKeyboardId;
1481 }
Chris Ye989bb932020-07-04 16:18:59 -07001482 const auto& it = mDevices.find(deviceId);
1483 return it != mDevices.end() ? it->second.get() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001484}
1485
Chris Ye8594e192020-07-14 10:34:06 -07001486EventHub::Device* EventHub::getDeviceByPathLocked(const std::string& devicePath) const {
Chris Ye989bb932020-07-04 16:18:59 -07001487 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001488 if (device->path == devicePath) {
Chris Ye989bb932020-07-04 16:18:59 -07001489 return device.get();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001490 }
1491 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001492 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001493}
1494
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001495/**
1496 * The file descriptor could be either input device, or a video device (associated with a
1497 * specific input device). Check both cases here, and return the device that this event
1498 * belongs to. Caller can compare the fd's once more to determine event type.
1499 * Looks through all input devices, and only attached video devices. Unattached video
1500 * devices are ignored.
1501 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001502EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
Chris Ye989bb932020-07-04 16:18:59 -07001503 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001504 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001505 // This is an input device event
Chris Ye989bb932020-07-04 16:18:59 -07001506 return device.get();
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001507 }
1508 if (device->videoDevice && device->videoDevice->getFd() == fd) {
1509 // This is a video device event
Chris Ye989bb932020-07-04 16:18:59 -07001510 return device.get();
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001511 }
1512 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001513 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
1514 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001515 return nullptr;
1516}
1517
Chris Yee2b1e5c2021-03-10 22:45:12 -08001518std::optional<int32_t> EventHub::getBatteryCapacity(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001519 std::filesystem::path batteryPath;
1520 {
1521 // Do not read the sysfs node to get the battery state while holding
1522 // the EventHub lock. For some peripheral devices, reading battery state
1523 // can be broken and take 5+ seconds. Holding the lock in this case would
1524 // block all other event processing during this time. For now, we assume this
1525 // call never happens on the InputReader thread and read the sysfs node outside
1526 // the lock to prevent event processing from being blocked by this call.
1527 std::scoped_lock _l(mLock);
Kim Low03ea0352020-11-06 12:45:07 -08001528
Andy Chenf9f1a022022-08-29 20:07:10 -04001529 const auto infos = getBatteryInfoLocked(deviceId);
1530 auto it = infos.find(batteryId);
1531 if (it == infos.end()) {
1532 return std::nullopt;
1533 }
1534 batteryPath = it->second.path;
1535 } // release lock
1536
Chris Yee2b1e5c2021-03-10 22:45:12 -08001537 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001538
1539 // Some devices report battery capacity as an integer through the "capacity" file
Andy Chenf9f1a022022-08-29 20:07:10 -04001540 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001541 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001542 return std::stoi(base::Trim(buffer));
Kim Low03ea0352020-11-06 12:45:07 -08001543 }
1544
1545 // Other devices report capacity as an enum value POWER_SUPPLY_CAPACITY_LEVEL_XXX
1546 // These values are taken from kernel source code include/linux/power_supply.h
Andy Chenf9f1a022022-08-29 20:07:10 -04001547 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY_LEVEL),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001548 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001549 // Remove any white space such as trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001550 const auto levelIt = BATTERY_LEVEL.find(base::Trim(buffer));
1551 if (levelIt != BATTERY_LEVEL.end()) {
1552 return levelIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001553 }
1554 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001555
Kim Low03ea0352020-11-06 12:45:07 -08001556 return std::nullopt;
1557}
1558
Chris Yee2b1e5c2021-03-10 22:45:12 -08001559std::optional<int32_t> EventHub::getBatteryStatus(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001560 std::filesystem::path batteryPath;
1561 {
1562 // Do not read the sysfs node to get the battery state while holding
1563 // the EventHub lock. For some peripheral devices, reading battery state
1564 // can be broken and take 5+ seconds. Holding the lock in this case would
1565 // block all other event processing during this time. For now, we assume this
1566 // call never happens on the InputReader thread and read the sysfs node outside
1567 // the lock to prevent event processing from being blocked by this call.
1568 std::scoped_lock _l(mLock);
1569
1570 const auto infos = getBatteryInfoLocked(deviceId);
1571 auto it = infos.find(batteryId);
1572 if (it == infos.end()) {
1573 return std::nullopt;
1574 }
1575 batteryPath = it->second.path;
1576 } // release lock
1577
Chris Yee2b1e5c2021-03-10 22:45:12 -08001578 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001579
Andy Chenf9f1a022022-08-29 20:07:10 -04001580 if (!base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::STATUS),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001581 &buffer)) {
Kim Low03ea0352020-11-06 12:45:07 -08001582 ALOGE("Failed to read sysfs battery info: %s", strerror(errno));
1583 return std::nullopt;
1584 }
1585
Chris Yed1936772021-02-22 10:30:40 -08001586 // Remove white space like trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001587 const auto statusIt = BATTERY_STATUS.find(base::Trim(buffer));
1588 if (statusIt != BATTERY_STATUS.end()) {
1589 return statusIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001590 }
1591
1592 return std::nullopt;
1593}
1594
Michael Wrightd02c5b62014-02-10 15:10:22 -08001595size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
1596 ALOG_ASSERT(bufferSize >= 1);
1597
Chris Ye87143712020-11-10 05:05:58 +00001598 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001599
1600 struct input_event readBuffer[bufferSize];
1601
1602 RawEvent* event = buffer;
1603 size_t capacity = bufferSize;
1604 bool awoken = false;
1605 for (;;) {
1606 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
1607
1608 // Reopen input devices if needed.
1609 if (mNeedToReopenDevices) {
1610 mNeedToReopenDevices = false;
1611
1612 ALOGI("Reopening all input devices due to a configuration change.");
1613
1614 closeAllDevicesLocked();
1615 mNeedToScanDevices = true;
1616 break; // return to the caller before we actually rescan
1617 }
1618
1619 // Report any devices that had last been added/removed.
Chris Ye989bb932020-07-04 16:18:59 -07001620 for (auto it = mClosingDevices.begin(); it != mClosingDevices.end();) {
1621 std::unique_ptr<Device> device = std::move(*it);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001622 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001623 event->when = now;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001624 event->deviceId = (device->id == mBuiltInKeyboardId)
1625 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
1626 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001627 event->type = DEVICE_REMOVED;
1628 event += 1;
Chris Ye989bb932020-07-04 16:18:59 -07001629 it = mClosingDevices.erase(it);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001630 mNeedToSendFinishedDeviceScan = true;
1631 if (--capacity == 0) {
1632 break;
1633 }
1634 }
1635
1636 if (mNeedToScanDevices) {
1637 mNeedToScanDevices = false;
1638 scanDevicesLocked();
1639 mNeedToSendFinishedDeviceScan = true;
1640 }
1641
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001642 while (!mOpeningDevices.empty()) {
1643 std::unique_ptr<Device> device = std::move(*mOpeningDevices.rbegin());
1644 mOpeningDevices.pop_back();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001645 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001646 event->when = now;
1647 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1648 event->type = DEVICE_ADDED;
1649 event += 1;
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001650
1651 // Try to find a matching video device by comparing device names
1652 for (auto it = mUnattachedVideoDevices.begin(); it != mUnattachedVideoDevices.end();
1653 it++) {
1654 std::unique_ptr<TouchVideoDevice>& videoDevice = *it;
Chris Yed3fef462021-03-07 17:10:08 -08001655 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001656 // videoDevice was transferred to 'device'
1657 it = mUnattachedVideoDevices.erase(it);
1658 break;
1659 }
1660 }
1661
1662 auto [dev_it, inserted] = mDevices.insert_or_assign(device->id, std::move(device));
1663 if (!inserted) {
Chris Ye989bb932020-07-04 16:18:59 -07001664 ALOGW("Device id %d exists, replaced.", device->id);
1665 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001666 mNeedToSendFinishedDeviceScan = true;
1667 if (--capacity == 0) {
1668 break;
1669 }
1670 }
1671
1672 if (mNeedToSendFinishedDeviceScan) {
1673 mNeedToSendFinishedDeviceScan = false;
1674 event->when = now;
1675 event->type = FINISHED_DEVICE_SCAN;
1676 event += 1;
1677 if (--capacity == 0) {
1678 break;
1679 }
1680 }
1681
1682 // Grab the next input event.
1683 bool deviceChanged = false;
1684 while (mPendingEventIndex < mPendingEventCount) {
1685 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001686 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001687 if (eventItem.events & EPOLLIN) {
1688 mPendingINotify = true;
1689 } else {
1690 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
1691 }
1692 continue;
1693 }
1694
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001695 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001696 if (eventItem.events & EPOLLIN) {
1697 ALOGV("awoken after wake()");
1698 awoken = true;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001699 char wakeReadBuffer[16];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001700 ssize_t nRead;
1701 do {
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001702 nRead = read(mWakeReadPipeFd, wakeReadBuffer, sizeof(wakeReadBuffer));
1703 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(wakeReadBuffer));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001704 } else {
1705 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001706 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001707 }
1708 continue;
1709 }
1710
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001711 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Chris Ye989bb932020-07-04 16:18:59 -07001712 if (device == nullptr) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001713 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
1714 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001715 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001716 continue;
1717 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001718 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
1719 if (eventItem.events & EPOLLIN) {
1720 size_t numFrames = device->videoDevice->readAndQueueFrames();
1721 if (numFrames == 0) {
1722 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001723 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001724 }
1725 } else if (eventItem.events & EPOLLHUP) {
1726 // TODO(b/121395353) - consider adding EPOLLRDHUP
1727 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001728 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001729 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1730 device->videoDevice = nullptr;
1731 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001732 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1733 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001734 ALOG_ASSERT(!DEBUG);
1735 }
1736 continue;
1737 }
1738 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -08001739 if (eventItem.events & EPOLLIN) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001740 int32_t readSize =
1741 read(device->fd, readBuffer, sizeof(struct input_event) * capacity);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001742 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
1743 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -07001744 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001745 " bufferSize: %zu capacity: %zu errno: %d)\n",
1746 device->fd, readSize, bufferSize, capacity, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001747 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001748 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001749 } else if (readSize < 0) {
1750 if (errno != EAGAIN && errno != EINTR) {
1751 ALOGW("could not get event (errno=%d)", errno);
1752 }
1753 } else if ((readSize % sizeof(struct input_event)) != 0) {
1754 ALOGE("could not get event (wrong size: %d)", readSize);
1755 } else {
1756 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1757
1758 size_t count = size_t(readSize) / sizeof(struct input_event);
1759 for (size_t i = 0; i < count; i++) {
1760 struct input_event& iev = readBuffer[i];
Siarhei Vishniakou592bac22018-11-08 19:42:38 -08001761 event->when = processEventTimestamp(iev);
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001762 event->readTime = systemTime(SYSTEM_TIME_MONOTONIC);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001763 event->deviceId = deviceId;
1764 event->type = iev.type;
1765 event->code = iev.code;
1766 event->value = iev.value;
1767 event += 1;
1768 capacity -= 1;
1769 }
1770 if (capacity == 0) {
1771 // The result buffer is full. Reset the pending event index
1772 // so we will try to read the device again on the next iteration.
1773 mPendingEventIndex -= 1;
1774 break;
1775 }
1776 }
1777 } else if (eventItem.events & EPOLLHUP) {
1778 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001779 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001780 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001781 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001782 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001783 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1784 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001785 }
1786 }
1787
1788 // readNotify() will modify the list of devices so this must be done after
1789 // processing all other events to ensure that we read all remaining events
1790 // before closing the devices.
1791 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
1792 mPendingINotify = false;
Prabir Pradhan952e65b2022-06-23 17:49:55 +00001793 const auto res = readNotifyLocked();
1794 if (!res.ok()) {
1795 ALOGW("Failed to read from inotify: %s", res.error().message().c_str());
1796 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001797 deviceChanged = true;
1798 }
1799
1800 // Report added or removed devices immediately.
1801 if (deviceChanged) {
1802 continue;
1803 }
1804
1805 // Return now if we have collected any events or if we were explicitly awoken.
1806 if (event != buffer || awoken) {
1807 break;
1808 }
1809
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001810 // Poll for events.
1811 // When a device driver has pending (unread) events, it acquires
1812 // a kernel wake lock. Once the last pending event has been read, the device
1813 // driver will release the kernel wake lock, but the epoll will hold the wakelock,
1814 // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
1815 // is called again for the same fd that produced the event.
1816 // Thus the system can only sleep if there are no events pending or
1817 // currently being processed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001818 //
1819 // The timeout is advisory only. If the device is asleep, it will not wake just to
1820 // service the timeout.
1821 mPendingEventIndex = 0;
1822
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001823 mLock.unlock(); // release lock before poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001824
1825 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1826
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001827 mLock.lock(); // reacquire lock after poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001828
1829 if (pollResult == 0) {
1830 // Timed out.
1831 mPendingEventCount = 0;
1832 break;
1833 }
1834
1835 if (pollResult < 0) {
1836 // An error occurred.
1837 mPendingEventCount = 0;
1838
1839 // Sleep after errors to avoid locking up the system.
1840 // Hopefully the error is transient.
1841 if (errno != EINTR) {
1842 ALOGW("poll failed (errno=%d)\n", errno);
1843 usleep(100000);
1844 }
1845 } else {
1846 // Some events occurred.
1847 mPendingEventCount = size_t(pollResult);
1848 }
1849 }
1850
1851 // All done, return the number of events we read.
1852 return event - buffer;
1853}
1854
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001855std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001856 std::scoped_lock _l(mLock);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001857
1858 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001859 if (device == nullptr || !device->videoDevice) {
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001860 return {};
1861 }
1862 return device->videoDevice->consumeFrames();
1863}
1864
Michael Wrightd02c5b62014-02-10 15:10:22 -08001865void EventHub::wake() {
1866 ALOGV("wake() called");
1867
1868 ssize_t nWrite;
1869 do {
1870 nWrite = write(mWakeWritePipeFd, "W", 1);
1871 } while (nWrite == -1 && errno == EINTR);
1872
1873 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001874 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001875 }
1876}
1877
1878void EventHub::scanDevicesLocked() {
Usama Arifb27c8e62021-06-03 16:44:09 +01001879 status_t result;
1880 std::error_code errorCode;
1881
1882 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
1883 result = scanDirLocked(DEVICE_INPUT_PATH);
1884 if (result < 0) {
1885 ALOGE("scan dir failed for %s", DEVICE_INPUT_PATH);
1886 }
1887 } else {
1888 if (errorCode) {
1889 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
1890 errorCode.message().c_str());
1891 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001892 }
Philip Quinn39b81682019-01-09 22:20:39 -08001893 if (isV4lScanningEnabled()) {
Usama Arifb27c8e62021-06-03 16:44:09 +01001894 result = scanVideoDirLocked(DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08001895 if (result != OK) {
Usama Arifb27c8e62021-06-03 16:44:09 +01001896 ALOGE("scan video dir failed for %s", DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08001897 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001898 }
Chris Ye989bb932020-07-04 16:18:59 -07001899 if (mDevices.find(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) == mDevices.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001900 createVirtualKeyboardLocked();
1901 }
1902}
1903
1904// ----------------------------------------------------------------------------
1905
Michael Wrightd02c5b62014-02-10 15:10:22 -08001906static const int32_t GAMEPAD_KEYCODES[] = {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001907 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C, //
1908 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z, //
1909 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1, //
1910 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2, //
1911 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR, //
1912 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE, //
Michael Wrightd02c5b62014-02-10 15:10:22 -08001913};
1914
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001915status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001916 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001917 struct epoll_event eventItem = {};
1918 eventItem.events = EPOLLIN | EPOLLWAKEUP;
1919 eventItem.data.fd = fd;
1920 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1921 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001922 return -errno;
1923 }
1924 return OK;
1925}
1926
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001927status_t EventHub::unregisterFdFromEpoll(int fd) {
1928 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
1929 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
1930 return -errno;
1931 }
1932 return OK;
1933}
1934
Chris Ye989bb932020-07-04 16:18:59 -07001935status_t EventHub::registerDeviceForEpollLocked(Device& device) {
1936 status_t result = registerFdForEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001937 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07001938 ALOGE("Could not add input device fd to epoll for device %" PRId32, device.id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001939 return result;
1940 }
Chris Ye989bb932020-07-04 16:18:59 -07001941 if (device.videoDevice) {
1942 registerVideoDeviceForEpollLocked(*device.videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001943 }
1944 return result;
1945}
1946
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001947void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
1948 status_t result = registerFdForEpoll(videoDevice.getFd());
1949 if (result != OK) {
1950 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
1951 }
1952}
1953
Chris Ye989bb932020-07-04 16:18:59 -07001954status_t EventHub::unregisterDeviceFromEpollLocked(Device& device) {
1955 if (device.hasValidFd()) {
1956 status_t result = unregisterFdFromEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001957 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07001958 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device.id);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001959 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001960 }
1961 }
Chris Ye989bb932020-07-04 16:18:59 -07001962 if (device.videoDevice) {
1963 unregisterVideoDeviceFromEpollLocked(*device.videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001964 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001965 return OK;
1966}
1967
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001968void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
1969 if (videoDevice.hasValidFd()) {
1970 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
1971 if (result != OK) {
1972 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001973 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001974 }
1975 }
1976}
1977
Chris Yed3fef462021-03-07 17:10:08 -08001978void EventHub::reportDeviceAddedForStatisticsLocked(const InputDeviceIdentifier& identifier,
Dominik Laskowski2f01d772022-03-23 16:01:29 -07001979 ftl::Flags<InputDeviceClass> classes) {
Chris Ye657c2f02021-05-25 16:24:37 -07001980 SHA256_CTX ctx;
1981 SHA256_Init(&ctx);
1982 SHA256_Update(&ctx, reinterpret_cast<const uint8_t*>(identifier.uniqueId.c_str()),
1983 identifier.uniqueId.size());
1984 std::array<uint8_t, SHA256_DIGEST_LENGTH> digest;
1985 SHA256_Final(digest.data(), &ctx);
1986
1987 std::string obfuscatedId;
1988 for (size_t i = 0; i < OBFUSCATED_LENGTH; i++) {
1989 obfuscatedId += StringPrintf("%02x", digest[i]);
1990 }
1991
Chris Yed3fef462021-03-07 17:10:08 -08001992 android::util::stats_write(android::util::INPUTDEVICE_REGISTERED, identifier.name.c_str(),
1993 identifier.vendor, identifier.product, identifier.version,
Chris Ye657c2f02021-05-25 16:24:37 -07001994 identifier.bus, obfuscatedId.c_str(), classes.get());
Chris Yed3fef462021-03-07 17:10:08 -08001995}
1996
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00001997void EventHub::openDeviceLocked(const std::string& devicePath) {
1998 // If an input device happens to register around the time when EventHub's constructor runs, it
1999 // is possible that the same input event node (for example, /dev/input/event3) will be noticed
2000 // in both 'inotify' callback and also in the 'scanDirLocked' pass. To prevent duplicate devices
2001 // from getting registered, ensure that this path is not already covered by an existing device.
2002 for (const auto& [deviceId, device] : mDevices) {
2003 if (device->path == devicePath) {
2004 return; // device was already registered
2005 }
2006 }
2007
Michael Wrightd02c5b62014-02-10 15:10:22 -08002008 char buffer[80];
2009
Chris Ye8594e192020-07-14 10:34:06 -07002010 ALOGV("Opening device: %s", devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002011
Chris Ye8594e192020-07-14 10:34:06 -07002012 int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002013 if (fd < 0) {
Chris Ye8594e192020-07-14 10:34:06 -07002014 ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002015 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002016 }
2017
2018 InputDeviceIdentifier identifier;
2019
2020 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002021 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Chris Ye8594e192020-07-14 10:34:06 -07002022 ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002023 } else {
2024 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002025 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002026 }
2027
2028 // Check to see if the device is on our excluded list
2029 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002030 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002031 if (identifier.name == item) {
Chris Ye8594e192020-07-14 10:34:06 -07002032 ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002033 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002034 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002035 }
2036 }
2037
2038 // Get device driver version.
2039 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002040 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Chris Ye8594e192020-07-14 10:34:06 -07002041 ALOGE("could not get driver version for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002042 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002043 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002044 }
2045
2046 // Get device identifier.
2047 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002048 if (ioctl(fd, EVIOCGID, &inputId)) {
Chris Ye8594e192020-07-14 10:34:06 -07002049 ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002050 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002051 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002052 }
2053 identifier.bus = inputId.bustype;
2054 identifier.product = inputId.product;
2055 identifier.vendor = inputId.vendor;
2056 identifier.version = inputId.version;
2057
2058 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002059 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
2060 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002061 } else {
2062 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002063 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002064 }
2065
2066 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002067 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
2068 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002069 } else {
2070 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002071 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002072 }
2073
2074 // Fill in the descriptor.
2075 assignDescriptorLocked(identifier);
2076
Michael Wrightd02c5b62014-02-10 15:10:22 -08002077 // Allocate device. (The device object takes ownership of the fd at this point.)
2078 int32_t deviceId = mNextDeviceId++;
Prabir Pradhancb42b472022-08-23 16:01:19 +00002079 std::unique_ptr<Device> device =
2080 std::make_unique<Device>(fd, deviceId, devicePath, identifier,
2081 obtainAssociatedDeviceLocked(devicePath));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002082
Chris Ye8594e192020-07-14 10:34:06 -07002083 ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002084 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002085 " vendor %04x\n"
2086 " product %04x\n"
2087 " version %04x\n",
2088 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002089 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
2090 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
2091 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
2092 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002093 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
2094 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002095
2096 // Load the configuration file for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002097 device->loadConfigurationLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002098
2099 // Figure out the kinds of events the device reports.
Chris Ye66fbac32020-07-06 20:36:43 -07002100 device->readDeviceBitMask(EVIOCGBIT(EV_KEY, 0), device->keyBitmask);
2101 device->readDeviceBitMask(EVIOCGBIT(EV_ABS, 0), device->absBitmask);
2102 device->readDeviceBitMask(EVIOCGBIT(EV_REL, 0), device->relBitmask);
2103 device->readDeviceBitMask(EVIOCGBIT(EV_SW, 0), device->swBitmask);
2104 device->readDeviceBitMask(EVIOCGBIT(EV_LED, 0), device->ledBitmask);
2105 device->readDeviceBitMask(EVIOCGBIT(EV_FF, 0), device->ffBitmask);
Chris Yef59a2f42020-10-16 12:55:26 -07002106 device->readDeviceBitMask(EVIOCGBIT(EV_MSC, 0), device->mscBitmask);
Chris Ye66fbac32020-07-06 20:36:43 -07002107 device->readDeviceBitMask(EVIOCGPROP(0), device->propBitmask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002108
2109 // See if this is a keyboard. Ignore everything in the button range except for
2110 // joystick and gamepad buttons which are handled like keyboards for the most part.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002111 bool haveKeyboardKeys =
Chris Ye66fbac32020-07-06 20:36:43 -07002112 device->keyBitmask.any(0, BTN_MISC) || device->keyBitmask.any(BTN_WHEEL, KEY_MAX + 1);
2113 bool haveGamepadButtons = device->keyBitmask.any(BTN_MISC, BTN_MOUSE) ||
2114 device->keyBitmask.any(BTN_JOYSTICK, BTN_DIGI);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002115 if (haveKeyboardKeys || haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002116 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002117 }
2118
2119 // See if this is a cursor device such as a trackball or mouse.
Chris Ye66fbac32020-07-06 20:36:43 -07002120 if (device->keyBitmask.test(BTN_MOUSE) && device->relBitmask.test(REL_X) &&
2121 device->relBitmask.test(REL_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002122 device->classes |= InputDeviceClass::CURSOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002123 }
2124
Prashant Malani1941ff52015-08-11 18:29:28 -07002125 // See if this is a rotary encoder type device.
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07002126 std::string deviceType;
2127 if (device->configuration && device->configuration->tryGetProperty("device.type", deviceType)) {
2128 if (deviceType == "rotaryEncoder") {
Chris Ye1b0c7342020-07-28 21:57:03 -07002129 device->classes |= InputDeviceClass::ROTARY_ENCODER;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002130 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002131 }
2132
Michael Wrightd02c5b62014-02-10 15:10:22 -08002133 // See if this is a touch pad.
2134 // Is this a new modern multi-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002135 if (device->absBitmask.test(ABS_MT_POSITION_X) && device->absBitmask.test(ABS_MT_POSITION_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002136 // Some joysticks such as the PS3 controller report axes that conflict
2137 // with the ABS_MT range. Try to confirm that the device really is
2138 // a touch screen.
Chris Ye66fbac32020-07-06 20:36:43 -07002139 if (device->keyBitmask.test(BTN_TOUCH) || !haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002140 device->classes |= (InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002141 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002142 // Is this an old style single-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002143 } else if (device->keyBitmask.test(BTN_TOUCH) && device->absBitmask.test(ABS_X) &&
2144 device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002145 device->classes |= InputDeviceClass::TOUCH;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002146 // Is this a BT stylus?
Chris Ye66fbac32020-07-06 20:36:43 -07002147 } else if ((device->absBitmask.test(ABS_PRESSURE) || device->keyBitmask.test(BTN_TOUCH)) &&
2148 !device->absBitmask.test(ABS_X) && !device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002149 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -07002150 // Keyboard will try to claim some of the buttons but we really want to reserve those so we
2151 // can fuse it with the touch screen data, so just take them back. Note this means an
2152 // external stylus cannot also be a keyboard device.
Chris Ye1b0c7342020-07-28 21:57:03 -07002153 device->classes &= ~InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002154 }
2155
2156 // See if this device is a joystick.
2157 // Assumes that joysticks always have gamepad buttons in order to distinguish them
2158 // from other devices such as accelerometers that also have absolute axes.
2159 if (haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002160 auto assumedClasses = device->classes | InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002161 for (int i = 0; i <= ABS_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002162 if (device->absBitmask.test(i) &&
Chris Ye1b0c7342020-07-28 21:57:03 -07002163 (getAbsAxisUsage(i, assumedClasses).test(InputDeviceClass::JOYSTICK))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002164 device->classes = assumedClasses;
2165 break;
2166 }
2167 }
2168 }
2169
Chris Yef59a2f42020-10-16 12:55:26 -07002170 // Check whether this device is an accelerometer.
2171 if (device->propBitmask.test(INPUT_PROP_ACCELEROMETER)) {
2172 device->classes |= InputDeviceClass::SENSOR;
2173 }
2174
Michael Wrightd02c5b62014-02-10 15:10:22 -08002175 // Check whether this device has switches.
2176 for (int i = 0; i <= SW_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002177 if (device->swBitmask.test(i)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002178 device->classes |= InputDeviceClass::SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002179 break;
2180 }
2181 }
2182
2183 // Check whether this device supports the vibrator.
Chris Ye66fbac32020-07-06 20:36:43 -07002184 if (device->ffBitmask.test(FF_RUMBLE)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002185 device->classes |= InputDeviceClass::VIBRATOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002186 }
2187
2188 // Configure virtual keys.
Chris Ye1b0c7342020-07-28 21:57:03 -07002189 if ((device->classes.test(InputDeviceClass::TOUCH))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002190 // Load the virtual keys for the touch screen, if any.
2191 // We do this now so that we can make sure to load the keymap if necessary.
Chris Ye989bb932020-07-04 16:18:59 -07002192 bool success = device->loadVirtualKeyMapLocked();
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06002193 if (success) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002194 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002195 }
2196 }
2197
2198 // Load the key map.
Chris Yef59a2f42020-10-16 12:55:26 -07002199 // We need to do this for joysticks too because the key layout may specify axes, and for
2200 // sensor as well because the key layout may specify the axes to sensor data mapping.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002201 status_t keyMapStatus = NAME_NOT_FOUND;
Chris Yef59a2f42020-10-16 12:55:26 -07002202 if (device->classes.any(InputDeviceClass::KEYBOARD | InputDeviceClass::JOYSTICK |
2203 InputDeviceClass::SENSOR)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002204 // Load the keymap for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002205 keyMapStatus = device->loadKeyMapLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002206 }
2207
2208 // Configure the keyboard, gamepad or virtual keyboard.
Chris Ye1b0c7342020-07-28 21:57:03 -07002209 if (device->classes.test(InputDeviceClass::KEYBOARD)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002210 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002211 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002212 isEligibleBuiltInKeyboard(device->identifier, device->configuration.get(),
2213 &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002214 mBuiltInKeyboardId = device->id;
2215 }
2216
2217 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
Chris Ye989bb932020-07-04 16:18:59 -07002218 if (device->hasKeycodeLocked(AKEYCODE_Q)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002219 device->classes |= InputDeviceClass::ALPHAKEY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002220 }
2221
2222 // See if this device has a DPAD.
Chris Ye989bb932020-07-04 16:18:59 -07002223 if (device->hasKeycodeLocked(AKEYCODE_DPAD_UP) &&
2224 device->hasKeycodeLocked(AKEYCODE_DPAD_DOWN) &&
2225 device->hasKeycodeLocked(AKEYCODE_DPAD_LEFT) &&
2226 device->hasKeycodeLocked(AKEYCODE_DPAD_RIGHT) &&
2227 device->hasKeycodeLocked(AKEYCODE_DPAD_CENTER)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002228 device->classes |= InputDeviceClass::DPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002229 }
2230
2231 // See if this device has a gamepad.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002232 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES) / sizeof(GAMEPAD_KEYCODES[0]); i++) {
Chris Ye989bb932020-07-04 16:18:59 -07002233 if (device->hasKeycodeLocked(GAMEPAD_KEYCODES[i])) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002234 device->classes |= InputDeviceClass::GAMEPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002235 break;
2236 }
2237 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002238 }
2239
2240 // If the device isn't recognized as something we handle, don't monitor it.
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002241 if (device->classes == ftl::Flags<InputDeviceClass>(0)) {
Chris Ye8594e192020-07-14 10:34:06 -07002242 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002243 device->identifier.name.c_str());
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002244 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002245 }
2246
Chris Ye3fdbfef2021-01-06 18:45:18 -08002247 // Classify InputDeviceClass::BATTERY.
Prabir Pradhan51894782022-08-23 16:29:10 +00002248 if (device->associatedDevice && !device->associatedDevice->batteryInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002249 device->classes |= InputDeviceClass::BATTERY;
2250 }
Kim Low03ea0352020-11-06 12:45:07 -08002251
Chris Ye3fdbfef2021-01-06 18:45:18 -08002252 // Classify InputDeviceClass::LIGHT.
Prabir Pradhan51894782022-08-23 16:29:10 +00002253 if (device->associatedDevice && !device->associatedDevice->lightInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002254 device->classes |= InputDeviceClass::LIGHT;
Kim Low03ea0352020-11-06 12:45:07 -08002255 }
2256
Tim Kilbourn063ff532015-04-08 10:26:18 -07002257 // Determine whether the device has a mic.
Chris Ye989bb932020-07-04 16:18:59 -07002258 if (device->deviceHasMicLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002259 device->classes |= InputDeviceClass::MIC;
Tim Kilbourn063ff532015-04-08 10:26:18 -07002260 }
2261
Michael Wrightd02c5b62014-02-10 15:10:22 -08002262 // Determine whether the device is external or internal.
Chris Ye989bb932020-07-04 16:18:59 -07002263 if (device->isExternalDeviceLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002264 device->classes |= InputDeviceClass::EXTERNAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002265 }
2266
Chris Ye1b0c7342020-07-28 21:57:03 -07002267 if (device->classes.any(InputDeviceClass::JOYSTICK | InputDeviceClass::DPAD) &&
2268 device->classes.test(InputDeviceClass::GAMEPAD)) {
Chris Ye989bb932020-07-04 16:18:59 -07002269 device->controllerNumber = getNextControllerNumberLocked(device->identifier.name);
2270 device->setLedForControllerLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002271 }
2272
Chris Ye989bb932020-07-04 16:18:59 -07002273 if (registerDeviceForEpollLocked(*device) != OK) {
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002274 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002275 }
2276
Chris Ye989bb932020-07-04 16:18:59 -07002277 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002278
Chris Ye1b0c7342020-07-28 21:57:03 -07002279 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=%s, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002280 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Chris Ye1b0c7342020-07-28 21:57:03 -07002281 deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(),
2282 device->classes.string().c_str(), device->configurationFile.c_str(),
2283 device->keyMap.keyLayoutFile.c_str(), device->keyMap.keyCharacterMapFile.c_str(),
2284 toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002285
Chris Ye989bb932020-07-04 16:18:59 -07002286 addDeviceLocked(std::move(device));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002287}
2288
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002289void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
2290 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
2291 if (!videoDevice) {
2292 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
2293 return;
2294 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002295 // Transfer ownership of this video device to a matching input device
Chris Ye989bb932020-07-04 16:18:59 -07002296 for (const auto& [id, device] : mDevices) {
Chris Yed3fef462021-03-07 17:10:08 -08002297 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002298 return; // 'device' now owns 'videoDevice'
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002299 }
2300 }
2301
2302 // Couldn't find a matching input device, so just add it to a temporary holding queue.
2303 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002304 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002305 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002306 mUnattachedVideoDevices.push_back(std::move(videoDevice));
2307}
2308
Chris Yed3fef462021-03-07 17:10:08 -08002309bool EventHub::tryAddVideoDeviceLocked(EventHub::Device& device,
2310 std::unique_ptr<TouchVideoDevice>& videoDevice) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002311 if (videoDevice->getName() != device.identifier.name) {
2312 return false;
2313 }
2314 device.videoDevice = std::move(videoDevice);
2315 if (device.enabled) {
2316 registerVideoDeviceForEpollLocked(*device.videoDevice);
2317 }
2318 return true;
2319}
2320
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002321bool EventHub::isDeviceEnabled(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00002322 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002323 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002324 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002325 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2326 return false;
2327 }
2328 return device->enabled;
2329}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002330
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002331status_t EventHub::enableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002332 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002333 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002334 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002335 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2336 return BAD_VALUE;
2337 }
2338 if (device->enabled) {
2339 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
2340 return OK;
2341 }
2342 status_t result = device->enable();
2343 if (result != OK) {
2344 ALOGE("Failed to enable device %" PRId32, deviceId);
2345 return result;
2346 }
2347
Chris Ye989bb932020-07-04 16:18:59 -07002348 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002349
Chris Ye989bb932020-07-04 16:18:59 -07002350 return registerDeviceForEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002351}
2352
2353status_t EventHub::disableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002354 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002355 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002356 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002357 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2358 return BAD_VALUE;
2359 }
2360 if (!device->enabled) {
2361 ALOGW("Duplicate call to %s, input device already disabled", __func__);
2362 return OK;
2363 }
Chris Ye989bb932020-07-04 16:18:59 -07002364 unregisterDeviceFromEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002365 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002366}
2367
2368void EventHub::createVirtualKeyboardLocked() {
2369 InputDeviceIdentifier identifier;
2370 identifier.name = "Virtual";
2371 identifier.uniqueId = "<virtual>";
2372 assignDescriptorLocked(identifier);
2373
Chris Ye989bb932020-07-04 16:18:59 -07002374 std::unique_ptr<Device> device =
2375 std::make_unique<Device>(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
Prabir Pradhancb42b472022-08-23 16:01:19 +00002376 identifier, nullptr /*associatedDevice*/);
Chris Ye1b0c7342020-07-28 21:57:03 -07002377 device->classes = InputDeviceClass::KEYBOARD | InputDeviceClass::ALPHAKEY |
2378 InputDeviceClass::DPAD | InputDeviceClass::VIRTUAL;
Chris Ye989bb932020-07-04 16:18:59 -07002379 device->loadKeyMapLocked();
2380 addDeviceLocked(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002381}
2382
Chris Ye989bb932020-07-04 16:18:59 -07002383void EventHub::addDeviceLocked(std::unique_ptr<Device> device) {
Chris Yed3fef462021-03-07 17:10:08 -08002384 reportDeviceAddedForStatisticsLocked(device->identifier, device->classes);
Chris Ye989bb932020-07-04 16:18:59 -07002385 mOpeningDevices.push_back(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002386}
2387
Chris Ye989bb932020-07-04 16:18:59 -07002388int32_t EventHub::getNextControllerNumberLocked(const std::string& name) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002389 if (mControllerNumbers.isFull()) {
2390 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Chris Ye989bb932020-07-04 16:18:59 -07002391 name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002392 return 0;
2393 }
2394 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
2395 // one
2396 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
2397}
2398
Chris Ye989bb932020-07-04 16:18:59 -07002399void EventHub::releaseControllerNumberLocked(int32_t num) {
2400 if (num > 0) {
2401 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002402 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002403}
2404
Chris Ye8594e192020-07-14 10:34:06 -07002405void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002406 Device* device = getDeviceByPathLocked(devicePath);
Chris Ye989bb932020-07-04 16:18:59 -07002407 if (device != nullptr) {
2408 closeDeviceLocked(*device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002409 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002410 }
Chris Ye8594e192020-07-14 10:34:06 -07002411 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002412}
2413
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002414/**
2415 * Find the video device by filename, and close it.
2416 * The video device is closed by path during an inotify event, where we don't have the
2417 * additional context about the video device fd, or the associated input device.
2418 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002419void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002420 // A video device may be owned by an existing input device, or it may be stored in
2421 // the mUnattachedVideoDevices queue. Check both locations.
Chris Ye989bb932020-07-04 16:18:59 -07002422 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002423 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002424 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002425 device->videoDevice = nullptr;
2426 return;
2427 }
2428 }
Siarhei Vishniakouf47c339e2021-12-30 11:22:26 -08002429 std::erase_if(mUnattachedVideoDevices,
2430 [&devicePath](const std::unique_ptr<TouchVideoDevice>& videoDevice) {
2431 return videoDevice->getPath() == devicePath;
2432 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08002433}
2434
2435void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002436 mUnattachedVideoDevices.clear();
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002437 while (!mDevices.empty()) {
2438 closeDeviceLocked(*(mDevices.begin()->second));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002439 }
2440}
2441
Chris Ye989bb932020-07-04 16:18:59 -07002442void EventHub::closeDeviceLocked(Device& device) {
2443 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=%s", device.path.c_str(),
2444 device.identifier.name.c_str(), device.id, device.fd, device.classes.string().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002445
Chris Ye989bb932020-07-04 16:18:59 -07002446 if (device.id == mBuiltInKeyboardId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002447 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Chris Ye989bb932020-07-04 16:18:59 -07002448 device.path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002449 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
2450 }
2451
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002452 unregisterDeviceFromEpollLocked(device);
Chris Ye989bb932020-07-04 16:18:59 -07002453 if (device.videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002454 // This must be done after the video device is removed from epoll
Chris Ye989bb932020-07-04 16:18:59 -07002455 mUnattachedVideoDevices.push_back(std::move(device.videoDevice));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002456 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002457
Chris Ye989bb932020-07-04 16:18:59 -07002458 releaseControllerNumberLocked(device.controllerNumber);
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002459 device.controllerNumber = 0;
Chris Ye989bb932020-07-04 16:18:59 -07002460 device.close();
Chris Ye989bb932020-07-04 16:18:59 -07002461 mClosingDevices.push_back(std::move(mDevices[device.id]));
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002462
Chris Ye989bb932020-07-04 16:18:59 -07002463 mDevices.erase(device.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002464}
2465
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002466base::Result<void> EventHub::readNotifyLocked() {
2467 static constexpr auto EVENT_SIZE = static_cast<ssize_t>(sizeof(inotify_event));
2468 uint8_t eventBuffer[512];
2469 ssize_t sizeRead;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002470
2471 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002472 do {
2473 sizeRead = read(mINotifyFd, eventBuffer, sizeof(eventBuffer));
2474 } while (sizeRead < 0 && errno == EINTR);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002475
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002476 if (sizeRead < EVENT_SIZE) return Errorf("could not get event, %s", strerror(errno));
2477
2478 for (ssize_t eventPos = 0; sizeRead >= EVENT_SIZE;) {
2479 const inotify_event* event;
2480 event = (const inotify_event*)(eventBuffer + eventPos);
2481 if (event->len == 0) continue;
2482
2483 handleNotifyEventLocked(*event);
2484
2485 const ssize_t eventSize = EVENT_SIZE + event->len;
2486 sizeRead -= eventSize;
2487 eventPos += eventSize;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002488 }
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002489 return {};
2490}
2491
2492void EventHub::handleNotifyEventLocked(const inotify_event& event) {
2493 if (event.wd == mDeviceInputWd) {
2494 std::string filename = std::string(DEVICE_INPUT_PATH) + "/" + event.name;
2495 if (event.mask & IN_CREATE) {
2496 openDeviceLocked(filename);
2497 } else {
2498 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
2499 closeDeviceByPathLocked(filename);
2500 }
2501 } else if (event.wd == mDeviceWd) {
2502 if (isV4lTouchNode(event.name)) {
2503 std::string filename = std::string(DEVICE_PATH) + "/" + event.name;
2504 if (event.mask & IN_CREATE) {
2505 openVideoDeviceLocked(filename);
2506 } else {
2507 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
2508 closeVideoDeviceByPathLocked(filename);
2509 }
2510 } else if (strcmp(event.name, "input") == 0 && event.mask & IN_CREATE) {
2511 addDeviceInputInotify();
2512 }
2513 } else {
2514 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event.wd);
2515 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002516}
2517
Chris Ye8594e192020-07-14 10:34:06 -07002518status_t EventHub::scanDirLocked(const std::string& dirname) {
2519 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2520 openDeviceLocked(entry.path());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002521 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002522 return 0;
2523}
2524
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002525/**
2526 * Look for all dirname/v4l-touch* devices, and open them.
2527 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002528status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Chris Ye8594e192020-07-14 10:34:06 -07002529 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2530 if (isV4lTouchNode(entry.path())) {
2531 ALOGI("Found touch video device %s", entry.path().c_str());
2532 openVideoDeviceLocked(entry.path());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002533 }
2534 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002535 return OK;
2536}
2537
Michael Wrightd02c5b62014-02-10 15:10:22 -08002538void EventHub::requestReopenDevices() {
2539 ALOGV("requestReopenDevices() called");
2540
Chris Ye87143712020-11-10 05:05:58 +00002541 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002542 mNeedToReopenDevices = true;
2543}
2544
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002545void EventHub::dump(std::string& dump) const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002546 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002547
2548 { // acquire lock
Chris Ye87143712020-11-10 05:05:58 +00002549 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002550
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002551 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002552
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002553 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002554
Chris Ye989bb932020-07-04 16:18:59 -07002555 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002556 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002557 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002558 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002559 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002560 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002561 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002562 }
Chris Ye1b0c7342020-07-28 21:57:03 -07002563 dump += StringPrintf(INDENT3 "Classes: %s\n", device->classes.string().c_str());
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002564 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002565 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002566 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
2567 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002568 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002569 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002570 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002571 "product=0x%04x, version=0x%04x\n",
2572 device->identifier.bus, device->identifier.vendor,
2573 device->identifier.product, device->identifier.version);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002574 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002575 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002576 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002577 device->keyMap.keyCharacterMapFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002578 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002579 device->configurationFile.c_str());
Prabir Pradhan51894782022-08-23 16:29:10 +00002580 dump += StringPrintf(INDENT3 "VideoDevice: %s\n",
2581 device->videoDevice ? device->videoDevice->dump().c_str()
2582 : "<none>");
2583 dump += StringPrintf(INDENT3 "SysfsDevicePath: %s\n",
2584 device->associatedDevice
2585 ? device->associatedDevice->sysfsRootPath.c_str()
2586 : "<none>");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002587 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002588
2589 dump += INDENT "Unattached video devices:\n";
2590 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
2591 dump += INDENT2 + videoDevice->dump() + "\n";
2592 }
2593 if (mUnattachedVideoDevices.empty()) {
2594 dump += INDENT2 "<none>\n";
2595 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002596 } // release lock
2597}
2598
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002599void EventHub::monitor() const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002600 // Acquire and release the lock to ensure that the event hub has not deadlocked.
Chris Ye1c2e0892020-11-30 21:41:44 -08002601 std::unique_lock<std::mutex> lock(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002602}
2603
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002604} // namespace android