blob: c9d21dc5733bcee930e0559922979d968e597d48 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2005 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070017#include <assert.h>
18#include <dirent.h>
19#include <errno.h>
20#include <fcntl.h>
21#include <inttypes.h>
22#include <memory.h>
23#include <stdint.h>
24#include <stdio.h>
25#include <stdlib.h>
26#include <string.h>
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +010027#include <sys/capability.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070028#include <sys/epoll.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070029#include <sys/inotify.h>
30#include <sys/ioctl.h>
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070031#include <sys/limits.h>
Kim Low03ea0352020-11-06 12:45:07 -080032#include <sys/stat.h>
33#include <sys/sysmacros.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070034#include <unistd.h>
35
Michael Wrightd02c5b62014-02-10 15:10:22 -080036#define LOG_TAG "EventHub"
37
38// #define LOG_NDEBUG 0
Kim Low03ea0352020-11-06 12:45:07 -080039#include <android-base/file.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080040#include <android-base/stringprintf.h>
Chris Yed3fef462021-03-07 17:10:08 -080041#include <android-base/strings.h>
Philip Quinn39b81682019-01-09 22:20:39 -080042#include <cutils/properties.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080043#include <ftl/enum.h>
Chris Ye8594e192020-07-14 10:34:06 -070044#include <input/KeyCharacterMap.h>
45#include <input/KeyLayoutMap.h>
46#include <input/VirtualKeyMap.h>
Dan Albert677d87e2014-06-16 17:31:28 -070047#include <openssl/sha.h>
Chris Yed3fef462021-03-07 17:10:08 -080048#include <statslog.h>
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070049#include <utils/Errors.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080050#include <utils/Log.h>
51#include <utils/Timers.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080052
Chris Ye8594e192020-07-14 10:34:06 -070053#include <filesystem>
Chris Ye3fdbfef2021-01-06 18:45:18 -080054#include <regex>
Prabir Pradhancb42b472022-08-23 16:01:19 +000055#include <utility>
Chris Ye8594e192020-07-14 10:34:06 -070056
57#include "EventHub.h"
Michael Wrightd02c5b62014-02-10 15:10:22 -080058
Michael Wrightd02c5b62014-02-10 15:10:22 -080059#define INDENT " "
60#define INDENT2 " "
61#define INDENT3 " "
62
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080063using android::base::StringPrintf;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +000064using android::hardware::input::InputDeviceCountryCode;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080065
Michael Wrightd02c5b62014-02-10 15:10:22 -080066namespace android {
67
Dominik Laskowski2f01d772022-03-23 16:01:29 -070068using namespace ftl::flag_operators;
69
Usama Arifb27c8e62021-06-03 16:44:09 +010070static const char* DEVICE_INPUT_PATH = "/dev/input";
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080071// v4l2 devices go directly into /dev
Usama Arifb27c8e62021-06-03 16:44:09 +010072static const char* DEVICE_PATH = "/dev";
Michael Wrightd02c5b62014-02-10 15:10:22 -080073
Chris Ye657c2f02021-05-25 16:24:37 -070074static constexpr size_t OBFUSCATED_LENGTH = 8;
75
Chris Ye87143712020-11-10 05:05:58 +000076static constexpr int32_t FF_STRONG_MAGNITUDE_CHANNEL_IDX = 0;
77static constexpr int32_t FF_WEAK_MAGNITUDE_CHANNEL_IDX = 1;
Chris Ye6393a262020-08-04 19:41:36 -070078
Chris Yee2b1e5c2021-03-10 22:45:12 -080079// Mapping for input battery class node IDs lookup.
80// https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
81static const std::unordered_map<std::string, InputBatteryClass> BATTERY_CLASSES =
82 {{"capacity", InputBatteryClass::CAPACITY},
83 {"capacity_level", InputBatteryClass::CAPACITY_LEVEL},
84 {"status", InputBatteryClass::STATUS}};
85
86// Mapping for input battery class node names lookup.
87// https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
88static const std::unordered_map<InputBatteryClass, std::string> BATTERY_NODES =
89 {{InputBatteryClass::CAPACITY, "capacity"},
90 {InputBatteryClass::CAPACITY_LEVEL, "capacity_level"},
91 {InputBatteryClass::STATUS, "status"}};
92
Kim Low03ea0352020-11-06 12:45:07 -080093// must be kept in sync with definitions in kernel /drivers/power/supply/power_supply_sysfs.c
94static const std::unordered_map<std::string, int32_t> BATTERY_STATUS =
95 {{"Unknown", BATTERY_STATUS_UNKNOWN},
96 {"Charging", BATTERY_STATUS_CHARGING},
97 {"Discharging", BATTERY_STATUS_DISCHARGING},
98 {"Not charging", BATTERY_STATUS_NOT_CHARGING},
99 {"Full", BATTERY_STATUS_FULL}};
100
101// Mapping taken from
102// https://gitlab.freedesktop.org/upower/upower/-/blob/master/src/linux/up-device-supply.c#L484
103static const std::unordered_map<std::string, int32_t> BATTERY_LEVEL = {{"Critical", 5},
104 {"Low", 10},
105 {"Normal", 55},
106 {"High", 70},
107 {"Full", 100},
108 {"Unknown", 50}};
109
Chris Ye3fdbfef2021-01-06 18:45:18 -0800110// Mapping for input led class node names lookup.
111// https://www.kernel.org/doc/html/latest/leds/leds-class.html
112static const std::unordered_map<std::string, InputLightClass> LIGHT_CLASSES =
113 {{"red", InputLightClass::RED},
114 {"green", InputLightClass::GREEN},
115 {"blue", InputLightClass::BLUE},
116 {"global", InputLightClass::GLOBAL},
117 {"brightness", InputLightClass::BRIGHTNESS},
118 {"multi_index", InputLightClass::MULTI_INDEX},
119 {"multi_intensity", InputLightClass::MULTI_INTENSITY},
120 {"max_brightness", InputLightClass::MAX_BRIGHTNESS}};
121
122// Mapping for input multicolor led class node names.
123// https://www.kernel.org/doc/html/latest/leds/leds-class-multicolor.html
124static const std::unordered_map<InputLightClass, std::string> LIGHT_NODES =
125 {{InputLightClass::BRIGHTNESS, "brightness"},
126 {InputLightClass::MULTI_INDEX, "multi_index"},
127 {InputLightClass::MULTI_INTENSITY, "multi_intensity"}};
128
129// Mapping for light color name and the light color
130const std::unordered_map<std::string, LightColor> LIGHT_COLORS = {{"red", LightColor::RED},
131 {"green", LightColor::GREEN},
132 {"blue", LightColor::BLUE}};
133
Michael Wrightd02c5b62014-02-10 15:10:22 -0800134static inline const char* toString(bool value) {
135 return value ? "true" : "false";
136}
137
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100138static std::string sha1(const std::string& in) {
Dan Albert677d87e2014-06-16 17:31:28 -0700139 SHA_CTX ctx;
140 SHA1_Init(&ctx);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100141 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
Dan Albert677d87e2014-06-16 17:31:28 -0700142 u_char digest[SHA_DIGEST_LENGTH];
143 SHA1_Final(digest, &ctx);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800144
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100145 std::string out;
Dan Albert677d87e2014-06-16 17:31:28 -0700146 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100147 out += StringPrintf("%02x", digest[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800148 }
149 return out;
150}
151
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800152/**
153 * Return true if name matches "v4l-touch*"
154 */
Chris Ye8594e192020-07-14 10:34:06 -0700155static bool isV4lTouchNode(std::string name) {
156 return name.find("v4l-touch") != std::string::npos;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800157}
158
Philip Quinn39b81682019-01-09 22:20:39 -0800159/**
160 * Returns true if V4L devices should be scanned.
161 *
162 * The system property ro.input.video_enabled can be used to control whether
163 * EventHub scans and opens V4L devices. As V4L does not support multiple
164 * clients, EventHub effectively blocks access to these devices when it opens
Siarhei Vishniakou29f88492019-04-05 14:11:43 -0700165 * them.
166 *
167 * Setting this to "false" would prevent any video devices from being discovered and
168 * associated with input devices.
169 *
170 * This property can be used as follows:
171 * 1. To turn off features that are dependent on video device presence.
172 * 2. During testing and development, to allow other clients to read video devices
173 * directly from /dev.
Philip Quinn39b81682019-01-09 22:20:39 -0800174 */
175static bool isV4lScanningEnabled() {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700176 return property_get_bool("ro.input.video_enabled", true /* default_value */);
Philip Quinn39b81682019-01-09 22:20:39 -0800177}
178
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800179static nsecs_t processEventTimestamp(const struct input_event& event) {
180 // Use the time specified in the event instead of the current time
181 // so that downstream code can get more accurate estimates of
182 // event dispatch latency from the time the event is enqueued onto
183 // the evdev client buffer.
184 //
185 // The event's timestamp fortuitously uses the same monotonic clock
186 // time base as the rest of Android. The kernel event device driver
187 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
188 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
189 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
190 // system call that also queries ktime_get_ts().
191
192 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.time.tv_sec) +
193 microseconds_to_nanoseconds(event.time.tv_usec);
194 return inputEventTime;
195}
196
Kim Low03ea0352020-11-06 12:45:07 -0800197/**
Prabir Pradhancb42b472022-08-23 16:01:19 +0000198 * Returns the sysfs root path of the input device.
Kim Low03ea0352020-11-06 12:45:07 -0800199 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800200static std::optional<std::filesystem::path> getSysfsRootPath(const char* devicePath) {
Kim Low03ea0352020-11-06 12:45:07 -0800201 std::error_code errorCode;
202
203 // Stat the device path to get the major and minor number of the character file
204 struct stat statbuf;
205 if (stat(devicePath, &statbuf) == -1) {
206 ALOGE("Could not stat device %s due to error: %s.", devicePath, std::strerror(errno));
Chris Ye3fdbfef2021-01-06 18:45:18 -0800207 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800208 }
209
210 unsigned int major_num = major(statbuf.st_rdev);
211 unsigned int minor_num = minor(statbuf.st_rdev);
212
213 // Realpath "/sys/dev/char/{major}:{minor}" to get the sysfs path to the input event
214 auto sysfsPath = std::filesystem::path("/sys/dev/char/");
215 sysfsPath /= std::to_string(major_num) + ":" + std::to_string(minor_num);
216 sysfsPath = std::filesystem::canonical(sysfsPath, errorCode);
217
218 // Make sure nothing went wrong in call to canonical()
219 if (errorCode) {
220 ALOGW("Could not run filesystem::canonical() due to error %d : %s.", errorCode.value(),
221 errorCode.message().c_str());
Chris Ye3fdbfef2021-01-06 18:45:18 -0800222 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800223 }
224
225 // Continue to go up a directory until we reach a directory named "input"
226 while (sysfsPath != "/" && sysfsPath.filename() != "input") {
227 sysfsPath = sysfsPath.parent_path();
228 }
229
230 // Then go up one more and you will be at the sysfs root of the device
231 sysfsPath = sysfsPath.parent_path();
232
233 // Make sure we didn't reach root path and that directory actually exists
234 if (sysfsPath == "/" || !std::filesystem::exists(sysfsPath, errorCode)) {
235 if (errorCode) {
236 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
237 errorCode.message().c_str());
238 }
239
240 // Not found
Chris Ye3fdbfef2021-01-06 18:45:18 -0800241 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800242 }
243
244 return sysfsPath;
245}
246
247/**
Chris Ye3fdbfef2021-01-06 18:45:18 -0800248 * Returns the list of files under a specified path.
Kim Low03ea0352020-11-06 12:45:07 -0800249 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800250static std::vector<std::filesystem::path> allFilesInPath(const std::filesystem::path& path) {
251 std::vector<std::filesystem::path> nodes;
252 std::error_code errorCode;
253 auto iter = std::filesystem::directory_iterator(path, errorCode);
254 while (!errorCode && iter != std::filesystem::directory_iterator()) {
255 nodes.push_back(iter->path());
256 iter++;
257 }
258 return nodes;
259}
260
261/**
262 * Returns the list of files under a specified directory in a sysfs path.
263 * Example:
264 * findSysfsNodes(sysfsRootPath, SysfsClass::LEDS) will return all led nodes under "leds" directory
265 * in the sysfs path.
266 */
267static std::vector<std::filesystem::path> findSysfsNodes(const std::filesystem::path& sysfsRoot,
268 SysfsClass clazz) {
Dominik Laskowski75788452021-02-09 18:51:25 -0800269 std::string nodeStr = ftl::enum_string(clazz);
Chris Ye3fdbfef2021-01-06 18:45:18 -0800270 std::for_each(nodeStr.begin(), nodeStr.end(),
271 [](char& c) { c = std::tolower(static_cast<unsigned char>(c)); });
272 std::vector<std::filesystem::path> nodes;
273 for (auto path = sysfsRoot; path != "/" && nodes.empty(); path = path.parent_path()) {
274 nodes = allFilesInPath(path / nodeStr);
275 }
276 return nodes;
277}
278
279static std::optional<std::array<LightColor, COLOR_NUM>> getColorIndexArray(
280 std::filesystem::path path) {
281 std::string indexStr;
282 if (!base::ReadFileToString(path, &indexStr)) {
283 return std::nullopt;
284 }
285
286 // Parse the multi color LED index file, refer to kernel docs
287 // leds/leds-class-multicolor.html
288 std::regex indexPattern("(red|green|blue)\\s(red|green|blue)\\s(red|green|blue)[\\n]");
289 std::smatch results;
290 std::array<LightColor, COLOR_NUM> colors;
291 if (!std::regex_match(indexStr, results, indexPattern)) {
292 return std::nullopt;
293 }
294
295 for (size_t i = 1; i < results.size(); i++) {
296 const auto it = LIGHT_COLORS.find(results[i].str());
297 if (it != LIGHT_COLORS.end()) {
298 // intensities.emplace(it->second, 0);
299 colors[i - 1] = it->second;
Kim Low03ea0352020-11-06 12:45:07 -0800300 }
301 }
Chris Ye3fdbfef2021-01-06 18:45:18 -0800302 return colors;
Kim Low03ea0352020-11-06 12:45:07 -0800303}
304
Prabir Pradhancb42b472022-08-23 16:01:19 +0000305/**
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000306 * Read country code information exposed through the sysfs path.
307 */
308static InputDeviceCountryCode readCountryCodeLocked(const std::filesystem::path& sysfsRootPath) {
309 // Check the sysfs root path
310 int hidCountryCode = static_cast<int>(InputDeviceCountryCode::INVALID);
311 std::string str;
312 if (base::ReadFileToString(sysfsRootPath / "country", &str)) {
313 hidCountryCode = std::stoi(str, nullptr, 16);
314 LOG_ALWAYS_FATAL_IF(hidCountryCode > 35 || hidCountryCode < 0,
315 "HID country code should be in range [0, 35]. Found country code "
316 "to be %d",
317 hidCountryCode);
318 }
319
320 return static_cast<InputDeviceCountryCode>(hidCountryCode);
321}
322
323/**
Prabir Pradhancb42b472022-08-23 16:01:19 +0000324 * Read information about batteries exposed through the sysfs path.
325 */
326static std::unordered_map<int32_t /*batteryId*/, RawBatteryInfo> readBatteryConfiguration(
327 const std::filesystem::path& sysfsRootPath) {
328 std::unordered_map<int32_t, RawBatteryInfo> batteryInfos;
329 int32_t nextBatteryId = 0;
330 // Check if device has any battery.
331 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::POWER_SUPPLY);
332 for (const auto& nodePath : paths) {
333 RawBatteryInfo info;
334 info.id = ++nextBatteryId;
335 info.path = nodePath;
336 info.name = nodePath.filename();
337
338 // Scan the path for all the files
339 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
340 const auto& files = allFilesInPath(nodePath);
341 for (const auto& file : files) {
342 const auto it = BATTERY_CLASSES.find(file.filename().string());
343 if (it != BATTERY_CLASSES.end()) {
344 info.flags |= it->second;
345 }
346 }
347 batteryInfos.insert_or_assign(info.id, info);
348 ALOGD("configureBatteryLocked rawBatteryId %d name %s", info.id, info.name.c_str());
349 }
350 return batteryInfos;
351}
352
353/**
354 * Read information about lights exposed through the sysfs path.
355 */
356static std::unordered_map<int32_t /*lightId*/, RawLightInfo> readLightsConfiguration(
357 const std::filesystem::path& sysfsRootPath) {
358 std::unordered_map<int32_t, RawLightInfo> lightInfos;
359 int32_t nextLightId = 0;
360 // Check if device has any lights.
361 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::LEDS);
362 for (const auto& nodePath : paths) {
363 RawLightInfo info;
364 info.id = ++nextLightId;
365 info.path = nodePath;
366 info.name = nodePath.filename();
367 info.maxBrightness = std::nullopt;
368 size_t nameStart = info.name.rfind(":");
369 if (nameStart != std::string::npos) {
370 // Trim the name to color name
371 info.name = info.name.substr(nameStart + 1);
372 // Set InputLightClass flag for colors
373 const auto it = LIGHT_CLASSES.find(info.name);
374 if (it != LIGHT_CLASSES.end()) {
375 info.flags |= it->second;
376 }
377 }
378 // Scan the path for all the files
379 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
380 const auto& files = allFilesInPath(nodePath);
381 for (const auto& file : files) {
382 const auto it = LIGHT_CLASSES.find(file.filename().string());
383 if (it != LIGHT_CLASSES.end()) {
384 info.flags |= it->second;
385 // If the node has maximum brightness, read it
386 if (it->second == InputLightClass::MAX_BRIGHTNESS) {
387 std::string str;
388 if (base::ReadFileToString(file, &str)) {
389 info.maxBrightness = std::stoi(str);
390 }
391 }
392 }
393 }
394 lightInfos.insert_or_assign(info.id, info);
395 ALOGD("configureLightsLocked rawLightId %d name %s", info.id, info.name.c_str());
396 }
397 return lightInfos;
398}
399
Michael Wrightd02c5b62014-02-10 15:10:22 -0800400// --- Global Functions ---
401
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700402ftl::Flags<InputDeviceClass> getAbsAxisUsage(int32_t axis,
403 ftl::Flags<InputDeviceClass> deviceClasses) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800404 // Touch devices get dibs on touch-related axes.
Chris Ye1b0c7342020-07-28 21:57:03 -0700405 if (deviceClasses.test(InputDeviceClass::TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800406 switch (axis) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700407 case ABS_X:
408 case ABS_Y:
409 case ABS_PRESSURE:
410 case ABS_TOOL_WIDTH:
411 case ABS_DISTANCE:
412 case ABS_TILT_X:
413 case ABS_TILT_Y:
414 case ABS_MT_SLOT:
415 case ABS_MT_TOUCH_MAJOR:
416 case ABS_MT_TOUCH_MINOR:
417 case ABS_MT_WIDTH_MAJOR:
418 case ABS_MT_WIDTH_MINOR:
419 case ABS_MT_ORIENTATION:
420 case ABS_MT_POSITION_X:
421 case ABS_MT_POSITION_Y:
422 case ABS_MT_TOOL_TYPE:
423 case ABS_MT_BLOB_ID:
424 case ABS_MT_TRACKING_ID:
425 case ABS_MT_PRESSURE:
426 case ABS_MT_DISTANCE:
Chris Ye1b0c7342020-07-28 21:57:03 -0700427 return InputDeviceClass::TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800428 }
429 }
430
Chris Yef59a2f42020-10-16 12:55:26 -0700431 if (deviceClasses.test(InputDeviceClass::SENSOR)) {
432 switch (axis) {
433 case ABS_X:
434 case ABS_Y:
435 case ABS_Z:
436 case ABS_RX:
437 case ABS_RY:
438 case ABS_RZ:
439 return InputDeviceClass::SENSOR;
440 }
441 }
442
Michael Wright842500e2015-03-13 17:32:02 -0700443 // External stylus gets the pressure axis
Chris Ye1b0c7342020-07-28 21:57:03 -0700444 if (deviceClasses.test(InputDeviceClass::EXTERNAL_STYLUS)) {
Michael Wright842500e2015-03-13 17:32:02 -0700445 if (axis == ABS_PRESSURE) {
Chris Ye1b0c7342020-07-28 21:57:03 -0700446 return InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -0700447 }
448 }
449
Michael Wrightd02c5b62014-02-10 15:10:22 -0800450 // Joystick devices get the rest.
Chris Ye1b0c7342020-07-28 21:57:03 -0700451 return deviceClasses & InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800452}
453
454// --- EventHub::Device ---
455
Prabir Pradhancb42b472022-08-23 16:01:19 +0000456EventHub::Device::Device(int fd, int32_t id, std::string path, InputDeviceIdentifier identifier,
457 std::shared_ptr<const AssociatedDevice> assocDev)
Chris Ye989bb932020-07-04 16:18:59 -0700458 : fd(fd),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700459 id(id),
Prabir Pradhancb42b472022-08-23 16:01:19 +0000460 path(std::move(path)),
461 identifier(std::move(identifier)),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700462 classes(0),
463 configuration(nullptr),
464 virtualKeyMap(nullptr),
465 ffEffectPlaying(false),
466 ffEffectId(-1),
Prabir Pradhancb42b472022-08-23 16:01:19 +0000467 associatedDevice(std::move(assocDev)),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700468 controllerNumber(0),
469 enabled(true),
Chris Ye66fbac32020-07-06 20:36:43 -0700470 isVirtual(fd < 0) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800471
472EventHub::Device::~Device() {
473 close();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800474}
475
476void EventHub::Device::close() {
477 if (fd >= 0) {
478 ::close(fd);
479 fd = -1;
480 }
481}
482
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700483status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100484 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700485 if (fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100486 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700487 return -errno;
488 }
489 enabled = true;
490 return OK;
491}
492
493status_t EventHub::Device::disable() {
494 close();
495 enabled = false;
496 return OK;
497}
498
Chris Ye989bb932020-07-04 16:18:59 -0700499bool EventHub::Device::hasValidFd() const {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700500 return !isVirtual && enabled;
501}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800502
Chris Ye3a1e4462020-08-12 10:13:15 -0700503const std::shared_ptr<KeyCharacterMap> EventHub::Device::getKeyCharacterMap() const {
Chris Ye989bb932020-07-04 16:18:59 -0700504 return keyMap.keyCharacterMap;
505}
506
507template <std::size_t N>
508status_t EventHub::Device::readDeviceBitMask(unsigned long ioctlCode, BitArray<N>& bitArray) {
509 if (!hasValidFd()) {
510 return BAD_VALUE;
511 }
512 if ((_IOC_SIZE(ioctlCode) == 0)) {
513 ioctlCode |= _IOC(0, 0, 0, bitArray.bytes());
514 }
515
516 typename BitArray<N>::Buffer buffer;
517 status_t ret = ioctl(fd, ioctlCode, buffer.data());
518 bitArray.loadFromBuffer(buffer);
519 return ret;
520}
521
522void EventHub::Device::configureFd() {
523 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
524 if (classes.test(InputDeviceClass::KEYBOARD)) {
525 // Disable kernel key repeat since we handle it ourselves
526 unsigned int repeatRate[] = {0, 0};
527 if (ioctl(fd, EVIOCSREP, repeatRate)) {
528 ALOGW("Unable to disable kernel key repeat for %s: %s", path.c_str(), strerror(errno));
529 }
530 }
531
532 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
533 // associated with input events. This is important because the input system
534 // uses the timestamps extensively and assumes they were recorded using the monotonic
535 // clock.
536 int clockId = CLOCK_MONOTONIC;
Chris Yef59a2f42020-10-16 12:55:26 -0700537 if (classes.test(InputDeviceClass::SENSOR)) {
538 // Each new sensor event should use the same time base as
539 // SystemClock.elapsedRealtimeNanos().
540 clockId = CLOCK_BOOTTIME;
541 }
Chris Ye989bb932020-07-04 16:18:59 -0700542 bool usingClockIoctl = !ioctl(fd, EVIOCSCLOCKID, &clockId);
543 ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
544}
545
546bool EventHub::Device::hasKeycodeLocked(int keycode) const {
547 if (!keyMap.haveKeyLayout()) {
548 return false;
549 }
550
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700551 std::vector<int32_t> scanCodes = keyMap.keyLayoutMap->findScanCodesForKey(keycode);
Chris Ye989bb932020-07-04 16:18:59 -0700552 const size_t N = scanCodes.size();
553 for (size_t i = 0; i < N && i <= KEY_MAX; i++) {
554 int32_t sc = scanCodes[i];
555 if (sc >= 0 && sc <= KEY_MAX && keyBitmask.test(sc)) {
556 return true;
557 }
558 }
559
560 return false;
561}
562
563void EventHub::Device::loadConfigurationLocked() {
564 configurationFile =
565 getInputDeviceConfigurationFilePathByDeviceIdentifier(identifier,
566 InputDeviceConfigurationFileType::
567 CONFIGURATION);
568 if (configurationFile.empty()) {
569 ALOGD("No input device configuration file found for device '%s'.", identifier.name.c_str());
570 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500571 android::base::Result<std::unique_ptr<PropertyMap>> propertyMap =
572 PropertyMap::load(configurationFile.c_str());
573 if (!propertyMap.ok()) {
Chris Ye989bb932020-07-04 16:18:59 -0700574 ALOGE("Error loading input device configuration file for device '%s'. "
575 "Using default configuration.",
576 identifier.name.c_str());
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500577 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500578 configuration = std::move(*propertyMap);
Chris Ye989bb932020-07-04 16:18:59 -0700579 }
580 }
581}
582
583bool EventHub::Device::loadVirtualKeyMapLocked() {
584 // The virtual key map is supplied by the kernel as a system board property file.
585 std::string propPath = "/sys/board_properties/virtualkeys.";
586 propPath += identifier.getCanonicalName();
587 if (access(propPath.c_str(), R_OK)) {
588 return false;
589 }
590 virtualKeyMap = VirtualKeyMap::load(propPath);
591 return virtualKeyMap != nullptr;
592}
593
594status_t EventHub::Device::loadKeyMapLocked() {
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500595 return keyMap.load(identifier, configuration.get());
Chris Ye989bb932020-07-04 16:18:59 -0700596}
597
598bool EventHub::Device::isExternalDeviceLocked() {
599 if (configuration) {
600 bool value;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700601 if (configuration->tryGetProperty("device.internal", value)) {
Chris Ye989bb932020-07-04 16:18:59 -0700602 return !value;
603 }
604 }
605 return identifier.bus == BUS_USB || identifier.bus == BUS_BLUETOOTH;
606}
607
608bool EventHub::Device::deviceHasMicLocked() {
609 if (configuration) {
610 bool value;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700611 if (configuration->tryGetProperty("audio.mic", value)) {
Chris Ye989bb932020-07-04 16:18:59 -0700612 return value;
613 }
614 }
615 return false;
616}
617
618void EventHub::Device::setLedStateLocked(int32_t led, bool on) {
619 int32_t sc;
620 if (hasValidFd() && mapLed(led, &sc) != NAME_NOT_FOUND) {
621 struct input_event ev;
622 ev.time.tv_sec = 0;
623 ev.time.tv_usec = 0;
624 ev.type = EV_LED;
625 ev.code = sc;
626 ev.value = on ? 1 : 0;
627
628 ssize_t nWrite;
629 do {
630 nWrite = write(fd, &ev, sizeof(struct input_event));
631 } while (nWrite == -1 && errno == EINTR);
632 }
633}
634
635void EventHub::Device::setLedForControllerLocked() {
636 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
637 setLedStateLocked(ALED_CONTROLLER_1 + i, controllerNumber == i + 1);
638 }
639}
640
641status_t EventHub::Device::mapLed(int32_t led, int32_t* outScanCode) const {
642 if (!keyMap.haveKeyLayout()) {
643 return NAME_NOT_FOUND;
644 }
645
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700646 std::optional<int32_t> scanCode = keyMap.keyLayoutMap->findScanCodeForLed(led);
647 if (scanCode.has_value()) {
648 if (*scanCode >= 0 && *scanCode <= LED_MAX && ledBitmask.test(*scanCode)) {
649 *outScanCode = *scanCode;
Chris Ye989bb932020-07-04 16:18:59 -0700650 return NO_ERROR;
651 }
652 }
653 return NAME_NOT_FOUND;
654}
655
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100656/**
657 * Get the capabilities for the current process.
658 * Crashes the system if unable to create / check / destroy the capabilities object.
659 */
660class Capabilities final {
661public:
662 explicit Capabilities() {
663 mCaps = cap_get_proc();
664 LOG_ALWAYS_FATAL_IF(mCaps == nullptr, "Could not get capabilities of the current process");
665 }
666
667 /**
668 * Check whether the current process has a specific capability
669 * in the set of effective capabilities.
670 * Return CAP_SET if the process has the requested capability
671 * Return CAP_CLEAR otherwise.
672 */
673 cap_flag_value_t checkEffectiveCapability(cap_value_t capability) {
674 cap_flag_value_t value;
675 const int result = cap_get_flag(mCaps, capability, CAP_EFFECTIVE, &value);
676 LOG_ALWAYS_FATAL_IF(result == -1, "Could not obtain the requested capability");
677 return value;
678 }
679
680 ~Capabilities() {
681 const int result = cap_free(mCaps);
682 LOG_ALWAYS_FATAL_IF(result == -1, "Could not release the capabilities structure");
683 }
684
685private:
686 cap_t mCaps;
687};
688
689static void ensureProcessCanBlockSuspend() {
690 Capabilities capabilities;
691 const bool canBlockSuspend =
692 capabilities.checkEffectiveCapability(CAP_BLOCK_SUSPEND) == CAP_SET;
693 LOG_ALWAYS_FATAL_IF(!canBlockSuspend,
694 "Input must be able to block suspend to properly process events");
695}
696
Michael Wrightd02c5b62014-02-10 15:10:22 -0800697// --- EventHub ---
698
Michael Wrightd02c5b62014-02-10 15:10:22 -0800699const int EventHub::EPOLL_MAX_EVENTS;
700
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700701EventHub::EventHub(void)
702 : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
703 mNextDeviceId(1),
704 mControllerNumbers(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800705 mNeedToSendFinishedDeviceScan(false),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700706 mNeedToReopenDevices(false),
707 mNeedToScanDevices(true),
708 mPendingEventCount(0),
709 mPendingEventIndex(0),
710 mPendingINotify(false) {
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100711 ensureProcessCanBlockSuspend();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800712
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800713 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800714 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800715
Michael Wright8e9a8562022-02-09 13:44:29 +0000716 mINotifyFd = inotify_init1(IN_CLOEXEC);
Prabir Pradhan952e65b2022-06-23 17:49:55 +0000717 LOG_ALWAYS_FATAL_IF(mINotifyFd < 0, "Could not create inotify instance: %s", strerror(errno));
Usama Arifb27c8e62021-06-03 16:44:09 +0100718
719 std::error_code errorCode;
720 bool isDeviceInotifyAdded = false;
721 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
722 addDeviceInputInotify();
Philip Quinn39b81682019-01-09 22:20:39 -0800723 } else {
Usama Arifb27c8e62021-06-03 16:44:09 +0100724 addDeviceInotify();
725 isDeviceInotifyAdded = true;
726 if (errorCode) {
727 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
728 errorCode.message().c_str());
729 }
730 }
731
732 if (isV4lScanningEnabled() && !isDeviceInotifyAdded) {
733 addDeviceInotify();
734 } else {
Philip Quinn39b81682019-01-09 22:20:39 -0800735 ALOGI("Video device scanning disabled");
736 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800737
Siarhei Vishniakou2d0e9482019-09-24 12:52:47 +0100738 struct epoll_event eventItem = {};
739 eventItem.events = EPOLLIN | EPOLLWAKEUP;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700740 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800741 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800742 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
743
744 int wakeFds[2];
Michael Wright8e9a8562022-02-09 13:44:29 +0000745 result = pipe2(wakeFds, O_CLOEXEC);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800746 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
747
748 mWakeReadPipeFd = wakeFds[0];
749 mWakeWritePipeFd = wakeFds[1];
750
751 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
752 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700753 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800754
755 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
756 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700757 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800758
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700759 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800760 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
761 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700762 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800763}
764
765EventHub::~EventHub(void) {
766 closeAllDevicesLocked();
767
Michael Wrightd02c5b62014-02-10 15:10:22 -0800768 ::close(mEpollFd);
769 ::close(mINotifyFd);
770 ::close(mWakeReadPipeFd);
771 ::close(mWakeWritePipeFd);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800772}
773
Usama Arifb27c8e62021-06-03 16:44:09 +0100774/**
775 * On devices that don't have any input devices (like some development boards), the /dev/input
776 * directory will be absent. However, the user may still plug in an input device at a later time.
777 * Add watch for contents of /dev/input only when /dev/input appears.
778 */
779void EventHub::addDeviceInputInotify() {
780 mDeviceInputWd = inotify_add_watch(mINotifyFd, DEVICE_INPUT_PATH, IN_DELETE | IN_CREATE);
781 LOG_ALWAYS_FATAL_IF(mDeviceInputWd < 0, "Could not register INotify for %s: %s",
782 DEVICE_INPUT_PATH, strerror(errno));
783}
784
785void EventHub::addDeviceInotify() {
786 mDeviceWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
787 LOG_ALWAYS_FATAL_IF(mDeviceWd < 0, "Could not register INotify for %s: %s", DEVICE_PATH,
788 strerror(errno));
789}
790
Michael Wrightd02c5b62014-02-10 15:10:22 -0800791InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000792 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800793 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700794 return device != nullptr ? device->identifier : InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800795}
796
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700797ftl::Flags<InputDeviceClass> EventHub::getDeviceClasses(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000798 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800799 Device* device = getDeviceLocked(deviceId);
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700800 return device != nullptr ? device->classes : ftl::Flags<InputDeviceClass>(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800801}
802
803int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000804 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800805 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700806 return device != nullptr ? device->controllerNumber : 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800807}
808
809void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
Chris Ye87143712020-11-10 05:05:58 +0000810 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800811 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700812 if (device != nullptr && device->configuration) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800813 *outConfiguration = *device->configuration;
814 } else {
815 outConfiguration->clear();
816 }
817}
818
819status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700820 RawAbsoluteAxisInfo* outAxisInfo) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800821 outAxisInfo->clear();
822
823 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000824 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800825
826 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700827 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800828 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700829 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
830 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
831 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800832 return -errno;
833 }
834
835 if (info.minimum != info.maximum) {
836 outAxisInfo->valid = true;
837 outAxisInfo->minValue = info.minimum;
838 outAxisInfo->maxValue = info.maximum;
839 outAxisInfo->flat = info.flat;
840 outAxisInfo->fuzz = info.fuzz;
841 outAxisInfo->resolution = info.resolution;
842 }
843 return OK;
844 }
845 }
846 return -1;
847}
848
849bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
850 if (axis >= 0 && axis <= REL_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000851 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800852 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700853 return device != nullptr ? device->relBitmask.test(axis) : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800854 }
855 return false;
856}
857
858bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
Chris Ye87143712020-11-10 05:05:58 +0000859 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800860
Chris Ye989bb932020-07-04 16:18:59 -0700861 Device* device = getDeviceLocked(deviceId);
862 return property >= 0 && property <= INPUT_PROP_MAX && device != nullptr
863 ? device->propBitmask.test(property)
864 : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800865}
866
Chris Yef59a2f42020-10-16 12:55:26 -0700867bool EventHub::hasMscEvent(int32_t deviceId, int mscEvent) const {
868 std::scoped_lock _l(mLock);
869
870 Device* device = getDeviceLocked(deviceId);
871 return mscEvent >= 0 && mscEvent <= MSC_MAX && device != nullptr
872 ? device->mscBitmask.test(mscEvent)
873 : false;
874}
875
Michael Wrightd02c5b62014-02-10 15:10:22 -0800876int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
877 if (scanCode >= 0 && scanCode <= KEY_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000878 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800879
880 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700881 if (device != nullptr && device->hasValidFd() && device->keyBitmask.test(scanCode)) {
882 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
883 return device->keyState.test(scanCode) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800884 }
885 }
886 }
887 return AKEY_STATE_UNKNOWN;
888}
889
890int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
Chris Ye87143712020-11-10 05:05:58 +0000891 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800892
893 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700894 if (device != nullptr && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700895 std::vector<int32_t> scanCodes = device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800896 if (scanCodes.size() != 0) {
Chris Ye66fbac32020-07-06 20:36:43 -0700897 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800898 for (size_t i = 0; i < scanCodes.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800899 int32_t sc = scanCodes[i];
Chris Ye66fbac32020-07-06 20:36:43 -0700900 if (sc >= 0 && sc <= KEY_MAX && device->keyState.test(sc)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800901 return AKEY_STATE_DOWN;
902 }
903 }
904 return AKEY_STATE_UP;
905 }
906 }
907 }
908 return AKEY_STATE_UNKNOWN;
909}
910
Philip Junker4af3b3d2021-12-14 10:36:55 +0100911int32_t EventHub::getKeyCodeForKeyLocation(int32_t deviceId, int32_t locationKeyCode) const {
912 std::scoped_lock _l(mLock);
913
914 Device* device = getDeviceLocked(deviceId);
915 if (device == nullptr || !device->hasValidFd() || device->keyMap.keyCharacterMap == nullptr ||
916 device->keyMap.keyLayoutMap == nullptr) {
917 return AKEYCODE_UNKNOWN;
918 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700919 std::vector<int32_t> scanCodes =
920 device->keyMap.keyLayoutMap->findScanCodesForKey(locationKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +0100921 if (scanCodes.empty()) {
922 ALOGW("Failed to get key code for key location: no scan code maps to key code %d for input"
923 "device %d",
924 locationKeyCode, deviceId);
925 return AKEYCODE_UNKNOWN;
926 }
927 if (scanCodes.size() > 1) {
928 ALOGW("Multiple scan codes map to the same key code %d, returning only the first match",
929 locationKeyCode);
930 }
931 int32_t outKeyCode;
932 status_t mapKeyRes =
933 device->getKeyCharacterMap()->mapKey(scanCodes[0], 0 /*usageCode*/, &outKeyCode);
934 switch (mapKeyRes) {
935 case OK:
936 return outKeyCode;
937 case NAME_NOT_FOUND:
938 // key character map doesn't re-map this scanCode, hence the keyCode remains the same
939 return locationKeyCode;
940 default:
941 ALOGW("Failed to get key code for key location: Key character map returned error %s",
942 statusToString(mapKeyRes).c_str());
943 return AKEYCODE_UNKNOWN;
944 }
945}
946
Michael Wrightd02c5b62014-02-10 15:10:22 -0800947int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
948 if (sw >= 0 && sw <= SW_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000949 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800950
951 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700952 if (device != nullptr && device->hasValidFd() && device->swBitmask.test(sw)) {
953 if (device->readDeviceBitMask(EVIOCGSW(0), device->swState) >= 0) {
954 return device->swState.test(sw) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800955 }
956 }
957 }
958 return AKEY_STATE_UNKNOWN;
959}
960
961status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
962 *outValue = 0;
963
964 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000965 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800966
967 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700968 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800969 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700970 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
971 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
972 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800973 return -errno;
974 }
975
976 *outValue = info.value;
977 return OK;
978 }
979 }
980 return -1;
981}
982
Siarhei Vishniakou74007942022-06-13 13:57:47 -0700983bool EventHub::markSupportedKeyCodes(int32_t deviceId, const std::vector<int32_t>& keyCodes,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700984 uint8_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +0000985 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800986
987 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700988 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -0700989 for (size_t codeIndex = 0; codeIndex < keyCodes.size(); codeIndex++) {
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700990 std::vector<int32_t> scanCodes =
991 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCodes[codeIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800992
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700993 // check the possible scan codes identified by the layout map against the
994 // map of codes actually emitted by the driver
Siarhei Vishniakou74007942022-06-13 13:57:47 -0700995 for (const int32_t scanCode : scanCodes) {
996 if (device->keyBitmask.test(scanCode)) {
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700997 outFlags[codeIndex] = 1;
998 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800999 }
1000 }
1001 }
1002 return true;
1003 }
1004 return false;
1005}
1006
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001007status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
1008 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +00001009 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001010 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001011 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001012
Chris Ye66fbac32020-07-06 20:36:43 -07001013 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001014 // Check the key character map first.
Chris Ye3a1e4462020-08-12 10:13:15 -07001015 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
1016 if (kcm) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001017 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
1018 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001019 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001020 }
1021 }
1022
1023 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001024 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -08001025 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001026 status = NO_ERROR;
1027 }
1028 }
1029
1030 if (status == NO_ERROR) {
Chris Ye3a1e4462020-08-12 10:13:15 -07001031 if (kcm) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001032 kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState);
1033 } else {
1034 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001035 }
1036 }
1037 }
1038
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001039 if (status != NO_ERROR) {
1040 *outKeycode = 0;
1041 *outFlags = 0;
1042 *outMetaState = metaState;
1043 }
1044
1045 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001046}
1047
1048status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
Chris Ye87143712020-11-10 05:05:58 +00001049 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001050 Device* device = getDeviceLocked(deviceId);
1051
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001052 if (device == nullptr || !device->keyMap.haveKeyLayout()) {
1053 return NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001054 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001055 std::optional<AxisInfo> info = device->keyMap.keyLayoutMap->mapAxis(scanCode);
1056 if (!info.has_value()) {
1057 return NAME_NOT_FOUND;
1058 }
1059 *outAxisInfo = *info;
1060 return NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001061}
1062
Chris Yef59a2f42020-10-16 12:55:26 -07001063base::Result<std::pair<InputDeviceSensorType, int32_t>> EventHub::mapSensor(int32_t deviceId,
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001064 int32_t absCode) const {
Chris Yef59a2f42020-10-16 12:55:26 -07001065 std::scoped_lock _l(mLock);
1066 Device* device = getDeviceLocked(deviceId);
1067
1068 if (device != nullptr && device->keyMap.haveKeyLayout()) {
1069 return device->keyMap.keyLayoutMap->mapSensor(absCode);
1070 }
1071 return Errorf("Device not found or device has no key layout.");
1072}
1073
Chris Yee2b1e5c2021-03-10 22:45:12 -08001074// Gets the battery info map from battery ID to RawBatteryInfo of the miscellaneous device
1075// associated with the device ID. Returns an empty map if no miscellaneous device found.
1076const std::unordered_map<int32_t, RawBatteryInfo>& EventHub::getBatteryInfoLocked(
1077 int32_t deviceId) const {
1078 static const std::unordered_map<int32_t, RawBatteryInfo> EMPTY_BATTERY_INFO = {};
1079 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001080 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001081 return EMPTY_BATTERY_INFO;
1082 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001083 return device->associatedDevice->batteryInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001084}
1085
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001086std::vector<int32_t> EventHub::getRawBatteryIds(int32_t deviceId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001087 std::scoped_lock _l(mLock);
1088 std::vector<int32_t> batteryIds;
1089
Prabir Pradhan51894782022-08-23 16:29:10 +00001090 for (const auto& [id, info] : getBatteryInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001091 batteryIds.push_back(id);
1092 }
1093
1094 return batteryIds;
1095}
1096
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001097std::optional<RawBatteryInfo> EventHub::getRawBatteryInfo(int32_t deviceId,
1098 int32_t batteryId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001099 std::scoped_lock _l(mLock);
1100
1101 const auto infos = getBatteryInfoLocked(deviceId);
1102
1103 auto it = infos.find(batteryId);
1104 if (it != infos.end()) {
1105 return it->second;
1106 }
1107
1108 return std::nullopt;
1109}
1110
1111// Gets the light info map from light ID to RawLightInfo of the miscellaneous device associated
Prabir Pradhan51894782022-08-23 16:29:10 +00001112// with the device ID. Returns an empty map if no miscellaneous device found.
Chris Yee2b1e5c2021-03-10 22:45:12 -08001113const std::unordered_map<int32_t, RawLightInfo>& EventHub::getLightInfoLocked(
1114 int32_t deviceId) const {
1115 static const std::unordered_map<int32_t, RawLightInfo> EMPTY_LIGHT_INFO = {};
1116 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001117 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001118 return EMPTY_LIGHT_INFO;
1119 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001120 return device->associatedDevice->lightInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001121}
1122
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001123std::vector<int32_t> EventHub::getRawLightIds(int32_t deviceId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001124 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001125 std::vector<int32_t> lightIds;
1126
Prabir Pradhan51894782022-08-23 16:29:10 +00001127 for (const auto& [id, info] : getLightInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001128 lightIds.push_back(id);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001129 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001130
Chris Ye3fdbfef2021-01-06 18:45:18 -08001131 return lightIds;
1132}
1133
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001134std::optional<RawLightInfo> EventHub::getRawLightInfo(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001135 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001136
Chris Yee2b1e5c2021-03-10 22:45:12 -08001137 const auto infos = getLightInfoLocked(deviceId);
1138
1139 auto it = infos.find(lightId);
1140 if (it != infos.end()) {
1141 return it->second;
Chris Ye3fdbfef2021-01-06 18:45:18 -08001142 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001143
Chris Ye3fdbfef2021-01-06 18:45:18 -08001144 return std::nullopt;
1145}
1146
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001147std::optional<int32_t> EventHub::getLightBrightness(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001148 std::scoped_lock _l(mLock);
1149
Chris Yee2b1e5c2021-03-10 22:45:12 -08001150 const auto infos = getLightInfoLocked(deviceId);
1151 auto it = infos.find(lightId);
1152 if (it == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001153 return std::nullopt;
1154 }
1155 std::string buffer;
1156 if (!base::ReadFileToString(it->second.path / LIGHT_NODES.at(InputLightClass::BRIGHTNESS),
1157 &buffer)) {
1158 return std::nullopt;
1159 }
1160 return std::stoi(buffer);
1161}
1162
1163std::optional<std::unordered_map<LightColor, int32_t>> EventHub::getLightIntensities(
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001164 int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001165 std::scoped_lock _l(mLock);
1166
Chris Yee2b1e5c2021-03-10 22:45:12 -08001167 const auto infos = getLightInfoLocked(deviceId);
1168 auto lightIt = infos.find(lightId);
1169 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001170 return std::nullopt;
1171 }
1172
1173 auto ret =
1174 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1175
1176 if (!ret.has_value()) {
1177 return std::nullopt;
1178 }
1179 std::array<LightColor, COLOR_NUM> colors = ret.value();
1180
1181 std::string intensityStr;
1182 if (!base::ReadFileToString(lightIt->second.path /
1183 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY),
1184 &intensityStr)) {
1185 return std::nullopt;
1186 }
1187
1188 // Intensity node outputs 3 color values
1189 std::regex intensityPattern("([0-9]+)\\s([0-9]+)\\s([0-9]+)[\\n]");
1190 std::smatch results;
1191
1192 if (!std::regex_match(intensityStr, results, intensityPattern)) {
1193 return std::nullopt;
1194 }
1195 std::unordered_map<LightColor, int32_t> intensities;
1196 for (size_t i = 1; i < results.size(); i++) {
1197 int value = std::stoi(results[i].str());
1198 intensities.emplace(colors[i - 1], value);
1199 }
1200 return intensities;
1201}
1202
1203void EventHub::setLightBrightness(int32_t deviceId, int32_t lightId, int32_t brightness) {
1204 std::scoped_lock _l(mLock);
1205
Chris Yee2b1e5c2021-03-10 22:45:12 -08001206 const auto infos = getLightInfoLocked(deviceId);
1207 auto lightIt = infos.find(lightId);
1208 if (lightIt == infos.end()) {
1209 ALOGE("%s lightId %d not found ", __func__, lightId);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001210 return;
1211 }
1212
1213 if (!base::WriteStringToFile(std::to_string(brightness),
1214 lightIt->second.path /
1215 LIGHT_NODES.at(InputLightClass::BRIGHTNESS))) {
1216 ALOGE("Can not write to file, error: %s", strerror(errno));
1217 }
1218}
1219
1220void EventHub::setLightIntensities(int32_t deviceId, int32_t lightId,
1221 std::unordered_map<LightColor, int32_t> intensities) {
1222 std::scoped_lock _l(mLock);
1223
Chris Yee2b1e5c2021-03-10 22:45:12 -08001224 const auto infos = getLightInfoLocked(deviceId);
1225 auto lightIt = infos.find(lightId);
1226 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001227 ALOGE("Light Id %d does not exist.", lightId);
1228 return;
1229 }
1230
1231 auto ret =
1232 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1233
1234 if (!ret.has_value()) {
1235 return;
1236 }
1237 std::array<LightColor, COLOR_NUM> colors = ret.value();
1238
1239 std::string rgbStr;
1240 for (size_t i = 0; i < COLOR_NUM; i++) {
1241 auto it = intensities.find(colors[i]);
1242 if (it != intensities.end()) {
1243 rgbStr += std::to_string(it->second);
1244 // Insert space between colors
1245 if (i < COLOR_NUM - 1) {
1246 rgbStr += " ";
1247 }
1248 }
1249 }
1250 // Append new line
1251 rgbStr += "\n";
1252
1253 if (!base::WriteStringToFile(rgbStr,
1254 lightIt->second.path /
1255 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY))) {
1256 ALOGE("Can not write to file, error: %s", strerror(errno));
1257 }
1258}
1259
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001260InputDeviceCountryCode EventHub::getCountryCode(int32_t deviceId) const {
1261 std::scoped_lock _l(mLock);
1262 Device* device = getDeviceLocked(deviceId);
1263 if (device == nullptr || !device->associatedDevice) {
1264 return InputDeviceCountryCode::INVALID;
1265 }
1266 return device->associatedDevice->countryCode;
1267}
1268
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001269void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Chris Ye87143712020-11-10 05:05:58 +00001270 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001271
1272 mExcludedDevices = devices;
1273}
1274
1275bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
Chris Ye87143712020-11-10 05:05:58 +00001276 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001277 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001278 if (device != nullptr && scanCode >= 0 && scanCode <= KEY_MAX) {
1279 return device->keyBitmask.test(scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001280 }
1281 return false;
1282}
1283
Arthur Hungcb40a002021-08-03 14:31:01 +00001284bool EventHub::hasKeyCode(int32_t deviceId, int32_t keyCode) const {
1285 std::scoped_lock _l(mLock);
1286 Device* device = getDeviceLocked(deviceId);
1287 if (device != nullptr) {
1288 return device->hasKeycodeLocked(keyCode);
1289 }
1290 return false;
1291}
1292
Michael Wrightd02c5b62014-02-10 15:10:22 -08001293bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
Chris Ye87143712020-11-10 05:05:58 +00001294 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001295 Device* device = getDeviceLocked(deviceId);
1296 int32_t sc;
Chris Ye989bb932020-07-04 16:18:59 -07001297 if (device != nullptr && device->mapLed(led, &sc) == NO_ERROR) {
Chris Ye66fbac32020-07-06 20:36:43 -07001298 return device->ledBitmask.test(sc);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001299 }
1300 return false;
1301}
1302
1303void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
Chris Ye87143712020-11-10 05:05:58 +00001304 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001305 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -07001306 if (device != nullptr && device->hasValidFd()) {
1307 device->setLedStateLocked(led, on);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001308 }
1309}
1310
1311void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001312 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001313 outVirtualKeys.clear();
1314
Chris Ye87143712020-11-10 05:05:58 +00001315 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001316 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001317 if (device != nullptr && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001318 const std::vector<VirtualKeyDefinition> virtualKeys =
1319 device->virtualKeyMap->getVirtualKeys();
1320 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001321 }
1322}
1323
Chris Ye3a1e4462020-08-12 10:13:15 -07001324const std::shared_ptr<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001325 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001326 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001327 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001328 return device->getKeyCharacterMap();
1329 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001330 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001331}
1332
Chris Ye3a1e4462020-08-12 10:13:15 -07001333bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, std::shared_ptr<KeyCharacterMap> map) {
Chris Ye87143712020-11-10 05:05:58 +00001334 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001335 Device* device = getDeviceLocked(deviceId);
Philip Junker90bc9492021-12-10 18:39:42 +01001336 if (device == nullptr || map == nullptr || device->keyMap.keyCharacterMap == nullptr) {
1337 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001338 }
Philip Junker90bc9492021-12-10 18:39:42 +01001339 device->keyMap.keyCharacterMap->combine(*map);
1340 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001341}
1342
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001343static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
1344 std::string rawDescriptor;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001345 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001346 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001347 if (!identifier.uniqueId.empty()) {
1348 rawDescriptor += "uniqueId:";
1349 rawDescriptor += identifier.uniqueId;
Josh Bartel938632f2022-07-19 15:34:22 -05001350 }
1351 if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001352 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001353 }
1354
1355 if (identifier.vendor == 0 && identifier.product == 0) {
1356 // If we don't know the vendor and product id, then the device is probably
1357 // built-in so we need to rely on other information to uniquely identify
1358 // the input device. Usually we try to avoid relying on the device name or
1359 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001360 if (!identifier.name.empty()) {
1361 rawDescriptor += "name:";
1362 rawDescriptor += identifier.name;
1363 } else if (!identifier.location.empty()) {
1364 rawDescriptor += "location:";
1365 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001366 }
1367 }
1368 identifier.descriptor = sha1(rawDescriptor);
1369 return rawDescriptor;
1370}
1371
1372void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
1373 // Compute a device descriptor that uniquely identifies the device.
1374 // The descriptor is assumed to be a stable identifier. Its value should not
1375 // change between reboots, reconnections, firmware updates or new releases
1376 // of Android. In practice we sometimes get devices that cannot be uniquely
1377 // identified. In this case we enforce uniqueness between connected devices.
1378 // Ideally, we also want the descriptor to be short and relatively opaque.
Josh Bartel938632f2022-07-19 15:34:22 -05001379 // Note that we explicitly do not use the path or location for external devices
1380 // as their path or location will change as they are plugged/unplugged or moved
1381 // to different ports. We do fallback to using name and location in the case of
1382 // internal devices which are detected by the vendor and product being 0 in
1383 // generateDescriptor. If two identical descriptors are detected we will fallback
1384 // to using a 'nonce' and incrementing it until the new descriptor no longer has
1385 // a match with any existing descriptors.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001386
1387 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001388 std::string rawDescriptor = generateDescriptor(identifier);
Josh Bartel938632f2022-07-19 15:34:22 -05001389 // Enforce that the generated descriptor is unique.
1390 while (hasDeviceWithDescriptorLocked(identifier.descriptor)) {
1391 identifier.nonce++;
1392 rawDescriptor = generateDescriptor(identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001393 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001394 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001395 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001396}
1397
Prabir Pradhancb42b472022-08-23 16:01:19 +00001398std::shared_ptr<const EventHub::AssociatedDevice> EventHub::obtainAssociatedDeviceLocked(
1399 const std::filesystem::path& devicePath) const {
1400 const std::optional<std::filesystem::path> sysfsRootPathOpt =
1401 getSysfsRootPath(devicePath.c_str());
1402 if (!sysfsRootPathOpt) {
1403 return nullptr;
1404 }
1405
1406 const auto& path = *sysfsRootPathOpt;
1407 for (const auto& [id, dev] : mDevices) {
1408 if (dev->associatedDevice && dev->associatedDevice->sysfsRootPath == path) {
1409 return dev->associatedDevice;
1410 }
1411 }
1412
1413 return std::make_shared<AssociatedDevice>(
1414 AssociatedDevice{.sysfsRootPath = path,
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001415 .countryCode = readCountryCodeLocked(path),
Prabir Pradhancb42b472022-08-23 16:01:19 +00001416 .batteryInfos = readBatteryConfiguration(path),
1417 .lightInfos = readLightsConfiguration(path)});
1418}
1419
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001420void EventHub::vibrate(int32_t deviceId, const VibrationElement& element) {
Chris Ye87143712020-11-10 05:05:58 +00001421 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001422 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001423 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001424 ff_effect effect;
1425 memset(&effect, 0, sizeof(effect));
1426 effect.type = FF_RUMBLE;
1427 effect.id = device->ffEffectId;
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001428 // evdev FF_RUMBLE effect only supports two channels of vibration.
Chris Ye6393a262020-08-04 19:41:36 -07001429 effect.u.rumble.strong_magnitude = element.getMagnitude(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1430 effect.u.rumble.weak_magnitude = element.getMagnitude(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001431 effect.replay.length = element.duration.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001432 effect.replay.delay = 0;
1433 if (ioctl(device->fd, EVIOCSFF, &effect)) {
1434 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001435 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001436 return;
1437 }
1438 device->ffEffectId = effect.id;
1439
1440 struct input_event ev;
1441 ev.time.tv_sec = 0;
1442 ev.time.tv_usec = 0;
1443 ev.type = EV_FF;
1444 ev.code = device->ffEffectId;
1445 ev.value = 1;
1446 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1447 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001448 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001449 return;
1450 }
1451 device->ffEffectPlaying = true;
1452 }
1453}
1454
1455void EventHub::cancelVibrate(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001456 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001457 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001458 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001459 if (device->ffEffectPlaying) {
1460 device->ffEffectPlaying = false;
1461
1462 struct input_event ev;
1463 ev.time.tv_sec = 0;
1464 ev.time.tv_usec = 0;
1465 ev.type = EV_FF;
1466 ev.code = device->ffEffectId;
1467 ev.value = 0;
1468 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1469 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001470 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001471 return;
1472 }
1473 }
1474 }
1475}
1476
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001477std::vector<int32_t> EventHub::getVibratorIds(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001478 std::scoped_lock _l(mLock);
1479 std::vector<int32_t> vibrators;
1480 Device* device = getDeviceLocked(deviceId);
1481 if (device != nullptr && device->hasValidFd() &&
1482 device->classes.test(InputDeviceClass::VIBRATOR)) {
1483 vibrators.push_back(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1484 vibrators.push_back(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
1485 }
1486 return vibrators;
1487}
1488
Josh Bartel938632f2022-07-19 15:34:22 -05001489/**
1490 * Checks both mDevices and mOpeningDevices for a device with the descriptor passed.
1491 */
1492bool EventHub::hasDeviceWithDescriptorLocked(const std::string& descriptor) const {
1493 for (const auto& device : mOpeningDevices) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001494 if (descriptor == device->identifier.descriptor) {
Josh Bartel938632f2022-07-19 15:34:22 -05001495 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001496 }
1497 }
Josh Bartel938632f2022-07-19 15:34:22 -05001498
1499 for (const auto& [id, device] : mDevices) {
1500 if (descriptor == device->identifier.descriptor) {
1501 return true;
1502 }
1503 }
1504 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001505}
1506
1507EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001508 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001509 deviceId = mBuiltInKeyboardId;
1510 }
Chris Ye989bb932020-07-04 16:18:59 -07001511 const auto& it = mDevices.find(deviceId);
1512 return it != mDevices.end() ? it->second.get() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001513}
1514
Chris Ye8594e192020-07-14 10:34:06 -07001515EventHub::Device* EventHub::getDeviceByPathLocked(const std::string& devicePath) const {
Chris Ye989bb932020-07-04 16:18:59 -07001516 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001517 if (device->path == devicePath) {
Chris Ye989bb932020-07-04 16:18:59 -07001518 return device.get();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001519 }
1520 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001521 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001522}
1523
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001524/**
1525 * The file descriptor could be either input device, or a video device (associated with a
1526 * specific input device). Check both cases here, and return the device that this event
1527 * belongs to. Caller can compare the fd's once more to determine event type.
1528 * Looks through all input devices, and only attached video devices. Unattached video
1529 * devices are ignored.
1530 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001531EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
Chris Ye989bb932020-07-04 16:18:59 -07001532 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001533 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001534 // This is an input device event
Chris Ye989bb932020-07-04 16:18:59 -07001535 return device.get();
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001536 }
1537 if (device->videoDevice && device->videoDevice->getFd() == fd) {
1538 // This is a video device event
Chris Ye989bb932020-07-04 16:18:59 -07001539 return device.get();
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001540 }
1541 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001542 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
1543 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001544 return nullptr;
1545}
1546
Chris Yee2b1e5c2021-03-10 22:45:12 -08001547std::optional<int32_t> EventHub::getBatteryCapacity(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001548 std::filesystem::path batteryPath;
1549 {
1550 // Do not read the sysfs node to get the battery state while holding
1551 // the EventHub lock. For some peripheral devices, reading battery state
1552 // can be broken and take 5+ seconds. Holding the lock in this case would
1553 // block all other event processing during this time. For now, we assume this
1554 // call never happens on the InputReader thread and read the sysfs node outside
1555 // the lock to prevent event processing from being blocked by this call.
1556 std::scoped_lock _l(mLock);
Kim Low03ea0352020-11-06 12:45:07 -08001557
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001558 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001559 auto it = infos.find(batteryId);
1560 if (it == infos.end()) {
1561 return std::nullopt;
1562 }
1563 batteryPath = it->second.path;
1564 } // release lock
1565
Chris Yee2b1e5c2021-03-10 22:45:12 -08001566 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001567
1568 // Some devices report battery capacity as an integer through the "capacity" file
Andy Chenf9f1a022022-08-29 20:07:10 -04001569 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001570 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001571 return std::stoi(base::Trim(buffer));
Kim Low03ea0352020-11-06 12:45:07 -08001572 }
1573
1574 // Other devices report capacity as an enum value POWER_SUPPLY_CAPACITY_LEVEL_XXX
1575 // These values are taken from kernel source code include/linux/power_supply.h
Andy Chenf9f1a022022-08-29 20:07:10 -04001576 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY_LEVEL),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001577 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001578 // Remove any white space such as trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001579 const auto levelIt = BATTERY_LEVEL.find(base::Trim(buffer));
1580 if (levelIt != BATTERY_LEVEL.end()) {
1581 return levelIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001582 }
1583 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001584
Kim Low03ea0352020-11-06 12:45:07 -08001585 return std::nullopt;
1586}
1587
Chris Yee2b1e5c2021-03-10 22:45:12 -08001588std::optional<int32_t> EventHub::getBatteryStatus(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001589 std::filesystem::path batteryPath;
1590 {
1591 // Do not read the sysfs node to get the battery state while holding
1592 // the EventHub lock. For some peripheral devices, reading battery state
1593 // can be broken and take 5+ seconds. Holding the lock in this case would
1594 // block all other event processing during this time. For now, we assume this
1595 // call never happens on the InputReader thread and read the sysfs node outside
1596 // the lock to prevent event processing from being blocked by this call.
1597 std::scoped_lock _l(mLock);
1598
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001599 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001600 auto it = infos.find(batteryId);
1601 if (it == infos.end()) {
1602 return std::nullopt;
1603 }
1604 batteryPath = it->second.path;
1605 } // release lock
1606
Chris Yee2b1e5c2021-03-10 22:45:12 -08001607 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001608
Andy Chenf9f1a022022-08-29 20:07:10 -04001609 if (!base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::STATUS),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001610 &buffer)) {
Kim Low03ea0352020-11-06 12:45:07 -08001611 ALOGE("Failed to read sysfs battery info: %s", strerror(errno));
1612 return std::nullopt;
1613 }
1614
Chris Yed1936772021-02-22 10:30:40 -08001615 // Remove white space like trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001616 const auto statusIt = BATTERY_STATUS.find(base::Trim(buffer));
1617 if (statusIt != BATTERY_STATUS.end()) {
1618 return statusIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001619 }
1620
1621 return std::nullopt;
1622}
1623
Michael Wrightd02c5b62014-02-10 15:10:22 -08001624size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
1625 ALOG_ASSERT(bufferSize >= 1);
1626
Chris Ye87143712020-11-10 05:05:58 +00001627 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001628
1629 struct input_event readBuffer[bufferSize];
1630
1631 RawEvent* event = buffer;
1632 size_t capacity = bufferSize;
1633 bool awoken = false;
1634 for (;;) {
1635 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
1636
1637 // Reopen input devices if needed.
1638 if (mNeedToReopenDevices) {
1639 mNeedToReopenDevices = false;
1640
1641 ALOGI("Reopening all input devices due to a configuration change.");
1642
1643 closeAllDevicesLocked();
1644 mNeedToScanDevices = true;
1645 break; // return to the caller before we actually rescan
1646 }
1647
1648 // Report any devices that had last been added/removed.
Chris Ye989bb932020-07-04 16:18:59 -07001649 for (auto it = mClosingDevices.begin(); it != mClosingDevices.end();) {
1650 std::unique_ptr<Device> device = std::move(*it);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001651 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001652 event->when = now;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001653 event->deviceId = (device->id == mBuiltInKeyboardId)
1654 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
1655 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001656 event->type = DEVICE_REMOVED;
1657 event += 1;
Chris Ye989bb932020-07-04 16:18:59 -07001658 it = mClosingDevices.erase(it);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001659 mNeedToSendFinishedDeviceScan = true;
1660 if (--capacity == 0) {
1661 break;
1662 }
1663 }
1664
1665 if (mNeedToScanDevices) {
1666 mNeedToScanDevices = false;
1667 scanDevicesLocked();
1668 mNeedToSendFinishedDeviceScan = true;
1669 }
1670
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001671 while (!mOpeningDevices.empty()) {
1672 std::unique_ptr<Device> device = std::move(*mOpeningDevices.rbegin());
1673 mOpeningDevices.pop_back();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001674 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001675 event->when = now;
1676 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1677 event->type = DEVICE_ADDED;
1678 event += 1;
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001679
1680 // Try to find a matching video device by comparing device names
1681 for (auto it = mUnattachedVideoDevices.begin(); it != mUnattachedVideoDevices.end();
1682 it++) {
1683 std::unique_ptr<TouchVideoDevice>& videoDevice = *it;
Chris Yed3fef462021-03-07 17:10:08 -08001684 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001685 // videoDevice was transferred to 'device'
1686 it = mUnattachedVideoDevices.erase(it);
1687 break;
1688 }
1689 }
1690
1691 auto [dev_it, inserted] = mDevices.insert_or_assign(device->id, std::move(device));
1692 if (!inserted) {
Chris Ye989bb932020-07-04 16:18:59 -07001693 ALOGW("Device id %d exists, replaced.", device->id);
1694 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001695 mNeedToSendFinishedDeviceScan = true;
1696 if (--capacity == 0) {
1697 break;
1698 }
1699 }
1700
1701 if (mNeedToSendFinishedDeviceScan) {
1702 mNeedToSendFinishedDeviceScan = false;
1703 event->when = now;
1704 event->type = FINISHED_DEVICE_SCAN;
1705 event += 1;
1706 if (--capacity == 0) {
1707 break;
1708 }
1709 }
1710
1711 // Grab the next input event.
1712 bool deviceChanged = false;
1713 while (mPendingEventIndex < mPendingEventCount) {
1714 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001715 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001716 if (eventItem.events & EPOLLIN) {
1717 mPendingINotify = true;
1718 } else {
1719 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
1720 }
1721 continue;
1722 }
1723
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001724 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001725 if (eventItem.events & EPOLLIN) {
1726 ALOGV("awoken after wake()");
1727 awoken = true;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001728 char wakeReadBuffer[16];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001729 ssize_t nRead;
1730 do {
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001731 nRead = read(mWakeReadPipeFd, wakeReadBuffer, sizeof(wakeReadBuffer));
1732 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(wakeReadBuffer));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001733 } else {
1734 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001735 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001736 }
1737 continue;
1738 }
1739
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001740 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Chris Ye989bb932020-07-04 16:18:59 -07001741 if (device == nullptr) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001742 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
1743 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001744 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001745 continue;
1746 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001747 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
1748 if (eventItem.events & EPOLLIN) {
1749 size_t numFrames = device->videoDevice->readAndQueueFrames();
1750 if (numFrames == 0) {
1751 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001752 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001753 }
1754 } else if (eventItem.events & EPOLLHUP) {
1755 // TODO(b/121395353) - consider adding EPOLLRDHUP
1756 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001757 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001758 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1759 device->videoDevice = nullptr;
1760 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001761 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1762 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001763 ALOG_ASSERT(!DEBUG);
1764 }
1765 continue;
1766 }
1767 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -08001768 if (eventItem.events & EPOLLIN) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001769 int32_t readSize =
1770 read(device->fd, readBuffer, sizeof(struct input_event) * capacity);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001771 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
1772 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -07001773 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001774 " bufferSize: %zu capacity: %zu errno: %d)\n",
1775 device->fd, readSize, bufferSize, capacity, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001776 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001777 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001778 } else if (readSize < 0) {
1779 if (errno != EAGAIN && errno != EINTR) {
1780 ALOGW("could not get event (errno=%d)", errno);
1781 }
1782 } else if ((readSize % sizeof(struct input_event)) != 0) {
1783 ALOGE("could not get event (wrong size: %d)", readSize);
1784 } else {
1785 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1786
1787 size_t count = size_t(readSize) / sizeof(struct input_event);
1788 for (size_t i = 0; i < count; i++) {
1789 struct input_event& iev = readBuffer[i];
Siarhei Vishniakou592bac22018-11-08 19:42:38 -08001790 event->when = processEventTimestamp(iev);
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001791 event->readTime = systemTime(SYSTEM_TIME_MONOTONIC);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001792 event->deviceId = deviceId;
1793 event->type = iev.type;
1794 event->code = iev.code;
1795 event->value = iev.value;
1796 event += 1;
1797 capacity -= 1;
1798 }
1799 if (capacity == 0) {
1800 // The result buffer is full. Reset the pending event index
1801 // so we will try to read the device again on the next iteration.
1802 mPendingEventIndex -= 1;
1803 break;
1804 }
1805 }
1806 } else if (eventItem.events & EPOLLHUP) {
1807 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001808 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001809 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001810 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001811 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001812 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1813 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001814 }
1815 }
1816
1817 // readNotify() will modify the list of devices so this must be done after
1818 // processing all other events to ensure that we read all remaining events
1819 // before closing the devices.
1820 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
1821 mPendingINotify = false;
Prabir Pradhan952e65b2022-06-23 17:49:55 +00001822 const auto res = readNotifyLocked();
1823 if (!res.ok()) {
1824 ALOGW("Failed to read from inotify: %s", res.error().message().c_str());
1825 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001826 deviceChanged = true;
1827 }
1828
1829 // Report added or removed devices immediately.
1830 if (deviceChanged) {
1831 continue;
1832 }
1833
1834 // Return now if we have collected any events or if we were explicitly awoken.
1835 if (event != buffer || awoken) {
1836 break;
1837 }
1838
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001839 // Poll for events.
1840 // When a device driver has pending (unread) events, it acquires
1841 // a kernel wake lock. Once the last pending event has been read, the device
1842 // driver will release the kernel wake lock, but the epoll will hold the wakelock,
1843 // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
1844 // is called again for the same fd that produced the event.
1845 // Thus the system can only sleep if there are no events pending or
1846 // currently being processed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001847 //
1848 // The timeout is advisory only. If the device is asleep, it will not wake just to
1849 // service the timeout.
1850 mPendingEventIndex = 0;
1851
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001852 mLock.unlock(); // release lock before poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001853
1854 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1855
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001856 mLock.lock(); // reacquire lock after poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001857
1858 if (pollResult == 0) {
1859 // Timed out.
1860 mPendingEventCount = 0;
1861 break;
1862 }
1863
1864 if (pollResult < 0) {
1865 // An error occurred.
1866 mPendingEventCount = 0;
1867
1868 // Sleep after errors to avoid locking up the system.
1869 // Hopefully the error is transient.
1870 if (errno != EINTR) {
1871 ALOGW("poll failed (errno=%d)\n", errno);
1872 usleep(100000);
1873 }
1874 } else {
1875 // Some events occurred.
1876 mPendingEventCount = size_t(pollResult);
1877 }
1878 }
1879
1880 // All done, return the number of events we read.
1881 return event - buffer;
1882}
1883
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001884std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001885 std::scoped_lock _l(mLock);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001886
1887 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001888 if (device == nullptr || !device->videoDevice) {
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001889 return {};
1890 }
1891 return device->videoDevice->consumeFrames();
1892}
1893
Michael Wrightd02c5b62014-02-10 15:10:22 -08001894void EventHub::wake() {
1895 ALOGV("wake() called");
1896
1897 ssize_t nWrite;
1898 do {
1899 nWrite = write(mWakeWritePipeFd, "W", 1);
1900 } while (nWrite == -1 && errno == EINTR);
1901
1902 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001903 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001904 }
1905}
1906
1907void EventHub::scanDevicesLocked() {
Usama Arifb27c8e62021-06-03 16:44:09 +01001908 status_t result;
1909 std::error_code errorCode;
1910
1911 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
1912 result = scanDirLocked(DEVICE_INPUT_PATH);
1913 if (result < 0) {
1914 ALOGE("scan dir failed for %s", DEVICE_INPUT_PATH);
1915 }
1916 } else {
1917 if (errorCode) {
1918 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
1919 errorCode.message().c_str());
1920 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001921 }
Philip Quinn39b81682019-01-09 22:20:39 -08001922 if (isV4lScanningEnabled()) {
Usama Arifb27c8e62021-06-03 16:44:09 +01001923 result = scanVideoDirLocked(DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08001924 if (result != OK) {
Usama Arifb27c8e62021-06-03 16:44:09 +01001925 ALOGE("scan video dir failed for %s", DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08001926 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001927 }
Chris Ye989bb932020-07-04 16:18:59 -07001928 if (mDevices.find(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) == mDevices.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001929 createVirtualKeyboardLocked();
1930 }
1931}
1932
1933// ----------------------------------------------------------------------------
1934
Michael Wrightd02c5b62014-02-10 15:10:22 -08001935static const int32_t GAMEPAD_KEYCODES[] = {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001936 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C, //
1937 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z, //
1938 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1, //
1939 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2, //
1940 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR, //
1941 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE, //
Michael Wrightd02c5b62014-02-10 15:10:22 -08001942};
1943
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001944status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001945 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001946 struct epoll_event eventItem = {};
1947 eventItem.events = EPOLLIN | EPOLLWAKEUP;
1948 eventItem.data.fd = fd;
1949 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1950 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001951 return -errno;
1952 }
1953 return OK;
1954}
1955
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001956status_t EventHub::unregisterFdFromEpoll(int fd) {
1957 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
1958 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
1959 return -errno;
1960 }
1961 return OK;
1962}
1963
Chris Ye989bb932020-07-04 16:18:59 -07001964status_t EventHub::registerDeviceForEpollLocked(Device& device) {
1965 status_t result = registerFdForEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001966 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07001967 ALOGE("Could not add input device fd to epoll for device %" PRId32, device.id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001968 return result;
1969 }
Chris Ye989bb932020-07-04 16:18:59 -07001970 if (device.videoDevice) {
1971 registerVideoDeviceForEpollLocked(*device.videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001972 }
1973 return result;
1974}
1975
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001976void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
1977 status_t result = registerFdForEpoll(videoDevice.getFd());
1978 if (result != OK) {
1979 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
1980 }
1981}
1982
Chris Ye989bb932020-07-04 16:18:59 -07001983status_t EventHub::unregisterDeviceFromEpollLocked(Device& device) {
1984 if (device.hasValidFd()) {
1985 status_t result = unregisterFdFromEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001986 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07001987 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device.id);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001988 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001989 }
1990 }
Chris Ye989bb932020-07-04 16:18:59 -07001991 if (device.videoDevice) {
1992 unregisterVideoDeviceFromEpollLocked(*device.videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001993 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001994 return OK;
1995}
1996
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001997void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
1998 if (videoDevice.hasValidFd()) {
1999 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
2000 if (result != OK) {
2001 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002002 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002003 }
2004 }
2005}
2006
Chris Yed3fef462021-03-07 17:10:08 -08002007void EventHub::reportDeviceAddedForStatisticsLocked(const InputDeviceIdentifier& identifier,
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002008 ftl::Flags<InputDeviceClass> classes) {
Chris Ye657c2f02021-05-25 16:24:37 -07002009 SHA256_CTX ctx;
2010 SHA256_Init(&ctx);
2011 SHA256_Update(&ctx, reinterpret_cast<const uint8_t*>(identifier.uniqueId.c_str()),
2012 identifier.uniqueId.size());
2013 std::array<uint8_t, SHA256_DIGEST_LENGTH> digest;
2014 SHA256_Final(digest.data(), &ctx);
2015
2016 std::string obfuscatedId;
2017 for (size_t i = 0; i < OBFUSCATED_LENGTH; i++) {
2018 obfuscatedId += StringPrintf("%02x", digest[i]);
2019 }
2020
Chris Yed3fef462021-03-07 17:10:08 -08002021 android::util::stats_write(android::util::INPUTDEVICE_REGISTERED, identifier.name.c_str(),
2022 identifier.vendor, identifier.product, identifier.version,
Chris Ye657c2f02021-05-25 16:24:37 -07002023 identifier.bus, obfuscatedId.c_str(), classes.get());
Chris Yed3fef462021-03-07 17:10:08 -08002024}
2025
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002026void EventHub::openDeviceLocked(const std::string& devicePath) {
2027 // If an input device happens to register around the time when EventHub's constructor runs, it
2028 // is possible that the same input event node (for example, /dev/input/event3) will be noticed
2029 // in both 'inotify' callback and also in the 'scanDirLocked' pass. To prevent duplicate devices
2030 // from getting registered, ensure that this path is not already covered by an existing device.
2031 for (const auto& [deviceId, device] : mDevices) {
2032 if (device->path == devicePath) {
2033 return; // device was already registered
2034 }
2035 }
2036
Michael Wrightd02c5b62014-02-10 15:10:22 -08002037 char buffer[80];
2038
Chris Ye8594e192020-07-14 10:34:06 -07002039 ALOGV("Opening device: %s", devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002040
Chris Ye8594e192020-07-14 10:34:06 -07002041 int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002042 if (fd < 0) {
Chris Ye8594e192020-07-14 10:34:06 -07002043 ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002044 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002045 }
2046
2047 InputDeviceIdentifier identifier;
2048
2049 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002050 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Chris Ye8594e192020-07-14 10:34:06 -07002051 ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002052 } else {
2053 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002054 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002055 }
2056
2057 // Check to see if the device is on our excluded list
2058 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002059 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002060 if (identifier.name == item) {
Chris Ye8594e192020-07-14 10:34:06 -07002061 ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002062 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002063 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002064 }
2065 }
2066
2067 // Get device driver version.
2068 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002069 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Chris Ye8594e192020-07-14 10:34:06 -07002070 ALOGE("could not get driver version for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002071 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002072 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002073 }
2074
2075 // Get device identifier.
2076 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002077 if (ioctl(fd, EVIOCGID, &inputId)) {
Chris Ye8594e192020-07-14 10:34:06 -07002078 ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002079 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002080 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002081 }
2082 identifier.bus = inputId.bustype;
2083 identifier.product = inputId.product;
2084 identifier.vendor = inputId.vendor;
2085 identifier.version = inputId.version;
2086
2087 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002088 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
2089 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002090 } else {
2091 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002092 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002093 }
2094
2095 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002096 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
2097 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002098 } else {
2099 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002100 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002101 }
2102
2103 // Fill in the descriptor.
2104 assignDescriptorLocked(identifier);
2105
Michael Wrightd02c5b62014-02-10 15:10:22 -08002106 // Allocate device. (The device object takes ownership of the fd at this point.)
2107 int32_t deviceId = mNextDeviceId++;
Prabir Pradhancb42b472022-08-23 16:01:19 +00002108 std::unique_ptr<Device> device =
2109 std::make_unique<Device>(fd, deviceId, devicePath, identifier,
2110 obtainAssociatedDeviceLocked(devicePath));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002111
Chris Ye8594e192020-07-14 10:34:06 -07002112 ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002113 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002114 " vendor %04x\n"
2115 " product %04x\n"
2116 " version %04x\n",
2117 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002118 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
2119 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
2120 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
2121 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002122 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
2123 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002124
2125 // Load the configuration file for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002126 device->loadConfigurationLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002127
2128 // Figure out the kinds of events the device reports.
Chris Ye66fbac32020-07-06 20:36:43 -07002129 device->readDeviceBitMask(EVIOCGBIT(EV_KEY, 0), device->keyBitmask);
2130 device->readDeviceBitMask(EVIOCGBIT(EV_ABS, 0), device->absBitmask);
2131 device->readDeviceBitMask(EVIOCGBIT(EV_REL, 0), device->relBitmask);
2132 device->readDeviceBitMask(EVIOCGBIT(EV_SW, 0), device->swBitmask);
2133 device->readDeviceBitMask(EVIOCGBIT(EV_LED, 0), device->ledBitmask);
2134 device->readDeviceBitMask(EVIOCGBIT(EV_FF, 0), device->ffBitmask);
Chris Yef59a2f42020-10-16 12:55:26 -07002135 device->readDeviceBitMask(EVIOCGBIT(EV_MSC, 0), device->mscBitmask);
Chris Ye66fbac32020-07-06 20:36:43 -07002136 device->readDeviceBitMask(EVIOCGPROP(0), device->propBitmask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002137
2138 // See if this is a keyboard. Ignore everything in the button range except for
2139 // joystick and gamepad buttons which are handled like keyboards for the most part.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002140 bool haveKeyboardKeys =
Chris Ye66fbac32020-07-06 20:36:43 -07002141 device->keyBitmask.any(0, BTN_MISC) || device->keyBitmask.any(BTN_WHEEL, KEY_MAX + 1);
2142 bool haveGamepadButtons = device->keyBitmask.any(BTN_MISC, BTN_MOUSE) ||
2143 device->keyBitmask.any(BTN_JOYSTICK, BTN_DIGI);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002144 if (haveKeyboardKeys || haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002145 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002146 }
2147
2148 // See if this is a cursor device such as a trackball or mouse.
Chris Ye66fbac32020-07-06 20:36:43 -07002149 if (device->keyBitmask.test(BTN_MOUSE) && device->relBitmask.test(REL_X) &&
2150 device->relBitmask.test(REL_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002151 device->classes |= InputDeviceClass::CURSOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002152 }
2153
Prashant Malani1941ff52015-08-11 18:29:28 -07002154 // See if this is a rotary encoder type device.
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07002155 std::string deviceType;
2156 if (device->configuration && device->configuration->tryGetProperty("device.type", deviceType)) {
2157 if (deviceType == "rotaryEncoder") {
Chris Ye1b0c7342020-07-28 21:57:03 -07002158 device->classes |= InputDeviceClass::ROTARY_ENCODER;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002159 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002160 }
2161
Michael Wrightd02c5b62014-02-10 15:10:22 -08002162 // See if this is a touch pad.
2163 // Is this a new modern multi-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002164 if (device->absBitmask.test(ABS_MT_POSITION_X) && device->absBitmask.test(ABS_MT_POSITION_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002165 // Some joysticks such as the PS3 controller report axes that conflict
2166 // with the ABS_MT range. Try to confirm that the device really is
2167 // a touch screen.
Chris Ye66fbac32020-07-06 20:36:43 -07002168 if (device->keyBitmask.test(BTN_TOUCH) || !haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002169 device->classes |= (InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002170 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002171 // Is this an old style single-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002172 } else if (device->keyBitmask.test(BTN_TOUCH) && device->absBitmask.test(ABS_X) &&
2173 device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002174 device->classes |= InputDeviceClass::TOUCH;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002175 // Is this a BT stylus?
Chris Ye66fbac32020-07-06 20:36:43 -07002176 } else if ((device->absBitmask.test(ABS_PRESSURE) || device->keyBitmask.test(BTN_TOUCH)) &&
2177 !device->absBitmask.test(ABS_X) && !device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002178 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -07002179 // Keyboard will try to claim some of the buttons but we really want to reserve those so we
2180 // can fuse it with the touch screen data, so just take them back. Note this means an
2181 // external stylus cannot also be a keyboard device.
Chris Ye1b0c7342020-07-28 21:57:03 -07002182 device->classes &= ~InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002183 }
2184
2185 // See if this device is a joystick.
2186 // Assumes that joysticks always have gamepad buttons in order to distinguish them
2187 // from other devices such as accelerometers that also have absolute axes.
2188 if (haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002189 auto assumedClasses = device->classes | InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002190 for (int i = 0; i <= ABS_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002191 if (device->absBitmask.test(i) &&
Chris Ye1b0c7342020-07-28 21:57:03 -07002192 (getAbsAxisUsage(i, assumedClasses).test(InputDeviceClass::JOYSTICK))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002193 device->classes = assumedClasses;
2194 break;
2195 }
2196 }
2197 }
2198
Chris Yef59a2f42020-10-16 12:55:26 -07002199 // Check whether this device is an accelerometer.
2200 if (device->propBitmask.test(INPUT_PROP_ACCELEROMETER)) {
2201 device->classes |= InputDeviceClass::SENSOR;
2202 }
2203
Michael Wrightd02c5b62014-02-10 15:10:22 -08002204 // Check whether this device has switches.
2205 for (int i = 0; i <= SW_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002206 if (device->swBitmask.test(i)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002207 device->classes |= InputDeviceClass::SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002208 break;
2209 }
2210 }
2211
2212 // Check whether this device supports the vibrator.
Chris Ye66fbac32020-07-06 20:36:43 -07002213 if (device->ffBitmask.test(FF_RUMBLE)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002214 device->classes |= InputDeviceClass::VIBRATOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002215 }
2216
2217 // Configure virtual keys.
Chris Ye1b0c7342020-07-28 21:57:03 -07002218 if ((device->classes.test(InputDeviceClass::TOUCH))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002219 // Load the virtual keys for the touch screen, if any.
2220 // We do this now so that we can make sure to load the keymap if necessary.
Chris Ye989bb932020-07-04 16:18:59 -07002221 bool success = device->loadVirtualKeyMapLocked();
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06002222 if (success) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002223 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002224 }
2225 }
2226
2227 // Load the key map.
Chris Yef59a2f42020-10-16 12:55:26 -07002228 // We need to do this for joysticks too because the key layout may specify axes, and for
2229 // sensor as well because the key layout may specify the axes to sensor data mapping.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002230 status_t keyMapStatus = NAME_NOT_FOUND;
Chris Yef59a2f42020-10-16 12:55:26 -07002231 if (device->classes.any(InputDeviceClass::KEYBOARD | InputDeviceClass::JOYSTICK |
2232 InputDeviceClass::SENSOR)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002233 // Load the keymap for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002234 keyMapStatus = device->loadKeyMapLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002235 }
2236
2237 // Configure the keyboard, gamepad or virtual keyboard.
Chris Ye1b0c7342020-07-28 21:57:03 -07002238 if (device->classes.test(InputDeviceClass::KEYBOARD)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002239 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002240 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002241 isEligibleBuiltInKeyboard(device->identifier, device->configuration.get(),
2242 &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002243 mBuiltInKeyboardId = device->id;
2244 }
2245
2246 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
Chris Ye989bb932020-07-04 16:18:59 -07002247 if (device->hasKeycodeLocked(AKEYCODE_Q)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002248 device->classes |= InputDeviceClass::ALPHAKEY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002249 }
2250
2251 // See if this device has a DPAD.
Chris Ye989bb932020-07-04 16:18:59 -07002252 if (device->hasKeycodeLocked(AKEYCODE_DPAD_UP) &&
2253 device->hasKeycodeLocked(AKEYCODE_DPAD_DOWN) &&
2254 device->hasKeycodeLocked(AKEYCODE_DPAD_LEFT) &&
2255 device->hasKeycodeLocked(AKEYCODE_DPAD_RIGHT) &&
2256 device->hasKeycodeLocked(AKEYCODE_DPAD_CENTER)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002257 device->classes |= InputDeviceClass::DPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002258 }
2259
2260 // See if this device has a gamepad.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002261 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES) / sizeof(GAMEPAD_KEYCODES[0]); i++) {
Chris Ye989bb932020-07-04 16:18:59 -07002262 if (device->hasKeycodeLocked(GAMEPAD_KEYCODES[i])) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002263 device->classes |= InputDeviceClass::GAMEPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002264 break;
2265 }
2266 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002267 }
2268
2269 // If the device isn't recognized as something we handle, don't monitor it.
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002270 if (device->classes == ftl::Flags<InputDeviceClass>(0)) {
Chris Ye8594e192020-07-14 10:34:06 -07002271 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002272 device->identifier.name.c_str());
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002273 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002274 }
2275
Chris Ye3fdbfef2021-01-06 18:45:18 -08002276 // Classify InputDeviceClass::BATTERY.
Prabir Pradhan51894782022-08-23 16:29:10 +00002277 if (device->associatedDevice && !device->associatedDevice->batteryInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002278 device->classes |= InputDeviceClass::BATTERY;
2279 }
Kim Low03ea0352020-11-06 12:45:07 -08002280
Chris Ye3fdbfef2021-01-06 18:45:18 -08002281 // Classify InputDeviceClass::LIGHT.
Prabir Pradhan51894782022-08-23 16:29:10 +00002282 if (device->associatedDevice && !device->associatedDevice->lightInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002283 device->classes |= InputDeviceClass::LIGHT;
Kim Low03ea0352020-11-06 12:45:07 -08002284 }
2285
Tim Kilbourn063ff532015-04-08 10:26:18 -07002286 // Determine whether the device has a mic.
Chris Ye989bb932020-07-04 16:18:59 -07002287 if (device->deviceHasMicLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002288 device->classes |= InputDeviceClass::MIC;
Tim Kilbourn063ff532015-04-08 10:26:18 -07002289 }
2290
Michael Wrightd02c5b62014-02-10 15:10:22 -08002291 // Determine whether the device is external or internal.
Chris Ye989bb932020-07-04 16:18:59 -07002292 if (device->isExternalDeviceLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002293 device->classes |= InputDeviceClass::EXTERNAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002294 }
2295
Chris Ye1b0c7342020-07-28 21:57:03 -07002296 if (device->classes.any(InputDeviceClass::JOYSTICK | InputDeviceClass::DPAD) &&
2297 device->classes.test(InputDeviceClass::GAMEPAD)) {
Chris Ye989bb932020-07-04 16:18:59 -07002298 device->controllerNumber = getNextControllerNumberLocked(device->identifier.name);
2299 device->setLedForControllerLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002300 }
2301
Chris Ye989bb932020-07-04 16:18:59 -07002302 if (registerDeviceForEpollLocked(*device) != OK) {
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002303 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002304 }
2305
Chris Ye989bb932020-07-04 16:18:59 -07002306 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002307
Chris Ye1b0c7342020-07-28 21:57:03 -07002308 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=%s, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002309 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Chris Ye1b0c7342020-07-28 21:57:03 -07002310 deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(),
2311 device->classes.string().c_str(), device->configurationFile.c_str(),
2312 device->keyMap.keyLayoutFile.c_str(), device->keyMap.keyCharacterMapFile.c_str(),
2313 toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002314
Chris Ye989bb932020-07-04 16:18:59 -07002315 addDeviceLocked(std::move(device));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002316}
2317
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002318void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
2319 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
2320 if (!videoDevice) {
2321 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
2322 return;
2323 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002324 // Transfer ownership of this video device to a matching input device
Chris Ye989bb932020-07-04 16:18:59 -07002325 for (const auto& [id, device] : mDevices) {
Chris Yed3fef462021-03-07 17:10:08 -08002326 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002327 return; // 'device' now owns 'videoDevice'
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002328 }
2329 }
2330
2331 // Couldn't find a matching input device, so just add it to a temporary holding queue.
2332 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002333 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002334 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002335 mUnattachedVideoDevices.push_back(std::move(videoDevice));
2336}
2337
Chris Yed3fef462021-03-07 17:10:08 -08002338bool EventHub::tryAddVideoDeviceLocked(EventHub::Device& device,
2339 std::unique_ptr<TouchVideoDevice>& videoDevice) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002340 if (videoDevice->getName() != device.identifier.name) {
2341 return false;
2342 }
2343 device.videoDevice = std::move(videoDevice);
2344 if (device.enabled) {
2345 registerVideoDeviceForEpollLocked(*device.videoDevice);
2346 }
2347 return true;
2348}
2349
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002350bool EventHub::isDeviceEnabled(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00002351 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002352 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002353 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002354 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2355 return false;
2356 }
2357 return device->enabled;
2358}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002359
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002360status_t EventHub::enableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002361 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002362 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002363 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002364 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2365 return BAD_VALUE;
2366 }
2367 if (device->enabled) {
2368 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
2369 return OK;
2370 }
2371 status_t result = device->enable();
2372 if (result != OK) {
2373 ALOGE("Failed to enable device %" PRId32, deviceId);
2374 return result;
2375 }
2376
Chris Ye989bb932020-07-04 16:18:59 -07002377 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002378
Chris Ye989bb932020-07-04 16:18:59 -07002379 return registerDeviceForEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002380}
2381
2382status_t EventHub::disableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002383 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002384 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002385 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002386 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2387 return BAD_VALUE;
2388 }
2389 if (!device->enabled) {
2390 ALOGW("Duplicate call to %s, input device already disabled", __func__);
2391 return OK;
2392 }
Chris Ye989bb932020-07-04 16:18:59 -07002393 unregisterDeviceFromEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002394 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002395}
2396
2397void EventHub::createVirtualKeyboardLocked() {
2398 InputDeviceIdentifier identifier;
2399 identifier.name = "Virtual";
2400 identifier.uniqueId = "<virtual>";
2401 assignDescriptorLocked(identifier);
2402
Chris Ye989bb932020-07-04 16:18:59 -07002403 std::unique_ptr<Device> device =
2404 std::make_unique<Device>(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
Prabir Pradhancb42b472022-08-23 16:01:19 +00002405 identifier, nullptr /*associatedDevice*/);
Chris Ye1b0c7342020-07-28 21:57:03 -07002406 device->classes = InputDeviceClass::KEYBOARD | InputDeviceClass::ALPHAKEY |
2407 InputDeviceClass::DPAD | InputDeviceClass::VIRTUAL;
Chris Ye989bb932020-07-04 16:18:59 -07002408 device->loadKeyMapLocked();
2409 addDeviceLocked(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002410}
2411
Chris Ye989bb932020-07-04 16:18:59 -07002412void EventHub::addDeviceLocked(std::unique_ptr<Device> device) {
Chris Yed3fef462021-03-07 17:10:08 -08002413 reportDeviceAddedForStatisticsLocked(device->identifier, device->classes);
Chris Ye989bb932020-07-04 16:18:59 -07002414 mOpeningDevices.push_back(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002415}
2416
Chris Ye989bb932020-07-04 16:18:59 -07002417int32_t EventHub::getNextControllerNumberLocked(const std::string& name) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002418 if (mControllerNumbers.isFull()) {
2419 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Chris Ye989bb932020-07-04 16:18:59 -07002420 name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002421 return 0;
2422 }
2423 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
2424 // one
2425 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
2426}
2427
Chris Ye989bb932020-07-04 16:18:59 -07002428void EventHub::releaseControllerNumberLocked(int32_t num) {
2429 if (num > 0) {
2430 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002431 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002432}
2433
Chris Ye8594e192020-07-14 10:34:06 -07002434void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002435 Device* device = getDeviceByPathLocked(devicePath);
Chris Ye989bb932020-07-04 16:18:59 -07002436 if (device != nullptr) {
2437 closeDeviceLocked(*device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002438 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002439 }
Chris Ye8594e192020-07-14 10:34:06 -07002440 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002441}
2442
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002443/**
2444 * Find the video device by filename, and close it.
2445 * The video device is closed by path during an inotify event, where we don't have the
2446 * additional context about the video device fd, or the associated input device.
2447 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002448void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002449 // A video device may be owned by an existing input device, or it may be stored in
2450 // the mUnattachedVideoDevices queue. Check both locations.
Chris Ye989bb932020-07-04 16:18:59 -07002451 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002452 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002453 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002454 device->videoDevice = nullptr;
2455 return;
2456 }
2457 }
Siarhei Vishniakouf47c339e2021-12-30 11:22:26 -08002458 std::erase_if(mUnattachedVideoDevices,
2459 [&devicePath](const std::unique_ptr<TouchVideoDevice>& videoDevice) {
2460 return videoDevice->getPath() == devicePath;
2461 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08002462}
2463
2464void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002465 mUnattachedVideoDevices.clear();
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002466 while (!mDevices.empty()) {
2467 closeDeviceLocked(*(mDevices.begin()->second));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002468 }
2469}
2470
Chris Ye989bb932020-07-04 16:18:59 -07002471void EventHub::closeDeviceLocked(Device& device) {
2472 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=%s", device.path.c_str(),
2473 device.identifier.name.c_str(), device.id, device.fd, device.classes.string().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002474
Chris Ye989bb932020-07-04 16:18:59 -07002475 if (device.id == mBuiltInKeyboardId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002476 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Chris Ye989bb932020-07-04 16:18:59 -07002477 device.path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002478 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
2479 }
2480
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002481 unregisterDeviceFromEpollLocked(device);
Chris Ye989bb932020-07-04 16:18:59 -07002482 if (device.videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002483 // This must be done after the video device is removed from epoll
Chris Ye989bb932020-07-04 16:18:59 -07002484 mUnattachedVideoDevices.push_back(std::move(device.videoDevice));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002485 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002486
Chris Ye989bb932020-07-04 16:18:59 -07002487 releaseControllerNumberLocked(device.controllerNumber);
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002488 device.controllerNumber = 0;
Chris Ye989bb932020-07-04 16:18:59 -07002489 device.close();
Chris Ye989bb932020-07-04 16:18:59 -07002490 mClosingDevices.push_back(std::move(mDevices[device.id]));
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002491
Chris Ye989bb932020-07-04 16:18:59 -07002492 mDevices.erase(device.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002493}
2494
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002495base::Result<void> EventHub::readNotifyLocked() {
2496 static constexpr auto EVENT_SIZE = static_cast<ssize_t>(sizeof(inotify_event));
2497 uint8_t eventBuffer[512];
2498 ssize_t sizeRead;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002499
2500 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002501 do {
2502 sizeRead = read(mINotifyFd, eventBuffer, sizeof(eventBuffer));
2503 } while (sizeRead < 0 && errno == EINTR);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002504
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002505 if (sizeRead < EVENT_SIZE) return Errorf("could not get event, %s", strerror(errno));
2506
2507 for (ssize_t eventPos = 0; sizeRead >= EVENT_SIZE;) {
2508 const inotify_event* event;
2509 event = (const inotify_event*)(eventBuffer + eventPos);
2510 if (event->len == 0) continue;
2511
2512 handleNotifyEventLocked(*event);
2513
2514 const ssize_t eventSize = EVENT_SIZE + event->len;
2515 sizeRead -= eventSize;
2516 eventPos += eventSize;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002517 }
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002518 return {};
2519}
2520
2521void EventHub::handleNotifyEventLocked(const inotify_event& event) {
2522 if (event.wd == mDeviceInputWd) {
2523 std::string filename = std::string(DEVICE_INPUT_PATH) + "/" + event.name;
2524 if (event.mask & IN_CREATE) {
2525 openDeviceLocked(filename);
2526 } else {
2527 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
2528 closeDeviceByPathLocked(filename);
2529 }
2530 } else if (event.wd == mDeviceWd) {
2531 if (isV4lTouchNode(event.name)) {
2532 std::string filename = std::string(DEVICE_PATH) + "/" + event.name;
2533 if (event.mask & IN_CREATE) {
2534 openVideoDeviceLocked(filename);
2535 } else {
2536 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
2537 closeVideoDeviceByPathLocked(filename);
2538 }
2539 } else if (strcmp(event.name, "input") == 0 && event.mask & IN_CREATE) {
2540 addDeviceInputInotify();
2541 }
2542 } else {
2543 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event.wd);
2544 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002545}
2546
Chris Ye8594e192020-07-14 10:34:06 -07002547status_t EventHub::scanDirLocked(const std::string& dirname) {
2548 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2549 openDeviceLocked(entry.path());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002550 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002551 return 0;
2552}
2553
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002554/**
2555 * Look for all dirname/v4l-touch* devices, and open them.
2556 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002557status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Chris Ye8594e192020-07-14 10:34:06 -07002558 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2559 if (isV4lTouchNode(entry.path())) {
2560 ALOGI("Found touch video device %s", entry.path().c_str());
2561 openVideoDeviceLocked(entry.path());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002562 }
2563 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002564 return OK;
2565}
2566
Michael Wrightd02c5b62014-02-10 15:10:22 -08002567void EventHub::requestReopenDevices() {
2568 ALOGV("requestReopenDevices() called");
2569
Chris Ye87143712020-11-10 05:05:58 +00002570 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002571 mNeedToReopenDevices = true;
2572}
2573
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002574void EventHub::dump(std::string& dump) const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002575 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002576
2577 { // acquire lock
Chris Ye87143712020-11-10 05:05:58 +00002578 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002579
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002580 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002581
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002582 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002583
Chris Ye989bb932020-07-04 16:18:59 -07002584 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002585 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002586 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002587 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002588 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002589 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002590 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002591 }
Chris Ye1b0c7342020-07-28 21:57:03 -07002592 dump += StringPrintf(INDENT3 "Classes: %s\n", device->classes.string().c_str());
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002593 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002594 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002595 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
2596 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002597 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002598 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002599 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002600 "product=0x%04x, version=0x%04x\n",
2601 device->identifier.bus, device->identifier.vendor,
2602 device->identifier.product, device->identifier.version);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002603 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002604 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002605 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002606 device->keyMap.keyCharacterMapFile.c_str());
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00002607 dump += StringPrintf(INDENT3 "CountryCode: %d\n",
2608 device->associatedDevice ? device->associatedDevice->countryCode
2609 : InputDeviceCountryCode::INVALID);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002610 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002611 device->configurationFile.c_str());
Prabir Pradhan51894782022-08-23 16:29:10 +00002612 dump += StringPrintf(INDENT3 "VideoDevice: %s\n",
2613 device->videoDevice ? device->videoDevice->dump().c_str()
2614 : "<none>");
2615 dump += StringPrintf(INDENT3 "SysfsDevicePath: %s\n",
2616 device->associatedDevice
2617 ? device->associatedDevice->sysfsRootPath.c_str()
2618 : "<none>");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002619 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002620
2621 dump += INDENT "Unattached video devices:\n";
2622 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
2623 dump += INDENT2 + videoDevice->dump() + "\n";
2624 }
2625 if (mUnattachedVideoDevices.empty()) {
2626 dump += INDENT2 "<none>\n";
2627 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002628 } // release lock
2629}
2630
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002631void EventHub::monitor() const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002632 // Acquire and release the lock to ensure that the event hub has not deadlocked.
Chris Ye1c2e0892020-11-30 21:41:44 -08002633 std::unique_lock<std::mutex> lock(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002634}
2635
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002636} // namespace android