blob: 39beed33f6abbf71824654253784b8640231228d [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>
Chris Ye8594e192020-07-14 10:34:06 -070055
56#include "EventHub.h"
Michael Wrightd02c5b62014-02-10 15:10:22 -080057
Michael Wrightd02c5b62014-02-10 15:10:22 -080058#define INDENT " "
59#define INDENT2 " "
60#define INDENT3 " "
61
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080062using android::base::StringPrintf;
63
Michael Wrightd02c5b62014-02-10 15:10:22 -080064namespace android {
65
Dominik Laskowski2f01d772022-03-23 16:01:29 -070066using namespace ftl::flag_operators;
67
Usama Arifb27c8e62021-06-03 16:44:09 +010068static const char* DEVICE_INPUT_PATH = "/dev/input";
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080069// v4l2 devices go directly into /dev
Usama Arifb27c8e62021-06-03 16:44:09 +010070static const char* DEVICE_PATH = "/dev";
Michael Wrightd02c5b62014-02-10 15:10:22 -080071
Chris Ye657c2f02021-05-25 16:24:37 -070072static constexpr size_t OBFUSCATED_LENGTH = 8;
73
Chris Ye87143712020-11-10 05:05:58 +000074static constexpr int32_t FF_STRONG_MAGNITUDE_CHANNEL_IDX = 0;
75static constexpr int32_t FF_WEAK_MAGNITUDE_CHANNEL_IDX = 1;
Chris Ye6393a262020-08-04 19:41:36 -070076
Chris Yee2b1e5c2021-03-10 22:45:12 -080077// Mapping for input battery class node IDs lookup.
78// https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
79static const std::unordered_map<std::string, InputBatteryClass> BATTERY_CLASSES =
80 {{"capacity", InputBatteryClass::CAPACITY},
81 {"capacity_level", InputBatteryClass::CAPACITY_LEVEL},
82 {"status", InputBatteryClass::STATUS}};
83
84// Mapping for input battery class node names lookup.
85// https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
86static const std::unordered_map<InputBatteryClass, std::string> BATTERY_NODES =
87 {{InputBatteryClass::CAPACITY, "capacity"},
88 {InputBatteryClass::CAPACITY_LEVEL, "capacity_level"},
89 {InputBatteryClass::STATUS, "status"}};
90
Kim Low03ea0352020-11-06 12:45:07 -080091// must be kept in sync with definitions in kernel /drivers/power/supply/power_supply_sysfs.c
92static const std::unordered_map<std::string, int32_t> BATTERY_STATUS =
93 {{"Unknown", BATTERY_STATUS_UNKNOWN},
94 {"Charging", BATTERY_STATUS_CHARGING},
95 {"Discharging", BATTERY_STATUS_DISCHARGING},
96 {"Not charging", BATTERY_STATUS_NOT_CHARGING},
97 {"Full", BATTERY_STATUS_FULL}};
98
99// Mapping taken from
100// https://gitlab.freedesktop.org/upower/upower/-/blob/master/src/linux/up-device-supply.c#L484
101static const std::unordered_map<std::string, int32_t> BATTERY_LEVEL = {{"Critical", 5},
102 {"Low", 10},
103 {"Normal", 55},
104 {"High", 70},
105 {"Full", 100},
106 {"Unknown", 50}};
107
Chris Ye3fdbfef2021-01-06 18:45:18 -0800108// Mapping for input led class node names lookup.
109// https://www.kernel.org/doc/html/latest/leds/leds-class.html
110static const std::unordered_map<std::string, InputLightClass> LIGHT_CLASSES =
111 {{"red", InputLightClass::RED},
112 {"green", InputLightClass::GREEN},
113 {"blue", InputLightClass::BLUE},
114 {"global", InputLightClass::GLOBAL},
115 {"brightness", InputLightClass::BRIGHTNESS},
116 {"multi_index", InputLightClass::MULTI_INDEX},
117 {"multi_intensity", InputLightClass::MULTI_INTENSITY},
118 {"max_brightness", InputLightClass::MAX_BRIGHTNESS}};
119
120// Mapping for input multicolor led class node names.
121// https://www.kernel.org/doc/html/latest/leds/leds-class-multicolor.html
122static const std::unordered_map<InputLightClass, std::string> LIGHT_NODES =
123 {{InputLightClass::BRIGHTNESS, "brightness"},
124 {InputLightClass::MULTI_INDEX, "multi_index"},
125 {InputLightClass::MULTI_INTENSITY, "multi_intensity"}};
126
127// Mapping for light color name and the light color
128const std::unordered_map<std::string, LightColor> LIGHT_COLORS = {{"red", LightColor::RED},
129 {"green", LightColor::GREEN},
130 {"blue", LightColor::BLUE}};
131
Michael Wrightd02c5b62014-02-10 15:10:22 -0800132static inline const char* toString(bool value) {
133 return value ? "true" : "false";
134}
135
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100136static std::string sha1(const std::string& in) {
Dan Albert677d87e2014-06-16 17:31:28 -0700137 SHA_CTX ctx;
138 SHA1_Init(&ctx);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100139 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
Dan Albert677d87e2014-06-16 17:31:28 -0700140 u_char digest[SHA_DIGEST_LENGTH];
141 SHA1_Final(digest, &ctx);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800142
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100143 std::string out;
Dan Albert677d87e2014-06-16 17:31:28 -0700144 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100145 out += StringPrintf("%02x", digest[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800146 }
147 return out;
148}
149
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800150/**
151 * Return true if name matches "v4l-touch*"
152 */
Chris Ye8594e192020-07-14 10:34:06 -0700153static bool isV4lTouchNode(std::string name) {
154 return name.find("v4l-touch") != std::string::npos;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800155}
156
Philip Quinn39b81682019-01-09 22:20:39 -0800157/**
158 * Returns true if V4L devices should be scanned.
159 *
160 * The system property ro.input.video_enabled can be used to control whether
161 * EventHub scans and opens V4L devices. As V4L does not support multiple
162 * clients, EventHub effectively blocks access to these devices when it opens
Siarhei Vishniakou29f88492019-04-05 14:11:43 -0700163 * them.
164 *
165 * Setting this to "false" would prevent any video devices from being discovered and
166 * associated with input devices.
167 *
168 * This property can be used as follows:
169 * 1. To turn off features that are dependent on video device presence.
170 * 2. During testing and development, to allow other clients to read video devices
171 * directly from /dev.
Philip Quinn39b81682019-01-09 22:20:39 -0800172 */
173static bool isV4lScanningEnabled() {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700174 return property_get_bool("ro.input.video_enabled", true /* default_value */);
Philip Quinn39b81682019-01-09 22:20:39 -0800175}
176
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800177static nsecs_t processEventTimestamp(const struct input_event& event) {
178 // Use the time specified in the event instead of the current time
179 // so that downstream code can get more accurate estimates of
180 // event dispatch latency from the time the event is enqueued onto
181 // the evdev client buffer.
182 //
183 // The event's timestamp fortuitously uses the same monotonic clock
184 // time base as the rest of Android. The kernel event device driver
185 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
186 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
187 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
188 // system call that also queries ktime_get_ts().
189
190 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.time.tv_sec) +
191 microseconds_to_nanoseconds(event.time.tv_usec);
192 return inputEventTime;
193}
194
Kim Low03ea0352020-11-06 12:45:07 -0800195/**
196 * Returns the sysfs root path of the input device
197 *
198 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800199static std::optional<std::filesystem::path> getSysfsRootPath(const char* devicePath) {
Kim Low03ea0352020-11-06 12:45:07 -0800200 std::error_code errorCode;
201
202 // Stat the device path to get the major and minor number of the character file
203 struct stat statbuf;
204 if (stat(devicePath, &statbuf) == -1) {
205 ALOGE("Could not stat device %s due to error: %s.", devicePath, std::strerror(errno));
Chris Ye3fdbfef2021-01-06 18:45:18 -0800206 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800207 }
208
209 unsigned int major_num = major(statbuf.st_rdev);
210 unsigned int minor_num = minor(statbuf.st_rdev);
211
212 // Realpath "/sys/dev/char/{major}:{minor}" to get the sysfs path to the input event
213 auto sysfsPath = std::filesystem::path("/sys/dev/char/");
214 sysfsPath /= std::to_string(major_num) + ":" + std::to_string(minor_num);
215 sysfsPath = std::filesystem::canonical(sysfsPath, errorCode);
216
217 // Make sure nothing went wrong in call to canonical()
218 if (errorCode) {
219 ALOGW("Could not run filesystem::canonical() due to error %d : %s.", errorCode.value(),
220 errorCode.message().c_str());
Chris Ye3fdbfef2021-01-06 18:45:18 -0800221 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800222 }
223
224 // Continue to go up a directory until we reach a directory named "input"
225 while (sysfsPath != "/" && sysfsPath.filename() != "input") {
226 sysfsPath = sysfsPath.parent_path();
227 }
228
229 // Then go up one more and you will be at the sysfs root of the device
230 sysfsPath = sysfsPath.parent_path();
231
232 // Make sure we didn't reach root path and that directory actually exists
233 if (sysfsPath == "/" || !std::filesystem::exists(sysfsPath, errorCode)) {
234 if (errorCode) {
235 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
236 errorCode.message().c_str());
237 }
238
239 // Not found
Chris Ye3fdbfef2021-01-06 18:45:18 -0800240 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800241 }
242
243 return sysfsPath;
244}
245
246/**
Chris Ye3fdbfef2021-01-06 18:45:18 -0800247 * Returns the list of files under a specified path.
Kim Low03ea0352020-11-06 12:45:07 -0800248 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800249static std::vector<std::filesystem::path> allFilesInPath(const std::filesystem::path& path) {
250 std::vector<std::filesystem::path> nodes;
251 std::error_code errorCode;
252 auto iter = std::filesystem::directory_iterator(path, errorCode);
253 while (!errorCode && iter != std::filesystem::directory_iterator()) {
254 nodes.push_back(iter->path());
255 iter++;
256 }
257 return nodes;
258}
259
260/**
261 * Returns the list of files under a specified directory in a sysfs path.
262 * Example:
263 * findSysfsNodes(sysfsRootPath, SysfsClass::LEDS) will return all led nodes under "leds" directory
264 * in the sysfs path.
265 */
266static std::vector<std::filesystem::path> findSysfsNodes(const std::filesystem::path& sysfsRoot,
267 SysfsClass clazz) {
Dominik Laskowski75788452021-02-09 18:51:25 -0800268 std::string nodeStr = ftl::enum_string(clazz);
Chris Ye3fdbfef2021-01-06 18:45:18 -0800269 std::for_each(nodeStr.begin(), nodeStr.end(),
270 [](char& c) { c = std::tolower(static_cast<unsigned char>(c)); });
271 std::vector<std::filesystem::path> nodes;
272 for (auto path = sysfsRoot; path != "/" && nodes.empty(); path = path.parent_path()) {
273 nodes = allFilesInPath(path / nodeStr);
274 }
275 return nodes;
276}
277
278static std::optional<std::array<LightColor, COLOR_NUM>> getColorIndexArray(
279 std::filesystem::path path) {
280 std::string indexStr;
281 if (!base::ReadFileToString(path, &indexStr)) {
282 return std::nullopt;
283 }
284
285 // Parse the multi color LED index file, refer to kernel docs
286 // leds/leds-class-multicolor.html
287 std::regex indexPattern("(red|green|blue)\\s(red|green|blue)\\s(red|green|blue)[\\n]");
288 std::smatch results;
289 std::array<LightColor, COLOR_NUM> colors;
290 if (!std::regex_match(indexStr, results, indexPattern)) {
291 return std::nullopt;
292 }
293
294 for (size_t i = 1; i < results.size(); i++) {
295 const auto it = LIGHT_COLORS.find(results[i].str());
296 if (it != LIGHT_COLORS.end()) {
297 // intensities.emplace(it->second, 0);
298 colors[i - 1] = it->second;
Kim Low03ea0352020-11-06 12:45:07 -0800299 }
300 }
Chris Ye3fdbfef2021-01-06 18:45:18 -0800301 return colors;
Kim Low03ea0352020-11-06 12:45:07 -0800302}
303
Michael Wrightd02c5b62014-02-10 15:10:22 -0800304// --- Global Functions ---
305
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700306ftl::Flags<InputDeviceClass> getAbsAxisUsage(int32_t axis,
307 ftl::Flags<InputDeviceClass> deviceClasses) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800308 // Touch devices get dibs on touch-related axes.
Chris Ye1b0c7342020-07-28 21:57:03 -0700309 if (deviceClasses.test(InputDeviceClass::TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800310 switch (axis) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700311 case ABS_X:
312 case ABS_Y:
313 case ABS_PRESSURE:
314 case ABS_TOOL_WIDTH:
315 case ABS_DISTANCE:
316 case ABS_TILT_X:
317 case ABS_TILT_Y:
318 case ABS_MT_SLOT:
319 case ABS_MT_TOUCH_MAJOR:
320 case ABS_MT_TOUCH_MINOR:
321 case ABS_MT_WIDTH_MAJOR:
322 case ABS_MT_WIDTH_MINOR:
323 case ABS_MT_ORIENTATION:
324 case ABS_MT_POSITION_X:
325 case ABS_MT_POSITION_Y:
326 case ABS_MT_TOOL_TYPE:
327 case ABS_MT_BLOB_ID:
328 case ABS_MT_TRACKING_ID:
329 case ABS_MT_PRESSURE:
330 case ABS_MT_DISTANCE:
Chris Ye1b0c7342020-07-28 21:57:03 -0700331 return InputDeviceClass::TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800332 }
333 }
334
Chris Yef59a2f42020-10-16 12:55:26 -0700335 if (deviceClasses.test(InputDeviceClass::SENSOR)) {
336 switch (axis) {
337 case ABS_X:
338 case ABS_Y:
339 case ABS_Z:
340 case ABS_RX:
341 case ABS_RY:
342 case ABS_RZ:
343 return InputDeviceClass::SENSOR;
344 }
345 }
346
Michael Wright842500e2015-03-13 17:32:02 -0700347 // External stylus gets the pressure axis
Chris Ye1b0c7342020-07-28 21:57:03 -0700348 if (deviceClasses.test(InputDeviceClass::EXTERNAL_STYLUS)) {
Michael Wright842500e2015-03-13 17:32:02 -0700349 if (axis == ABS_PRESSURE) {
Chris Ye1b0c7342020-07-28 21:57:03 -0700350 return InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -0700351 }
352 }
353
Michael Wrightd02c5b62014-02-10 15:10:22 -0800354 // Joystick devices get the rest.
Chris Ye1b0c7342020-07-28 21:57:03 -0700355 return deviceClasses & InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800356}
357
358// --- EventHub::Device ---
359
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100360EventHub::Device::Device(int fd, int32_t id, const std::string& path,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700361 const InputDeviceIdentifier& identifier)
Chris Ye989bb932020-07-04 16:18:59 -0700362 : fd(fd),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700363 id(id),
364 path(path),
365 identifier(identifier),
366 classes(0),
367 configuration(nullptr),
368 virtualKeyMap(nullptr),
369 ffEffectPlaying(false),
370 ffEffectId(-1),
Chris Ye1dd2e5c2021-04-04 23:12:41 -0700371 associatedDevice(nullptr),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700372 controllerNumber(0),
373 enabled(true),
Chris Ye66fbac32020-07-06 20:36:43 -0700374 isVirtual(fd < 0) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800375
376EventHub::Device::~Device() {
377 close();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800378}
379
380void EventHub::Device::close() {
381 if (fd >= 0) {
382 ::close(fd);
383 fd = -1;
384 }
385}
386
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700387status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100388 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700389 if (fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100390 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700391 return -errno;
392 }
393 enabled = true;
394 return OK;
395}
396
397status_t EventHub::Device::disable() {
398 close();
399 enabled = false;
400 return OK;
401}
402
Chris Ye989bb932020-07-04 16:18:59 -0700403bool EventHub::Device::hasValidFd() const {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700404 return !isVirtual && enabled;
405}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800406
Chris Ye3a1e4462020-08-12 10:13:15 -0700407const std::shared_ptr<KeyCharacterMap> EventHub::Device::getKeyCharacterMap() const {
Chris Ye989bb932020-07-04 16:18:59 -0700408 return keyMap.keyCharacterMap;
409}
410
411template <std::size_t N>
412status_t EventHub::Device::readDeviceBitMask(unsigned long ioctlCode, BitArray<N>& bitArray) {
413 if (!hasValidFd()) {
414 return BAD_VALUE;
415 }
416 if ((_IOC_SIZE(ioctlCode) == 0)) {
417 ioctlCode |= _IOC(0, 0, 0, bitArray.bytes());
418 }
419
420 typename BitArray<N>::Buffer buffer;
421 status_t ret = ioctl(fd, ioctlCode, buffer.data());
422 bitArray.loadFromBuffer(buffer);
423 return ret;
424}
425
426void EventHub::Device::configureFd() {
427 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
428 if (classes.test(InputDeviceClass::KEYBOARD)) {
429 // Disable kernel key repeat since we handle it ourselves
430 unsigned int repeatRate[] = {0, 0};
431 if (ioctl(fd, EVIOCSREP, repeatRate)) {
432 ALOGW("Unable to disable kernel key repeat for %s: %s", path.c_str(), strerror(errno));
433 }
434 }
435
436 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
437 // associated with input events. This is important because the input system
438 // uses the timestamps extensively and assumes they were recorded using the monotonic
439 // clock.
440 int clockId = CLOCK_MONOTONIC;
Chris Yef59a2f42020-10-16 12:55:26 -0700441 if (classes.test(InputDeviceClass::SENSOR)) {
442 // Each new sensor event should use the same time base as
443 // SystemClock.elapsedRealtimeNanos().
444 clockId = CLOCK_BOOTTIME;
445 }
Chris Ye989bb932020-07-04 16:18:59 -0700446 bool usingClockIoctl = !ioctl(fd, EVIOCSCLOCKID, &clockId);
447 ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
448}
449
450bool EventHub::Device::hasKeycodeLocked(int keycode) const {
451 if (!keyMap.haveKeyLayout()) {
452 return false;
453 }
454
Siarhei Vishniakou53f0a5e2022-05-18 09:45:54 -0700455 std::vector<int32_t> scanCodes = keyMap.keyLayoutMap->findScanCodesForKey(keycode);
Chris Ye989bb932020-07-04 16:18:59 -0700456 const size_t N = scanCodes.size();
457 for (size_t i = 0; i < N && i <= KEY_MAX; i++) {
458 int32_t sc = scanCodes[i];
459 if (sc >= 0 && sc <= KEY_MAX && keyBitmask.test(sc)) {
460 return true;
461 }
462 }
463
Charles Linaadf8d52023-03-30 13:34:54 +0800464 std::vector<int32_t> usageCodes = keyMap.keyLayoutMap->findUsageCodesForKey(keycode);
465 if (usageCodes.size() > 0 && mscBitmask.test(MSC_SCAN)) {
466 return true;
467 }
468
Chris Ye989bb932020-07-04 16:18:59 -0700469 return false;
470}
471
472void EventHub::Device::loadConfigurationLocked() {
473 configurationFile =
474 getInputDeviceConfigurationFilePathByDeviceIdentifier(identifier,
475 InputDeviceConfigurationFileType::
476 CONFIGURATION);
477 if (configurationFile.empty()) {
478 ALOGD("No input device configuration file found for device '%s'.", identifier.name.c_str());
479 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500480 android::base::Result<std::unique_ptr<PropertyMap>> propertyMap =
481 PropertyMap::load(configurationFile.c_str());
482 if (!propertyMap.ok()) {
Chris Ye989bb932020-07-04 16:18:59 -0700483 ALOGE("Error loading input device configuration file for device '%s'. "
484 "Using default configuration.",
485 identifier.name.c_str());
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500486 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500487 configuration = std::move(*propertyMap);
Chris Ye989bb932020-07-04 16:18:59 -0700488 }
489 }
490}
491
492bool EventHub::Device::loadVirtualKeyMapLocked() {
493 // The virtual key map is supplied by the kernel as a system board property file.
494 std::string propPath = "/sys/board_properties/virtualkeys.";
495 propPath += identifier.getCanonicalName();
496 if (access(propPath.c_str(), R_OK)) {
497 return false;
498 }
499 virtualKeyMap = VirtualKeyMap::load(propPath);
500 return virtualKeyMap != nullptr;
501}
502
503status_t EventHub::Device::loadKeyMapLocked() {
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500504 return keyMap.load(identifier, configuration.get());
Chris Ye989bb932020-07-04 16:18:59 -0700505}
506
507bool EventHub::Device::isExternalDeviceLocked() {
508 if (configuration) {
509 bool value;
510 if (configuration->tryGetProperty(String8("device.internal"), value)) {
511 return !value;
512 }
513 }
514 return identifier.bus == BUS_USB || identifier.bus == BUS_BLUETOOTH;
515}
516
517bool EventHub::Device::deviceHasMicLocked() {
518 if (configuration) {
519 bool value;
520 if (configuration->tryGetProperty(String8("audio.mic"), value)) {
521 return value;
522 }
523 }
524 return false;
525}
526
527void EventHub::Device::setLedStateLocked(int32_t led, bool on) {
528 int32_t sc;
529 if (hasValidFd() && mapLed(led, &sc) != NAME_NOT_FOUND) {
530 struct input_event ev;
531 ev.time.tv_sec = 0;
532 ev.time.tv_usec = 0;
533 ev.type = EV_LED;
534 ev.code = sc;
535 ev.value = on ? 1 : 0;
536
537 ssize_t nWrite;
538 do {
539 nWrite = write(fd, &ev, sizeof(struct input_event));
540 } while (nWrite == -1 && errno == EINTR);
541 }
542}
543
544void EventHub::Device::setLedForControllerLocked() {
545 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
546 setLedStateLocked(ALED_CONTROLLER_1 + i, controllerNumber == i + 1);
547 }
548}
549
550status_t EventHub::Device::mapLed(int32_t led, int32_t* outScanCode) const {
551 if (!keyMap.haveKeyLayout()) {
552 return NAME_NOT_FOUND;
553 }
554
Siarhei Vishniakou53f0a5e2022-05-18 09:45:54 -0700555 std::optional<int32_t> scanCode = keyMap.keyLayoutMap->findScanCodeForLed(led);
556 if (scanCode.has_value()) {
557 if (*scanCode >= 0 && *scanCode <= LED_MAX && ledBitmask.test(*scanCode)) {
558 *outScanCode = *scanCode;
Chris Ye989bb932020-07-04 16:18:59 -0700559 return NO_ERROR;
560 }
561 }
562 return NAME_NOT_FOUND;
563}
564
Chris Ye3fdbfef2021-01-06 18:45:18 -0800565// Check the sysfs path for any input device batteries, returns true if battery found.
Chris Ye1dd2e5c2021-04-04 23:12:41 -0700566bool EventHub::AssociatedDevice::configureBatteryLocked() {
Chris Yee2b1e5c2021-03-10 22:45:12 -0800567 nextBatteryId = 0;
568 // Check if device has any battery.
569 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::POWER_SUPPLY);
570 for (const auto& nodePath : paths) {
571 RawBatteryInfo info;
572 info.id = ++nextBatteryId;
573 info.path = nodePath;
574 info.name = nodePath.filename();
575
576 // Scan the path for all the files
577 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
578 const auto& files = allFilesInPath(nodePath);
579 for (const auto& file : files) {
580 const auto it = BATTERY_CLASSES.find(file.filename().string());
581 if (it != BATTERY_CLASSES.end()) {
582 info.flags |= it->second;
583 }
584 }
585 batteryInfos.insert_or_assign(info.id, info);
586 ALOGD("configureBatteryLocked rawBatteryId %d name %s", info.id, info.name.c_str());
Chris Ye3fdbfef2021-01-06 18:45:18 -0800587 }
Chris Yee2b1e5c2021-03-10 22:45:12 -0800588 return !batteryInfos.empty();
Chris Ye3fdbfef2021-01-06 18:45:18 -0800589}
590
591// Check the sysfs path for any input device lights, returns true if lights found.
Chris Ye1dd2e5c2021-04-04 23:12:41 -0700592bool EventHub::AssociatedDevice::configureLightsLocked() {
Chris Yee2b1e5c2021-03-10 22:45:12 -0800593 nextLightId = 0;
Chris Ye3fdbfef2021-01-06 18:45:18 -0800594 // Check if device has any lights.
Chris Yee2b1e5c2021-03-10 22:45:12 -0800595 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::LEDS);
Chris Ye3fdbfef2021-01-06 18:45:18 -0800596 for (const auto& nodePath : paths) {
597 RawLightInfo info;
598 info.id = ++nextLightId;
599 info.path = nodePath;
600 info.name = nodePath.filename();
601 info.maxBrightness = std::nullopt;
602 size_t nameStart = info.name.rfind(":");
603 if (nameStart != std::string::npos) {
604 // Trim the name to color name
605 info.name = info.name.substr(nameStart + 1);
606 // Set InputLightClass flag for colors
607 const auto it = LIGHT_CLASSES.find(info.name);
608 if (it != LIGHT_CLASSES.end()) {
609 info.flags |= it->second;
610 }
611 }
612 // Scan the path for all the files
613 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
614 const auto& files = allFilesInPath(nodePath);
615 for (const auto& file : files) {
616 const auto it = LIGHT_CLASSES.find(file.filename().string());
617 if (it != LIGHT_CLASSES.end()) {
618 info.flags |= it->second;
619 // If the node has maximum brightness, read it
620 if (it->second == InputLightClass::MAX_BRIGHTNESS) {
621 std::string str;
622 if (base::ReadFileToString(file, &str)) {
623 info.maxBrightness = std::stoi(str);
624 }
625 }
626 }
627 }
628 lightInfos.insert_or_assign(info.id, info);
Chris Yee2b1e5c2021-03-10 22:45:12 -0800629 ALOGD("configureLightsLocked rawLightId %d name %s", info.id, info.name.c_str());
Chris Ye3fdbfef2021-01-06 18:45:18 -0800630 }
631 return !lightInfos.empty();
632}
633
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100634/**
635 * Get the capabilities for the current process.
636 * Crashes the system if unable to create / check / destroy the capabilities object.
637 */
638class Capabilities final {
639public:
640 explicit Capabilities() {
641 mCaps = cap_get_proc();
642 LOG_ALWAYS_FATAL_IF(mCaps == nullptr, "Could not get capabilities of the current process");
643 }
644
645 /**
646 * Check whether the current process has a specific capability
647 * in the set of effective capabilities.
648 * Return CAP_SET if the process has the requested capability
649 * Return CAP_CLEAR otherwise.
650 */
651 cap_flag_value_t checkEffectiveCapability(cap_value_t capability) {
652 cap_flag_value_t value;
653 const int result = cap_get_flag(mCaps, capability, CAP_EFFECTIVE, &value);
654 LOG_ALWAYS_FATAL_IF(result == -1, "Could not obtain the requested capability");
655 return value;
656 }
657
658 ~Capabilities() {
659 const int result = cap_free(mCaps);
660 LOG_ALWAYS_FATAL_IF(result == -1, "Could not release the capabilities structure");
661 }
662
663private:
664 cap_t mCaps;
665};
666
667static void ensureProcessCanBlockSuspend() {
668 Capabilities capabilities;
669 const bool canBlockSuspend =
670 capabilities.checkEffectiveCapability(CAP_BLOCK_SUSPEND) == CAP_SET;
671 LOG_ALWAYS_FATAL_IF(!canBlockSuspend,
672 "Input must be able to block suspend to properly process events");
673}
674
Michael Wrightd02c5b62014-02-10 15:10:22 -0800675// --- EventHub ---
676
Michael Wrightd02c5b62014-02-10 15:10:22 -0800677const int EventHub::EPOLL_MAX_EVENTS;
678
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700679EventHub::EventHub(void)
680 : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
681 mNextDeviceId(1),
682 mControllerNumbers(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800683 mNeedToSendFinishedDeviceScan(false),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700684 mNeedToReopenDevices(false),
685 mNeedToScanDevices(true),
686 mPendingEventCount(0),
687 mPendingEventIndex(0),
688 mPendingINotify(false) {
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100689 ensureProcessCanBlockSuspend();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800690
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800691 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800692 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800693
Michael Wright8e9a8562022-02-09 13:44:29 +0000694 mINotifyFd = inotify_init1(IN_CLOEXEC);
Usama Arifb27c8e62021-06-03 16:44:09 +0100695
696 std::error_code errorCode;
697 bool isDeviceInotifyAdded = false;
698 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
699 addDeviceInputInotify();
Philip Quinn39b81682019-01-09 22:20:39 -0800700 } else {
Usama Arifb27c8e62021-06-03 16:44:09 +0100701 addDeviceInotify();
702 isDeviceInotifyAdded = true;
703 if (errorCode) {
704 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
705 errorCode.message().c_str());
706 }
707 }
708
709 if (isV4lScanningEnabled() && !isDeviceInotifyAdded) {
710 addDeviceInotify();
711 } else {
Philip Quinn39b81682019-01-09 22:20:39 -0800712 ALOGI("Video device scanning disabled");
713 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800714
Siarhei Vishniakou2d0e9482019-09-24 12:52:47 +0100715 struct epoll_event eventItem = {};
716 eventItem.events = EPOLLIN | EPOLLWAKEUP;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700717 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800718 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800719 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
720
721 int wakeFds[2];
Michael Wright8e9a8562022-02-09 13:44:29 +0000722 result = pipe2(wakeFds, O_CLOEXEC);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800723 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
724
725 mWakeReadPipeFd = wakeFds[0];
726 mWakeWritePipeFd = wakeFds[1];
727
728 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
729 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700730 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800731
732 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
733 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700734 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800735
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700736 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800737 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
738 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700739 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800740}
741
742EventHub::~EventHub(void) {
743 closeAllDevicesLocked();
744
Michael Wrightd02c5b62014-02-10 15:10:22 -0800745 ::close(mEpollFd);
746 ::close(mINotifyFd);
747 ::close(mWakeReadPipeFd);
748 ::close(mWakeWritePipeFd);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800749}
750
Usama Arifb27c8e62021-06-03 16:44:09 +0100751/**
752 * On devices that don't have any input devices (like some development boards), the /dev/input
753 * directory will be absent. However, the user may still plug in an input device at a later time.
754 * Add watch for contents of /dev/input only when /dev/input appears.
755 */
756void EventHub::addDeviceInputInotify() {
757 mDeviceInputWd = inotify_add_watch(mINotifyFd, DEVICE_INPUT_PATH, IN_DELETE | IN_CREATE);
758 LOG_ALWAYS_FATAL_IF(mDeviceInputWd < 0, "Could not register INotify for %s: %s",
759 DEVICE_INPUT_PATH, strerror(errno));
760}
761
762void EventHub::addDeviceInotify() {
763 mDeviceWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
764 LOG_ALWAYS_FATAL_IF(mDeviceWd < 0, "Could not register INotify for %s: %s", DEVICE_PATH,
765 strerror(errno));
766}
767
Michael Wrightd02c5b62014-02-10 15:10:22 -0800768InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000769 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800770 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700771 return device != nullptr ? device->identifier : InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800772}
773
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700774ftl::Flags<InputDeviceClass> EventHub::getDeviceClasses(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000775 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800776 Device* device = getDeviceLocked(deviceId);
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700777 return device != nullptr ? device->classes : ftl::Flags<InputDeviceClass>(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800778}
779
780int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000781 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800782 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700783 return device != nullptr ? device->controllerNumber : 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800784}
785
786void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
Chris Ye87143712020-11-10 05:05:58 +0000787 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700789 if (device != nullptr && device->configuration) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800790 *outConfiguration = *device->configuration;
791 } else {
792 outConfiguration->clear();
793 }
794}
795
796status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700797 RawAbsoluteAxisInfo* outAxisInfo) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800798 outAxisInfo->clear();
799
800 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000801 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800802
803 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700804 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800805 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700806 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
807 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
808 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800809 return -errno;
810 }
811
812 if (info.minimum != info.maximum) {
813 outAxisInfo->valid = true;
814 outAxisInfo->minValue = info.minimum;
815 outAxisInfo->maxValue = info.maximum;
816 outAxisInfo->flat = info.flat;
817 outAxisInfo->fuzz = info.fuzz;
818 outAxisInfo->resolution = info.resolution;
819 }
820 return OK;
821 }
822 }
823 return -1;
824}
825
826bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
827 if (axis >= 0 && axis <= REL_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000828 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800829 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700830 return device != nullptr ? device->relBitmask.test(axis) : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800831 }
832 return false;
833}
834
835bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
Chris Ye87143712020-11-10 05:05:58 +0000836 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800837
Chris Ye989bb932020-07-04 16:18:59 -0700838 Device* device = getDeviceLocked(deviceId);
839 return property >= 0 && property <= INPUT_PROP_MAX && device != nullptr
840 ? device->propBitmask.test(property)
841 : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800842}
843
Chris Yef59a2f42020-10-16 12:55:26 -0700844bool EventHub::hasMscEvent(int32_t deviceId, int mscEvent) const {
845 std::scoped_lock _l(mLock);
846
847 Device* device = getDeviceLocked(deviceId);
848 return mscEvent >= 0 && mscEvent <= MSC_MAX && device != nullptr
849 ? device->mscBitmask.test(mscEvent)
850 : false;
851}
852
Michael Wrightd02c5b62014-02-10 15:10:22 -0800853int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
854 if (scanCode >= 0 && scanCode <= KEY_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000855 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800856
857 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700858 if (device != nullptr && device->hasValidFd() && device->keyBitmask.test(scanCode)) {
859 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
860 return device->keyState.test(scanCode) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800861 }
862 }
863 }
864 return AKEY_STATE_UNKNOWN;
865}
866
867int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
Chris Ye87143712020-11-10 05:05:58 +0000868 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800869
870 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700871 if (device != nullptr && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou53f0a5e2022-05-18 09:45:54 -0700872 std::vector<int32_t> scanCodes = device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800873 if (scanCodes.size() != 0) {
Chris Ye66fbac32020-07-06 20:36:43 -0700874 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800875 for (size_t i = 0; i < scanCodes.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800876 int32_t sc = scanCodes[i];
Chris Ye66fbac32020-07-06 20:36:43 -0700877 if (sc >= 0 && sc <= KEY_MAX && device->keyState.test(sc)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800878 return AKEY_STATE_DOWN;
879 }
880 }
881 return AKEY_STATE_UP;
882 }
883 }
884 }
885 return AKEY_STATE_UNKNOWN;
886}
887
Philip Junker4af3b3d2021-12-14 10:36:55 +0100888int32_t EventHub::getKeyCodeForKeyLocation(int32_t deviceId, int32_t locationKeyCode) const {
889 std::scoped_lock _l(mLock);
890
891 Device* device = getDeviceLocked(deviceId);
892 if (device == nullptr || !device->hasValidFd() || device->keyMap.keyCharacterMap == nullptr ||
893 device->keyMap.keyLayoutMap == nullptr) {
894 return AKEYCODE_UNKNOWN;
895 }
Siarhei Vishniakou53f0a5e2022-05-18 09:45:54 -0700896 std::vector<int32_t> scanCodes =
897 device->keyMap.keyLayoutMap->findScanCodesForKey(locationKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +0100898 if (scanCodes.empty()) {
899 ALOGW("Failed to get key code for key location: no scan code maps to key code %d for input"
900 "device %d",
901 locationKeyCode, deviceId);
902 return AKEYCODE_UNKNOWN;
903 }
904 if (scanCodes.size() > 1) {
905 ALOGW("Multiple scan codes map to the same key code %d, returning only the first match",
906 locationKeyCode);
907 }
908 int32_t outKeyCode;
909 status_t mapKeyRes =
910 device->getKeyCharacterMap()->mapKey(scanCodes[0], 0 /*usageCode*/, &outKeyCode);
911 switch (mapKeyRes) {
912 case OK:
913 return outKeyCode;
914 case NAME_NOT_FOUND:
915 // key character map doesn't re-map this scanCode, hence the keyCode remains the same
916 return locationKeyCode;
917 default:
918 ALOGW("Failed to get key code for key location: Key character map returned error %s",
919 statusToString(mapKeyRes).c_str());
920 return AKEYCODE_UNKNOWN;
921 }
922}
923
Michael Wrightd02c5b62014-02-10 15:10:22 -0800924int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
925 if (sw >= 0 && sw <= SW_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000926 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800927
928 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700929 if (device != nullptr && device->hasValidFd() && device->swBitmask.test(sw)) {
930 if (device->readDeviceBitMask(EVIOCGSW(0), device->swState) >= 0) {
931 return device->swState.test(sw) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800932 }
933 }
934 }
935 return AKEY_STATE_UNKNOWN;
936}
937
938status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
939 *outValue = 0;
940
941 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000942 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800943
944 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700945 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800946 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700947 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
948 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
949 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800950 return -errno;
951 }
952
953 *outValue = info.value;
954 return OK;
955 }
956 }
957 return -1;
958}
959
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700960bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes, const int32_t* keyCodes,
961 uint8_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +0000962 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800963
964 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700965 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800966 for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) {
Siarhei Vishniakou53f0a5e2022-05-18 09:45:54 -0700967 std::vector<int32_t> scanCodes =
968 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCodes[codeIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800969
Siarhei Vishniakou53f0a5e2022-05-18 09:45:54 -0700970 // check the possible scan codes identified by the layout map against the
971 // map of codes actually emitted by the driver
972 for (size_t sc = 0; sc < scanCodes.size(); sc++) {
973 if (device->keyBitmask.test(scanCodes[sc])) {
974 outFlags[codeIndex] = 1;
975 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800976 }
977 }
978 }
979 return true;
980 }
981 return false;
982}
983
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700984status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
985 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +0000986 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800987 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700988 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800989
Chris Ye66fbac32020-07-06 20:36:43 -0700990 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800991 // Check the key character map first.
Chris Ye3a1e4462020-08-12 10:13:15 -0700992 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
993 if (kcm) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800994 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
995 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700996 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800997 }
998 }
999
1000 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001001 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -08001002 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001003 status = NO_ERROR;
1004 }
1005 }
1006
1007 if (status == NO_ERROR) {
Chris Ye3a1e4462020-08-12 10:13:15 -07001008 if (kcm) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001009 kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState);
1010 } else {
1011 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001012 }
1013 }
1014 }
1015
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001016 if (status != NO_ERROR) {
1017 *outKeycode = 0;
1018 *outFlags = 0;
1019 *outMetaState = metaState;
1020 }
1021
1022 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001023}
1024
1025status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
Chris Ye87143712020-11-10 05:05:58 +00001026 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001027 Device* device = getDeviceLocked(deviceId);
1028
Siarhei Vishniakou53f0a5e2022-05-18 09:45:54 -07001029 if (device == nullptr || !device->keyMap.haveKeyLayout()) {
1030 return NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001031 }
Siarhei Vishniakou53f0a5e2022-05-18 09:45:54 -07001032 std::optional<AxisInfo> info = device->keyMap.keyLayoutMap->mapAxis(scanCode);
1033 if (!info.has_value()) {
1034 return NAME_NOT_FOUND;
1035 }
1036 *outAxisInfo = *info;
1037 return NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001038}
1039
Chris Yef59a2f42020-10-16 12:55:26 -07001040base::Result<std::pair<InputDeviceSensorType, int32_t>> EventHub::mapSensor(int32_t deviceId,
1041 int32_t absCode) {
1042 std::scoped_lock _l(mLock);
1043 Device* device = getDeviceLocked(deviceId);
1044
1045 if (device != nullptr && device->keyMap.haveKeyLayout()) {
1046 return device->keyMap.keyLayoutMap->mapSensor(absCode);
1047 }
1048 return Errorf("Device not found or device has no key layout.");
1049}
1050
Chris Yee2b1e5c2021-03-10 22:45:12 -08001051// Gets the battery info map from battery ID to RawBatteryInfo of the miscellaneous device
1052// associated with the device ID. Returns an empty map if no miscellaneous device found.
1053const std::unordered_map<int32_t, RawBatteryInfo>& EventHub::getBatteryInfoLocked(
1054 int32_t deviceId) const {
1055 static const std::unordered_map<int32_t, RawBatteryInfo> EMPTY_BATTERY_INFO = {};
1056 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001057 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001058 return EMPTY_BATTERY_INFO;
1059 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001060 return device->associatedDevice->batteryInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001061}
1062
1063const std::vector<int32_t> EventHub::getRawBatteryIds(int32_t deviceId) {
1064 std::scoped_lock _l(mLock);
1065 std::vector<int32_t> batteryIds;
1066
1067 for (const auto [id, info] : getBatteryInfoLocked(deviceId)) {
1068 batteryIds.push_back(id);
1069 }
1070
1071 return batteryIds;
1072}
1073
1074std::optional<RawBatteryInfo> EventHub::getRawBatteryInfo(int32_t deviceId, int32_t batteryId) {
1075 std::scoped_lock _l(mLock);
1076
1077 const auto infos = getBatteryInfoLocked(deviceId);
1078
1079 auto it = infos.find(batteryId);
1080 if (it != infos.end()) {
1081 return it->second;
1082 }
1083
1084 return std::nullopt;
1085}
1086
1087// Gets the light info map from light ID to RawLightInfo of the miscellaneous device associated
1088// with the deivice ID. Returns an empty map if no miscellaneous device found.
1089const std::unordered_map<int32_t, RawLightInfo>& EventHub::getLightInfoLocked(
1090 int32_t deviceId) const {
1091 static const std::unordered_map<int32_t, RawLightInfo> EMPTY_LIGHT_INFO = {};
1092 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001093 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001094 return EMPTY_LIGHT_INFO;
1095 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001096 return device->associatedDevice->lightInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001097}
1098
Chris Ye3fdbfef2021-01-06 18:45:18 -08001099const std::vector<int32_t> EventHub::getRawLightIds(int32_t deviceId) {
1100 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001101 std::vector<int32_t> lightIds;
1102
Chris Yee2b1e5c2021-03-10 22:45:12 -08001103 for (const auto [id, info] : getLightInfoLocked(deviceId)) {
1104 lightIds.push_back(id);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001105 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001106
Chris Ye3fdbfef2021-01-06 18:45:18 -08001107 return lightIds;
1108}
1109
1110std::optional<RawLightInfo> EventHub::getRawLightInfo(int32_t deviceId, int32_t lightId) {
1111 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001112
Chris Yee2b1e5c2021-03-10 22:45:12 -08001113 const auto infos = getLightInfoLocked(deviceId);
1114
1115 auto it = infos.find(lightId);
1116 if (it != infos.end()) {
1117 return it->second;
Chris Ye3fdbfef2021-01-06 18:45:18 -08001118 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001119
Chris Ye3fdbfef2021-01-06 18:45:18 -08001120 return std::nullopt;
1121}
1122
1123std::optional<int32_t> EventHub::getLightBrightness(int32_t deviceId, int32_t lightId) {
1124 std::scoped_lock _l(mLock);
1125
Chris Yee2b1e5c2021-03-10 22:45:12 -08001126 const auto infos = getLightInfoLocked(deviceId);
1127 auto it = infos.find(lightId);
1128 if (it == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001129 return std::nullopt;
1130 }
1131 std::string buffer;
1132 if (!base::ReadFileToString(it->second.path / LIGHT_NODES.at(InputLightClass::BRIGHTNESS),
1133 &buffer)) {
1134 return std::nullopt;
1135 }
1136 return std::stoi(buffer);
1137}
1138
1139std::optional<std::unordered_map<LightColor, int32_t>> EventHub::getLightIntensities(
1140 int32_t deviceId, int32_t lightId) {
1141 std::scoped_lock _l(mLock);
1142
Chris Yee2b1e5c2021-03-10 22:45:12 -08001143 const auto infos = getLightInfoLocked(deviceId);
1144 auto lightIt = infos.find(lightId);
1145 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001146 return std::nullopt;
1147 }
1148
1149 auto ret =
1150 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1151
1152 if (!ret.has_value()) {
1153 return std::nullopt;
1154 }
1155 std::array<LightColor, COLOR_NUM> colors = ret.value();
1156
1157 std::string intensityStr;
1158 if (!base::ReadFileToString(lightIt->second.path /
1159 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY),
1160 &intensityStr)) {
1161 return std::nullopt;
1162 }
1163
1164 // Intensity node outputs 3 color values
1165 std::regex intensityPattern("([0-9]+)\\s([0-9]+)\\s([0-9]+)[\\n]");
1166 std::smatch results;
1167
1168 if (!std::regex_match(intensityStr, results, intensityPattern)) {
1169 return std::nullopt;
1170 }
1171 std::unordered_map<LightColor, int32_t> intensities;
1172 for (size_t i = 1; i < results.size(); i++) {
1173 int value = std::stoi(results[i].str());
1174 intensities.emplace(colors[i - 1], value);
1175 }
1176 return intensities;
1177}
1178
1179void EventHub::setLightBrightness(int32_t deviceId, int32_t lightId, int32_t brightness) {
1180 std::scoped_lock _l(mLock);
1181
Chris Yee2b1e5c2021-03-10 22:45:12 -08001182 const auto infos = getLightInfoLocked(deviceId);
1183 auto lightIt = infos.find(lightId);
1184 if (lightIt == infos.end()) {
1185 ALOGE("%s lightId %d not found ", __func__, lightId);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001186 return;
1187 }
1188
1189 if (!base::WriteStringToFile(std::to_string(brightness),
1190 lightIt->second.path /
1191 LIGHT_NODES.at(InputLightClass::BRIGHTNESS))) {
1192 ALOGE("Can not write to file, error: %s", strerror(errno));
1193 }
1194}
1195
1196void EventHub::setLightIntensities(int32_t deviceId, int32_t lightId,
1197 std::unordered_map<LightColor, int32_t> intensities) {
1198 std::scoped_lock _l(mLock);
1199
Chris Yee2b1e5c2021-03-10 22:45:12 -08001200 const auto infos = getLightInfoLocked(deviceId);
1201 auto lightIt = infos.find(lightId);
1202 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001203 ALOGE("Light Id %d does not exist.", lightId);
1204 return;
1205 }
1206
1207 auto ret =
1208 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1209
1210 if (!ret.has_value()) {
1211 return;
1212 }
1213 std::array<LightColor, COLOR_NUM> colors = ret.value();
1214
1215 std::string rgbStr;
1216 for (size_t i = 0; i < COLOR_NUM; i++) {
1217 auto it = intensities.find(colors[i]);
1218 if (it != intensities.end()) {
1219 rgbStr += std::to_string(it->second);
1220 // Insert space between colors
1221 if (i < COLOR_NUM - 1) {
1222 rgbStr += " ";
1223 }
1224 }
1225 }
1226 // Append new line
1227 rgbStr += "\n";
1228
1229 if (!base::WriteStringToFile(rgbStr,
1230 lightIt->second.path /
1231 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY))) {
1232 ALOGE("Can not write to file, error: %s", strerror(errno));
1233 }
1234}
1235
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001236void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Chris Ye87143712020-11-10 05:05:58 +00001237 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001238
1239 mExcludedDevices = devices;
1240}
1241
1242bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
Chris Ye87143712020-11-10 05:05:58 +00001243 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001244 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001245 if (device != nullptr && scanCode >= 0 && scanCode <= KEY_MAX) {
1246 return device->keyBitmask.test(scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001247 }
1248 return false;
1249}
1250
Arthur Hungcb40a002021-08-03 14:31:01 +00001251bool EventHub::hasKeyCode(int32_t deviceId, int32_t keyCode) const {
1252 std::scoped_lock _l(mLock);
1253 Device* device = getDeviceLocked(deviceId);
1254 if (device != nullptr) {
1255 return device->hasKeycodeLocked(keyCode);
1256 }
1257 return false;
1258}
1259
Michael Wrightd02c5b62014-02-10 15:10:22 -08001260bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
Chris Ye87143712020-11-10 05:05:58 +00001261 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001262 Device* device = getDeviceLocked(deviceId);
1263 int32_t sc;
Chris Ye989bb932020-07-04 16:18:59 -07001264 if (device != nullptr && device->mapLed(led, &sc) == NO_ERROR) {
Chris Ye66fbac32020-07-06 20:36:43 -07001265 return device->ledBitmask.test(sc);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001266 }
1267 return false;
1268}
1269
1270void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
Chris Ye87143712020-11-10 05:05:58 +00001271 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001272 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -07001273 if (device != nullptr && device->hasValidFd()) {
1274 device->setLedStateLocked(led, on);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001275 }
1276}
1277
1278void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001279 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001280 outVirtualKeys.clear();
1281
Chris Ye87143712020-11-10 05:05:58 +00001282 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001283 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001284 if (device != nullptr && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001285 const std::vector<VirtualKeyDefinition> virtualKeys =
1286 device->virtualKeyMap->getVirtualKeys();
1287 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001288 }
1289}
1290
Chris Ye3a1e4462020-08-12 10:13:15 -07001291const std::shared_ptr<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001292 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001293 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001294 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001295 return device->getKeyCharacterMap();
1296 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001297 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001298}
1299
Chris Ye3a1e4462020-08-12 10:13:15 -07001300bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, std::shared_ptr<KeyCharacterMap> map) {
Chris Ye87143712020-11-10 05:05:58 +00001301 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001302 Device* device = getDeviceLocked(deviceId);
Philip Junker90bc9492021-12-10 18:39:42 +01001303 if (device == nullptr || map == nullptr || device->keyMap.keyCharacterMap == nullptr) {
1304 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001305 }
Philip Junker90bc9492021-12-10 18:39:42 +01001306 device->keyMap.keyCharacterMap->combine(*map);
1307 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001308}
1309
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001310static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
1311 std::string rawDescriptor;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001312 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001313 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001314 if (!identifier.uniqueId.empty()) {
1315 rawDescriptor += "uniqueId:";
1316 rawDescriptor += identifier.uniqueId;
Josh Bartel938632f2022-07-19 15:34:22 -05001317 }
1318 if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001319 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001320 }
1321
1322 if (identifier.vendor == 0 && identifier.product == 0) {
1323 // If we don't know the vendor and product id, then the device is probably
1324 // built-in so we need to rely on other information to uniquely identify
1325 // the input device. Usually we try to avoid relying on the device name or
1326 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001327 if (!identifier.name.empty()) {
1328 rawDescriptor += "name:";
1329 rawDescriptor += identifier.name;
1330 } else if (!identifier.location.empty()) {
1331 rawDescriptor += "location:";
1332 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001333 }
1334 }
1335 identifier.descriptor = sha1(rawDescriptor);
1336 return rawDescriptor;
1337}
1338
1339void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
1340 // Compute a device descriptor that uniquely identifies the device.
1341 // The descriptor is assumed to be a stable identifier. Its value should not
1342 // change between reboots, reconnections, firmware updates or new releases
1343 // of Android. In practice we sometimes get devices that cannot be uniquely
1344 // identified. In this case we enforce uniqueness between connected devices.
1345 // Ideally, we also want the descriptor to be short and relatively opaque.
Josh Bartel938632f2022-07-19 15:34:22 -05001346 // Note that we explicitly do not use the path or location for external devices
1347 // as their path or location will change as they are plugged/unplugged or moved
1348 // to different ports. We do fallback to using name and location in the case of
1349 // internal devices which are detected by the vendor and product being 0 in
1350 // generateDescriptor. If two identical descriptors are detected we will fallback
1351 // to using a 'nonce' and incrementing it until the new descriptor no longer has
1352 // a match with any existing descriptors.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001353
1354 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001355 std::string rawDescriptor = generateDescriptor(identifier);
Josh Bartel938632f2022-07-19 15:34:22 -05001356 // Enforce that the generated descriptor is unique.
1357 while (hasDeviceWithDescriptorLocked(identifier.descriptor)) {
1358 identifier.nonce++;
1359 rawDescriptor = generateDescriptor(identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001360 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001361 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001362 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001363}
1364
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001365void EventHub::vibrate(int32_t deviceId, const VibrationElement& element) {
Chris Ye87143712020-11-10 05:05:58 +00001366 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001367 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001368 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001369 ff_effect effect;
1370 memset(&effect, 0, sizeof(effect));
1371 effect.type = FF_RUMBLE;
1372 effect.id = device->ffEffectId;
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001373 // evdev FF_RUMBLE effect only supports two channels of vibration.
Chris Ye6393a262020-08-04 19:41:36 -07001374 effect.u.rumble.strong_magnitude = element.getMagnitude(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1375 effect.u.rumble.weak_magnitude = element.getMagnitude(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001376 effect.replay.length = element.duration.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001377 effect.replay.delay = 0;
1378 if (ioctl(device->fd, EVIOCSFF, &effect)) {
1379 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001380 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001381 return;
1382 }
1383 device->ffEffectId = effect.id;
1384
1385 struct input_event ev;
1386 ev.time.tv_sec = 0;
1387 ev.time.tv_usec = 0;
1388 ev.type = EV_FF;
1389 ev.code = device->ffEffectId;
1390 ev.value = 1;
1391 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1392 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001393 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001394 return;
1395 }
1396 device->ffEffectPlaying = true;
1397 }
1398}
1399
1400void EventHub::cancelVibrate(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001401 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001402 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001403 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001404 if (device->ffEffectPlaying) {
1405 device->ffEffectPlaying = false;
1406
1407 struct input_event ev;
1408 ev.time.tv_sec = 0;
1409 ev.time.tv_usec = 0;
1410 ev.type = EV_FF;
1411 ev.code = device->ffEffectId;
1412 ev.value = 0;
1413 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1414 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001415 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001416 return;
1417 }
1418 }
1419 }
1420}
1421
Chris Ye87143712020-11-10 05:05:58 +00001422std::vector<int32_t> EventHub::getVibratorIds(int32_t deviceId) {
1423 std::scoped_lock _l(mLock);
1424 std::vector<int32_t> vibrators;
1425 Device* device = getDeviceLocked(deviceId);
1426 if (device != nullptr && device->hasValidFd() &&
1427 device->classes.test(InputDeviceClass::VIBRATOR)) {
1428 vibrators.push_back(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1429 vibrators.push_back(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
1430 }
1431 return vibrators;
1432}
1433
Josh Bartel938632f2022-07-19 15:34:22 -05001434/**
1435 * Checks both mDevices and mOpeningDevices for a device with the descriptor passed.
1436 */
1437bool EventHub::hasDeviceWithDescriptorLocked(const std::string& descriptor) const {
1438 for (const auto& device : mOpeningDevices) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001439 if (descriptor == device->identifier.descriptor) {
Josh Bartel938632f2022-07-19 15:34:22 -05001440 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001441 }
1442 }
Josh Bartel938632f2022-07-19 15:34:22 -05001443
1444 for (const auto& [id, device] : mDevices) {
1445 if (descriptor == device->identifier.descriptor) {
1446 return true;
1447 }
1448 }
1449 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001450}
1451
1452EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001453 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001454 deviceId = mBuiltInKeyboardId;
1455 }
Chris Ye989bb932020-07-04 16:18:59 -07001456 const auto& it = mDevices.find(deviceId);
1457 return it != mDevices.end() ? it->second.get() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001458}
1459
Chris Ye8594e192020-07-14 10:34:06 -07001460EventHub::Device* EventHub::getDeviceByPathLocked(const std::string& devicePath) const {
Chris Ye989bb932020-07-04 16:18:59 -07001461 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001462 if (device->path == devicePath) {
Chris Ye989bb932020-07-04 16:18:59 -07001463 return device.get();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001464 }
1465 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001466 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001467}
1468
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001469/**
1470 * The file descriptor could be either input device, or a video device (associated with a
1471 * specific input device). Check both cases here, and return the device that this event
1472 * belongs to. Caller can compare the fd's once more to determine event type.
1473 * Looks through all input devices, and only attached video devices. Unattached video
1474 * devices are ignored.
1475 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001476EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
Chris Ye989bb932020-07-04 16:18:59 -07001477 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001478 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001479 // This is an input device event
Chris Ye989bb932020-07-04 16:18:59 -07001480 return device.get();
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001481 }
1482 if (device->videoDevice && device->videoDevice->getFd() == fd) {
1483 // This is a video device event
Chris Ye989bb932020-07-04 16:18:59 -07001484 return device.get();
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001485 }
1486 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001487 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
1488 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001489 return nullptr;
1490}
1491
Chris Yee2b1e5c2021-03-10 22:45:12 -08001492std::optional<int32_t> EventHub::getBatteryCapacity(int32_t deviceId, int32_t batteryId) const {
Andy Chen22c330c2022-08-29 20:07:10 -04001493 std::filesystem::path batteryPath;
1494 {
1495 // Do not read the sysfs node to get the battery state while holding
1496 // the EventHub lock. For some peripheral devices, reading battery state
1497 // can be broken and take 5+ seconds. Holding the lock in this case would
1498 // block all other event processing during this time. For now, we assume this
1499 // call never happens on the InputReader thread and read the sysfs node outside
1500 // the lock to prevent event processing from being blocked by this call.
1501 std::scoped_lock _l(mLock);
Kim Low03ea0352020-11-06 12:45:07 -08001502
Andy Chen22c330c2022-08-29 20:07:10 -04001503 const auto infos = getBatteryInfoLocked(deviceId);
1504 auto it = infos.find(batteryId);
1505 if (it == infos.end()) {
1506 return std::nullopt;
1507 }
1508 batteryPath = it->second.path;
1509 } // release lock
1510
Chris Yee2b1e5c2021-03-10 22:45:12 -08001511 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001512
1513 // Some devices report battery capacity as an integer through the "capacity" file
Andy Chen22c330c2022-08-29 20:07:10 -04001514 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001515 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001516 return std::stoi(base::Trim(buffer));
Kim Low03ea0352020-11-06 12:45:07 -08001517 }
1518
1519 // Other devices report capacity as an enum value POWER_SUPPLY_CAPACITY_LEVEL_XXX
1520 // These values are taken from kernel source code include/linux/power_supply.h
Andy Chen22c330c2022-08-29 20:07:10 -04001521 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY_LEVEL),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001522 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001523 // Remove any white space such as trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001524 const auto levelIt = BATTERY_LEVEL.find(base::Trim(buffer));
1525 if (levelIt != BATTERY_LEVEL.end()) {
1526 return levelIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001527 }
1528 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001529
Kim Low03ea0352020-11-06 12:45:07 -08001530 return std::nullopt;
1531}
1532
Chris Yee2b1e5c2021-03-10 22:45:12 -08001533std::optional<int32_t> EventHub::getBatteryStatus(int32_t deviceId, int32_t batteryId) const {
Andy Chen22c330c2022-08-29 20:07:10 -04001534 std::filesystem::path batteryPath;
1535 {
1536 // Do not read the sysfs node to get the battery state while holding
1537 // the EventHub lock. For some peripheral devices, reading battery state
1538 // can be broken and take 5+ seconds. Holding the lock in this case would
1539 // block all other event processing during this time. For now, we assume this
1540 // call never happens on the InputReader thread and read the sysfs node outside
1541 // the lock to prevent event processing from being blocked by this call.
1542 std::scoped_lock _l(mLock);
1543
1544 const auto infos = getBatteryInfoLocked(deviceId);
1545 auto it = infos.find(batteryId);
1546 if (it == infos.end()) {
1547 return std::nullopt;
1548 }
1549 batteryPath = it->second.path;
1550 } // release lock
1551
Chris Yee2b1e5c2021-03-10 22:45:12 -08001552 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001553
Andy Chen22c330c2022-08-29 20:07:10 -04001554 if (!base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::STATUS),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001555 &buffer)) {
Kim Low03ea0352020-11-06 12:45:07 -08001556 ALOGE("Failed to read sysfs battery info: %s", strerror(errno));
1557 return std::nullopt;
1558 }
1559
Chris Yed1936772021-02-22 10:30:40 -08001560 // Remove white space like trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001561 const auto statusIt = BATTERY_STATUS.find(base::Trim(buffer));
1562 if (statusIt != BATTERY_STATUS.end()) {
1563 return statusIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001564 }
1565
1566 return std::nullopt;
1567}
1568
Michael Wrightd02c5b62014-02-10 15:10:22 -08001569size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
1570 ALOG_ASSERT(bufferSize >= 1);
1571
Chris Ye87143712020-11-10 05:05:58 +00001572 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001573
1574 struct input_event readBuffer[bufferSize];
1575
1576 RawEvent* event = buffer;
1577 size_t capacity = bufferSize;
1578 bool awoken = false;
1579 for (;;) {
1580 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
1581
1582 // Reopen input devices if needed.
1583 if (mNeedToReopenDevices) {
1584 mNeedToReopenDevices = false;
1585
1586 ALOGI("Reopening all input devices due to a configuration change.");
1587
1588 closeAllDevicesLocked();
1589 mNeedToScanDevices = true;
1590 break; // return to the caller before we actually rescan
1591 }
1592
1593 // Report any devices that had last been added/removed.
Chris Ye989bb932020-07-04 16:18:59 -07001594 for (auto it = mClosingDevices.begin(); it != mClosingDevices.end();) {
1595 std::unique_ptr<Device> device = std::move(*it);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001596 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001597 event->when = now;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001598 event->deviceId = (device->id == mBuiltInKeyboardId)
1599 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
1600 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001601 event->type = DEVICE_REMOVED;
1602 event += 1;
Chris Ye989bb932020-07-04 16:18:59 -07001603 it = mClosingDevices.erase(it);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001604 mNeedToSendFinishedDeviceScan = true;
1605 if (--capacity == 0) {
1606 break;
1607 }
1608 }
1609
1610 if (mNeedToScanDevices) {
1611 mNeedToScanDevices = false;
1612 scanDevicesLocked();
1613 mNeedToSendFinishedDeviceScan = true;
1614 }
1615
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001616 while (!mOpeningDevices.empty()) {
1617 std::unique_ptr<Device> device = std::move(*mOpeningDevices.rbegin());
1618 mOpeningDevices.pop_back();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001619 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001620 event->when = now;
1621 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1622 event->type = DEVICE_ADDED;
1623 event += 1;
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001624
1625 // Try to find a matching video device by comparing device names
1626 for (auto it = mUnattachedVideoDevices.begin(); it != mUnattachedVideoDevices.end();
1627 it++) {
1628 std::unique_ptr<TouchVideoDevice>& videoDevice = *it;
Chris Yed3fef462021-03-07 17:10:08 -08001629 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001630 // videoDevice was transferred to 'device'
1631 it = mUnattachedVideoDevices.erase(it);
1632 break;
1633 }
1634 }
1635
1636 auto [dev_it, inserted] = mDevices.insert_or_assign(device->id, std::move(device));
1637 if (!inserted) {
Chris Ye989bb932020-07-04 16:18:59 -07001638 ALOGW("Device id %d exists, replaced.", device->id);
1639 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001640 mNeedToSendFinishedDeviceScan = true;
1641 if (--capacity == 0) {
1642 break;
1643 }
1644 }
1645
1646 if (mNeedToSendFinishedDeviceScan) {
1647 mNeedToSendFinishedDeviceScan = false;
1648 event->when = now;
1649 event->type = FINISHED_DEVICE_SCAN;
1650 event += 1;
1651 if (--capacity == 0) {
1652 break;
1653 }
1654 }
1655
1656 // Grab the next input event.
1657 bool deviceChanged = false;
1658 while (mPendingEventIndex < mPendingEventCount) {
1659 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001660 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001661 if (eventItem.events & EPOLLIN) {
1662 mPendingINotify = true;
1663 } else {
1664 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
1665 }
1666 continue;
1667 }
1668
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001669 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001670 if (eventItem.events & EPOLLIN) {
1671 ALOGV("awoken after wake()");
1672 awoken = true;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001673 char wakeReadBuffer[16];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001674 ssize_t nRead;
1675 do {
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001676 nRead = read(mWakeReadPipeFd, wakeReadBuffer, sizeof(wakeReadBuffer));
1677 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(wakeReadBuffer));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001678 } else {
1679 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001680 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001681 }
1682 continue;
1683 }
1684
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001685 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Chris Ye989bb932020-07-04 16:18:59 -07001686 if (device == nullptr) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001687 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
1688 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001689 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001690 continue;
1691 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001692 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
1693 if (eventItem.events & EPOLLIN) {
1694 size_t numFrames = device->videoDevice->readAndQueueFrames();
1695 if (numFrames == 0) {
1696 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001697 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001698 }
1699 } else if (eventItem.events & EPOLLHUP) {
1700 // TODO(b/121395353) - consider adding EPOLLRDHUP
1701 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001702 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001703 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1704 device->videoDevice = nullptr;
1705 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001706 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1707 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001708 ALOG_ASSERT(!DEBUG);
1709 }
1710 continue;
1711 }
1712 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -08001713 if (eventItem.events & EPOLLIN) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001714 int32_t readSize =
1715 read(device->fd, readBuffer, sizeof(struct input_event) * capacity);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001716 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
1717 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -07001718 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001719 " bufferSize: %zu capacity: %zu errno: %d)\n",
1720 device->fd, readSize, bufferSize, capacity, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001721 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001722 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001723 } else if (readSize < 0) {
1724 if (errno != EAGAIN && errno != EINTR) {
1725 ALOGW("could not get event (errno=%d)", errno);
1726 }
1727 } else if ((readSize % sizeof(struct input_event)) != 0) {
1728 ALOGE("could not get event (wrong size: %d)", readSize);
1729 } else {
1730 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1731
1732 size_t count = size_t(readSize) / sizeof(struct input_event);
1733 for (size_t i = 0; i < count; i++) {
1734 struct input_event& iev = readBuffer[i];
Siarhei Vishniakou592bac22018-11-08 19:42:38 -08001735 event->when = processEventTimestamp(iev);
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001736 event->readTime = systemTime(SYSTEM_TIME_MONOTONIC);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001737 event->deviceId = deviceId;
1738 event->type = iev.type;
1739 event->code = iev.code;
1740 event->value = iev.value;
1741 event += 1;
1742 capacity -= 1;
1743 }
1744 if (capacity == 0) {
1745 // The result buffer is full. Reset the pending event index
1746 // so we will try to read the device again on the next iteration.
1747 mPendingEventIndex -= 1;
1748 break;
1749 }
1750 }
1751 } else if (eventItem.events & EPOLLHUP) {
1752 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001753 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001754 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001755 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001756 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001757 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1758 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001759 }
1760 }
1761
1762 // readNotify() will modify the list of devices so this must be done after
1763 // processing all other events to ensure that we read all remaining events
1764 // before closing the devices.
1765 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
1766 mPendingINotify = false;
1767 readNotifyLocked();
1768 deviceChanged = true;
1769 }
1770
1771 // Report added or removed devices immediately.
1772 if (deviceChanged) {
1773 continue;
1774 }
1775
1776 // Return now if we have collected any events or if we were explicitly awoken.
1777 if (event != buffer || awoken) {
1778 break;
1779 }
1780
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001781 // Poll for events.
1782 // When a device driver has pending (unread) events, it acquires
1783 // a kernel wake lock. Once the last pending event has been read, the device
1784 // driver will release the kernel wake lock, but the epoll will hold the wakelock,
1785 // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
1786 // is called again for the same fd that produced the event.
1787 // Thus the system can only sleep if there are no events pending or
1788 // currently being processed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001789 //
1790 // The timeout is advisory only. If the device is asleep, it will not wake just to
1791 // service the timeout.
1792 mPendingEventIndex = 0;
1793
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001794 mLock.unlock(); // release lock before poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001795
1796 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1797
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001798 mLock.lock(); // reacquire lock after poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799
1800 if (pollResult == 0) {
1801 // Timed out.
1802 mPendingEventCount = 0;
1803 break;
1804 }
1805
1806 if (pollResult < 0) {
1807 // An error occurred.
1808 mPendingEventCount = 0;
1809
1810 // Sleep after errors to avoid locking up the system.
1811 // Hopefully the error is transient.
1812 if (errno != EINTR) {
1813 ALOGW("poll failed (errno=%d)\n", errno);
1814 usleep(100000);
1815 }
1816 } else {
1817 // Some events occurred.
1818 mPendingEventCount = size_t(pollResult);
1819 }
1820 }
1821
1822 // All done, return the number of events we read.
1823 return event - buffer;
1824}
1825
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001826std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001827 std::scoped_lock _l(mLock);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001828
1829 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001830 if (device == nullptr || !device->videoDevice) {
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001831 return {};
1832 }
1833 return device->videoDevice->consumeFrames();
1834}
1835
Michael Wrightd02c5b62014-02-10 15:10:22 -08001836void EventHub::wake() {
1837 ALOGV("wake() called");
1838
1839 ssize_t nWrite;
1840 do {
1841 nWrite = write(mWakeWritePipeFd, "W", 1);
1842 } while (nWrite == -1 && errno == EINTR);
1843
1844 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001845 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001846 }
1847}
1848
1849void EventHub::scanDevicesLocked() {
Usama Arifb27c8e62021-06-03 16:44:09 +01001850 status_t result;
1851 std::error_code errorCode;
1852
1853 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
1854 result = scanDirLocked(DEVICE_INPUT_PATH);
1855 if (result < 0) {
1856 ALOGE("scan dir failed for %s", DEVICE_INPUT_PATH);
1857 }
1858 } else {
1859 if (errorCode) {
1860 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
1861 errorCode.message().c_str());
1862 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001863 }
Philip Quinn39b81682019-01-09 22:20:39 -08001864 if (isV4lScanningEnabled()) {
Usama Arifb27c8e62021-06-03 16:44:09 +01001865 result = scanVideoDirLocked(DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08001866 if (result != OK) {
Usama Arifb27c8e62021-06-03 16:44:09 +01001867 ALOGE("scan video dir failed for %s", DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08001868 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001869 }
Chris Ye989bb932020-07-04 16:18:59 -07001870 if (mDevices.find(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) == mDevices.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001871 createVirtualKeyboardLocked();
1872 }
1873}
1874
1875// ----------------------------------------------------------------------------
1876
Michael Wrightd02c5b62014-02-10 15:10:22 -08001877static const int32_t GAMEPAD_KEYCODES[] = {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001878 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C, //
1879 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z, //
1880 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1, //
1881 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2, //
1882 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR, //
1883 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE, //
Michael Wrightd02c5b62014-02-10 15:10:22 -08001884};
1885
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001886status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001887 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001888 struct epoll_event eventItem = {};
1889 eventItem.events = EPOLLIN | EPOLLWAKEUP;
1890 eventItem.data.fd = fd;
1891 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1892 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001893 return -errno;
1894 }
1895 return OK;
1896}
1897
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001898status_t EventHub::unregisterFdFromEpoll(int fd) {
1899 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
1900 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
1901 return -errno;
1902 }
1903 return OK;
1904}
1905
Chris Ye989bb932020-07-04 16:18:59 -07001906status_t EventHub::registerDeviceForEpollLocked(Device& device) {
1907 status_t result = registerFdForEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001908 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07001909 ALOGE("Could not add input device fd to epoll for device %" PRId32, device.id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001910 return result;
1911 }
Chris Ye989bb932020-07-04 16:18:59 -07001912 if (device.videoDevice) {
1913 registerVideoDeviceForEpollLocked(*device.videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001914 }
1915 return result;
1916}
1917
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001918void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
1919 status_t result = registerFdForEpoll(videoDevice.getFd());
1920 if (result != OK) {
1921 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
1922 }
1923}
1924
Chris Ye989bb932020-07-04 16:18:59 -07001925status_t EventHub::unregisterDeviceFromEpollLocked(Device& device) {
1926 if (device.hasValidFd()) {
1927 status_t result = unregisterFdFromEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001928 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07001929 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device.id);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001930 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001931 }
1932 }
Chris Ye989bb932020-07-04 16:18:59 -07001933 if (device.videoDevice) {
1934 unregisterVideoDeviceFromEpollLocked(*device.videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001935 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001936 return OK;
1937}
1938
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001939void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
1940 if (videoDevice.hasValidFd()) {
1941 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
1942 if (result != OK) {
1943 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001944 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001945 }
1946 }
1947}
1948
Chris Yed3fef462021-03-07 17:10:08 -08001949void EventHub::reportDeviceAddedForStatisticsLocked(const InputDeviceIdentifier& identifier,
Dominik Laskowski2f01d772022-03-23 16:01:29 -07001950 ftl::Flags<InputDeviceClass> classes) {
Chris Ye657c2f02021-05-25 16:24:37 -07001951 SHA256_CTX ctx;
1952 SHA256_Init(&ctx);
1953 SHA256_Update(&ctx, reinterpret_cast<const uint8_t*>(identifier.uniqueId.c_str()),
1954 identifier.uniqueId.size());
1955 std::array<uint8_t, SHA256_DIGEST_LENGTH> digest;
1956 SHA256_Final(digest.data(), &ctx);
1957
1958 std::string obfuscatedId;
1959 for (size_t i = 0; i < OBFUSCATED_LENGTH; i++) {
1960 obfuscatedId += StringPrintf("%02x", digest[i]);
1961 }
1962
Chris Yed3fef462021-03-07 17:10:08 -08001963 android::util::stats_write(android::util::INPUTDEVICE_REGISTERED, identifier.name.c_str(),
1964 identifier.vendor, identifier.product, identifier.version,
Chris Ye657c2f02021-05-25 16:24:37 -07001965 identifier.bus, obfuscatedId.c_str(), classes.get());
Chris Yed3fef462021-03-07 17:10:08 -08001966}
1967
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00001968void EventHub::openDeviceLocked(const std::string& devicePath) {
1969 // If an input device happens to register around the time when EventHub's constructor runs, it
1970 // is possible that the same input event node (for example, /dev/input/event3) will be noticed
1971 // in both 'inotify' callback and also in the 'scanDirLocked' pass. To prevent duplicate devices
1972 // from getting registered, ensure that this path is not already covered by an existing device.
1973 for (const auto& [deviceId, device] : mDevices) {
1974 if (device->path == devicePath) {
1975 return; // device was already registered
1976 }
1977 }
1978
Michael Wrightd02c5b62014-02-10 15:10:22 -08001979 char buffer[80];
1980
Chris Ye8594e192020-07-14 10:34:06 -07001981 ALOGV("Opening device: %s", devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001982
Chris Ye8594e192020-07-14 10:34:06 -07001983 int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001984 if (fd < 0) {
Chris Ye8594e192020-07-14 10:34:06 -07001985 ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00001986 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001987 }
1988
1989 InputDeviceIdentifier identifier;
1990
1991 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001992 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Chris Ye8594e192020-07-14 10:34:06 -07001993 ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001994 } else {
1995 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001996 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001997 }
1998
1999 // Check to see if the device is on our excluded list
2000 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002001 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002002 if (identifier.name == item) {
Chris Ye8594e192020-07-14 10:34:06 -07002003 ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002004 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002005 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002006 }
2007 }
2008
2009 // Get device driver version.
2010 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002011 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Chris Ye8594e192020-07-14 10:34:06 -07002012 ALOGE("could not get driver version for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002013 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002014 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002015 }
2016
2017 // Get device identifier.
2018 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002019 if (ioctl(fd, EVIOCGID, &inputId)) {
Chris Ye8594e192020-07-14 10:34:06 -07002020 ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002021 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002022 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002023 }
2024 identifier.bus = inputId.bustype;
2025 identifier.product = inputId.product;
2026 identifier.vendor = inputId.vendor;
2027 identifier.version = inputId.version;
2028
2029 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002030 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
2031 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002032 } else {
2033 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002034 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002035 }
2036
2037 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002038 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
2039 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002040 } else {
2041 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002042 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002043 }
2044
2045 // Fill in the descriptor.
2046 assignDescriptorLocked(identifier);
2047
Michael Wrightd02c5b62014-02-10 15:10:22 -08002048 // Allocate device. (The device object takes ownership of the fd at this point.)
2049 int32_t deviceId = mNextDeviceId++;
Chris Ye989bb932020-07-04 16:18:59 -07002050 std::unique_ptr<Device> device = std::make_unique<Device>(fd, deviceId, devicePath, identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002051
Chris Ye8594e192020-07-14 10:34:06 -07002052 ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002053 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002054 " vendor %04x\n"
2055 " product %04x\n"
2056 " version %04x\n",
2057 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002058 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
2059 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
2060 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
2061 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002062 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
2063 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002064
2065 // Load the configuration file for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002066 device->loadConfigurationLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002067
Chris Yee2b1e5c2021-03-10 22:45:12 -08002068 bool hasBattery = false;
2069 bool hasLights = false;
2070 // Check the sysfs root path
2071 std::optional<std::filesystem::path> sysfsRootPath = getSysfsRootPath(devicePath.c_str());
2072 if (sysfsRootPath.has_value()) {
Chris Ye1dd2e5c2021-04-04 23:12:41 -07002073 std::shared_ptr<AssociatedDevice> associatedDevice;
2074 for (const auto& [id, dev] : mDevices) {
2075 if (device->identifier.descriptor == dev->identifier.descriptor &&
2076 !dev->associatedDevice) {
2077 associatedDevice = dev->associatedDevice;
2078 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08002079 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07002080 if (!associatedDevice) {
2081 associatedDevice = std::make_shared<AssociatedDevice>(sysfsRootPath.value());
2082 }
2083 hasBattery = associatedDevice->configureBatteryLocked();
2084 hasLights = associatedDevice->configureLightsLocked();
Chris Yee2b1e5c2021-03-10 22:45:12 -08002085
Chris Ye1dd2e5c2021-04-04 23:12:41 -07002086 device->associatedDevice = associatedDevice;
Chris Yee2b1e5c2021-03-10 22:45:12 -08002087 }
Chris Ye3fdbfef2021-01-06 18:45:18 -08002088
Michael Wrightd02c5b62014-02-10 15:10:22 -08002089 // Figure out the kinds of events the device reports.
Chris Ye66fbac32020-07-06 20:36:43 -07002090 device->readDeviceBitMask(EVIOCGBIT(EV_KEY, 0), device->keyBitmask);
2091 device->readDeviceBitMask(EVIOCGBIT(EV_ABS, 0), device->absBitmask);
2092 device->readDeviceBitMask(EVIOCGBIT(EV_REL, 0), device->relBitmask);
2093 device->readDeviceBitMask(EVIOCGBIT(EV_SW, 0), device->swBitmask);
2094 device->readDeviceBitMask(EVIOCGBIT(EV_LED, 0), device->ledBitmask);
2095 device->readDeviceBitMask(EVIOCGBIT(EV_FF, 0), device->ffBitmask);
Chris Yef59a2f42020-10-16 12:55:26 -07002096 device->readDeviceBitMask(EVIOCGBIT(EV_MSC, 0), device->mscBitmask);
Chris Ye66fbac32020-07-06 20:36:43 -07002097 device->readDeviceBitMask(EVIOCGPROP(0), device->propBitmask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002098
2099 // See if this is a keyboard. Ignore everything in the button range except for
2100 // joystick and gamepad buttons which are handled like keyboards for the most part.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002101 bool haveKeyboardKeys =
Chris Ye66fbac32020-07-06 20:36:43 -07002102 device->keyBitmask.any(0, BTN_MISC) || device->keyBitmask.any(BTN_WHEEL, KEY_MAX + 1);
2103 bool haveGamepadButtons = device->keyBitmask.any(BTN_MISC, BTN_MOUSE) ||
2104 device->keyBitmask.any(BTN_JOYSTICK, BTN_DIGI);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002105 if (haveKeyboardKeys || haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002106 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002107 }
2108
2109 // See if this is a cursor device such as a trackball or mouse.
Chris Ye66fbac32020-07-06 20:36:43 -07002110 if (device->keyBitmask.test(BTN_MOUSE) && device->relBitmask.test(REL_X) &&
2111 device->relBitmask.test(REL_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002112 device->classes |= InputDeviceClass::CURSOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002113 }
2114
Prashant Malani1941ff52015-08-11 18:29:28 -07002115 // See if this is a rotary encoder type device.
2116 String8 deviceType = String8();
2117 if (device->configuration &&
2118 device->configuration->tryGetProperty(String8("device.type"), deviceType)) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002119 if (!deviceType.compare(String8("rotaryEncoder"))) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002120 device->classes |= InputDeviceClass::ROTARY_ENCODER;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002121 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002122 }
2123
Michael Wrightd02c5b62014-02-10 15:10:22 -08002124 // See if this is a touch pad.
2125 // Is this a new modern multi-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002126 if (device->absBitmask.test(ABS_MT_POSITION_X) && device->absBitmask.test(ABS_MT_POSITION_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002127 // Some joysticks such as the PS3 controller report axes that conflict
2128 // with the ABS_MT range. Try to confirm that the device really is
2129 // a touch screen.
Chris Ye66fbac32020-07-06 20:36:43 -07002130 if (device->keyBitmask.test(BTN_TOUCH) || !haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002131 device->classes |= (InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002132 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002133 // Is this an old style single-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002134 } else if (device->keyBitmask.test(BTN_TOUCH) && device->absBitmask.test(ABS_X) &&
2135 device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002136 device->classes |= InputDeviceClass::TOUCH;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002137 // Is this a BT stylus?
Chris Ye66fbac32020-07-06 20:36:43 -07002138 } else if ((device->absBitmask.test(ABS_PRESSURE) || device->keyBitmask.test(BTN_TOUCH)) &&
2139 !device->absBitmask.test(ABS_X) && !device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002140 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -07002141 // Keyboard will try to claim some of the buttons but we really want to reserve those so we
2142 // can fuse it with the touch screen data, so just take them back. Note this means an
2143 // external stylus cannot also be a keyboard device.
Chris Ye1b0c7342020-07-28 21:57:03 -07002144 device->classes &= ~InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002145 }
2146
2147 // See if this device is a joystick.
2148 // Assumes that joysticks always have gamepad buttons in order to distinguish them
2149 // from other devices such as accelerometers that also have absolute axes.
2150 if (haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002151 auto assumedClasses = device->classes | InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002152 for (int i = 0; i <= ABS_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002153 if (device->absBitmask.test(i) &&
Chris Ye1b0c7342020-07-28 21:57:03 -07002154 (getAbsAxisUsage(i, assumedClasses).test(InputDeviceClass::JOYSTICK))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002155 device->classes = assumedClasses;
2156 break;
2157 }
2158 }
2159 }
2160
Chris Yef59a2f42020-10-16 12:55:26 -07002161 // Check whether this device is an accelerometer.
2162 if (device->propBitmask.test(INPUT_PROP_ACCELEROMETER)) {
2163 device->classes |= InputDeviceClass::SENSOR;
2164 }
2165
Michael Wrightd02c5b62014-02-10 15:10:22 -08002166 // Check whether this device has switches.
2167 for (int i = 0; i <= SW_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002168 if (device->swBitmask.test(i)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002169 device->classes |= InputDeviceClass::SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002170 break;
2171 }
2172 }
2173
2174 // Check whether this device supports the vibrator.
Chris Ye66fbac32020-07-06 20:36:43 -07002175 if (device->ffBitmask.test(FF_RUMBLE)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002176 device->classes |= InputDeviceClass::VIBRATOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002177 }
2178
2179 // Configure virtual keys.
Chris Ye1b0c7342020-07-28 21:57:03 -07002180 if ((device->classes.test(InputDeviceClass::TOUCH))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002181 // Load the virtual keys for the touch screen, if any.
2182 // We do this now so that we can make sure to load the keymap if necessary.
Chris Ye989bb932020-07-04 16:18:59 -07002183 bool success = device->loadVirtualKeyMapLocked();
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06002184 if (success) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002185 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002186 }
2187 }
2188
2189 // Load the key map.
Chris Yef59a2f42020-10-16 12:55:26 -07002190 // We need to do this for joysticks too because the key layout may specify axes, and for
2191 // sensor as well because the key layout may specify the axes to sensor data mapping.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002192 status_t keyMapStatus = NAME_NOT_FOUND;
Chris Yef59a2f42020-10-16 12:55:26 -07002193 if (device->classes.any(InputDeviceClass::KEYBOARD | InputDeviceClass::JOYSTICK |
2194 InputDeviceClass::SENSOR)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002195 // Load the keymap for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002196 keyMapStatus = device->loadKeyMapLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002197 }
2198
2199 // Configure the keyboard, gamepad or virtual keyboard.
Chris Ye1b0c7342020-07-28 21:57:03 -07002200 if (device->classes.test(InputDeviceClass::KEYBOARD)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002201 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002202 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002203 isEligibleBuiltInKeyboard(device->identifier, device->configuration.get(),
2204 &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002205 mBuiltInKeyboardId = device->id;
2206 }
2207
2208 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
Chris Ye989bb932020-07-04 16:18:59 -07002209 if (device->hasKeycodeLocked(AKEYCODE_Q)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002210 device->classes |= InputDeviceClass::ALPHAKEY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002211 }
2212
2213 // See if this device has a DPAD.
Chris Ye989bb932020-07-04 16:18:59 -07002214 if (device->hasKeycodeLocked(AKEYCODE_DPAD_UP) &&
2215 device->hasKeycodeLocked(AKEYCODE_DPAD_DOWN) &&
2216 device->hasKeycodeLocked(AKEYCODE_DPAD_LEFT) &&
2217 device->hasKeycodeLocked(AKEYCODE_DPAD_RIGHT) &&
2218 device->hasKeycodeLocked(AKEYCODE_DPAD_CENTER)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002219 device->classes |= InputDeviceClass::DPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002220 }
2221
2222 // See if this device has a gamepad.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002223 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES) / sizeof(GAMEPAD_KEYCODES[0]); i++) {
Chris Ye989bb932020-07-04 16:18:59 -07002224 if (device->hasKeycodeLocked(GAMEPAD_KEYCODES[i])) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002225 device->classes |= InputDeviceClass::GAMEPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002226 break;
2227 }
2228 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002229 }
2230
2231 // If the device isn't recognized as something we handle, don't monitor it.
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002232 if (device->classes == ftl::Flags<InputDeviceClass>(0)) {
Chris Ye8594e192020-07-14 10:34:06 -07002233 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002234 device->identifier.name.c_str());
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002235 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002236 }
2237
Chris Ye3fdbfef2021-01-06 18:45:18 -08002238 // Classify InputDeviceClass::BATTERY.
2239 if (hasBattery) {
2240 device->classes |= InputDeviceClass::BATTERY;
2241 }
Kim Low03ea0352020-11-06 12:45:07 -08002242
Chris Ye3fdbfef2021-01-06 18:45:18 -08002243 // Classify InputDeviceClass::LIGHT.
2244 if (hasLights) {
2245 device->classes |= InputDeviceClass::LIGHT;
Kim Low03ea0352020-11-06 12:45:07 -08002246 }
2247
Tim Kilbourn063ff532015-04-08 10:26:18 -07002248 // Determine whether the device has a mic.
Chris Ye989bb932020-07-04 16:18:59 -07002249 if (device->deviceHasMicLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002250 device->classes |= InputDeviceClass::MIC;
Tim Kilbourn063ff532015-04-08 10:26:18 -07002251 }
2252
Michael Wrightd02c5b62014-02-10 15:10:22 -08002253 // Determine whether the device is external or internal.
Chris Ye989bb932020-07-04 16:18:59 -07002254 if (device->isExternalDeviceLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002255 device->classes |= InputDeviceClass::EXTERNAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002256 }
2257
Chris Ye1b0c7342020-07-28 21:57:03 -07002258 if (device->classes.any(InputDeviceClass::JOYSTICK | InputDeviceClass::DPAD) &&
2259 device->classes.test(InputDeviceClass::GAMEPAD)) {
Chris Ye989bb932020-07-04 16:18:59 -07002260 device->controllerNumber = getNextControllerNumberLocked(device->identifier.name);
2261 device->setLedForControllerLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002262 }
2263
Chris Ye989bb932020-07-04 16:18:59 -07002264 if (registerDeviceForEpollLocked(*device) != OK) {
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002265 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002266 }
2267
Chris Ye989bb932020-07-04 16:18:59 -07002268 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002269
Chris Ye1b0c7342020-07-28 21:57:03 -07002270 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=%s, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002271 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Chris Ye1b0c7342020-07-28 21:57:03 -07002272 deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(),
2273 device->classes.string().c_str(), device->configurationFile.c_str(),
2274 device->keyMap.keyLayoutFile.c_str(), device->keyMap.keyCharacterMapFile.c_str(),
2275 toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002276
Chris Ye989bb932020-07-04 16:18:59 -07002277 addDeviceLocked(std::move(device));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002278}
2279
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002280void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
2281 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
2282 if (!videoDevice) {
2283 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
2284 return;
2285 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002286 // Transfer ownership of this video device to a matching input device
Chris Ye989bb932020-07-04 16:18:59 -07002287 for (const auto& [id, device] : mDevices) {
Chris Yed3fef462021-03-07 17:10:08 -08002288 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002289 return; // 'device' now owns 'videoDevice'
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002290 }
2291 }
2292
2293 // Couldn't find a matching input device, so just add it to a temporary holding queue.
2294 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002295 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002296 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002297 mUnattachedVideoDevices.push_back(std::move(videoDevice));
2298}
2299
Chris Yed3fef462021-03-07 17:10:08 -08002300bool EventHub::tryAddVideoDeviceLocked(EventHub::Device& device,
2301 std::unique_ptr<TouchVideoDevice>& videoDevice) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002302 if (videoDevice->getName() != device.identifier.name) {
2303 return false;
2304 }
2305 device.videoDevice = std::move(videoDevice);
2306 if (device.enabled) {
2307 registerVideoDeviceForEpollLocked(*device.videoDevice);
2308 }
2309 return true;
2310}
2311
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002312bool EventHub::isDeviceEnabled(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002313 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002314 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002315 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002316 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2317 return false;
2318 }
2319 return device->enabled;
2320}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002321
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002322status_t EventHub::enableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002323 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002324 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002325 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002326 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2327 return BAD_VALUE;
2328 }
2329 if (device->enabled) {
2330 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
2331 return OK;
2332 }
2333 status_t result = device->enable();
2334 if (result != OK) {
2335 ALOGE("Failed to enable device %" PRId32, deviceId);
2336 return result;
2337 }
2338
Chris Ye989bb932020-07-04 16:18:59 -07002339 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002340
Chris Ye989bb932020-07-04 16:18:59 -07002341 return registerDeviceForEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002342}
2343
2344status_t EventHub::disableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002345 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002346 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002347 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002348 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2349 return BAD_VALUE;
2350 }
2351 if (!device->enabled) {
2352 ALOGW("Duplicate call to %s, input device already disabled", __func__);
2353 return OK;
2354 }
Chris Ye989bb932020-07-04 16:18:59 -07002355 unregisterDeviceFromEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002356 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002357}
2358
2359void EventHub::createVirtualKeyboardLocked() {
2360 InputDeviceIdentifier identifier;
2361 identifier.name = "Virtual";
2362 identifier.uniqueId = "<virtual>";
2363 assignDescriptorLocked(identifier);
2364
Chris Ye989bb932020-07-04 16:18:59 -07002365 std::unique_ptr<Device> device =
2366 std::make_unique<Device>(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
2367 identifier);
Chris Ye1b0c7342020-07-28 21:57:03 -07002368 device->classes = InputDeviceClass::KEYBOARD | InputDeviceClass::ALPHAKEY |
2369 InputDeviceClass::DPAD | InputDeviceClass::VIRTUAL;
Chris Ye989bb932020-07-04 16:18:59 -07002370 device->loadKeyMapLocked();
2371 addDeviceLocked(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002372}
2373
Chris Ye989bb932020-07-04 16:18:59 -07002374void EventHub::addDeviceLocked(std::unique_ptr<Device> device) {
Chris Yed3fef462021-03-07 17:10:08 -08002375 reportDeviceAddedForStatisticsLocked(device->identifier, device->classes);
Chris Ye989bb932020-07-04 16:18:59 -07002376 mOpeningDevices.push_back(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002377}
2378
Chris Ye989bb932020-07-04 16:18:59 -07002379int32_t EventHub::getNextControllerNumberLocked(const std::string& name) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002380 if (mControllerNumbers.isFull()) {
2381 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Chris Ye989bb932020-07-04 16:18:59 -07002382 name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002383 return 0;
2384 }
2385 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
2386 // one
2387 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
2388}
2389
Chris Ye989bb932020-07-04 16:18:59 -07002390void EventHub::releaseControllerNumberLocked(int32_t num) {
2391 if (num > 0) {
2392 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002393 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002394}
2395
Chris Ye8594e192020-07-14 10:34:06 -07002396void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002397 Device* device = getDeviceByPathLocked(devicePath);
Chris Ye989bb932020-07-04 16:18:59 -07002398 if (device != nullptr) {
2399 closeDeviceLocked(*device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002400 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002401 }
Chris Ye8594e192020-07-14 10:34:06 -07002402 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002403}
2404
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002405/**
2406 * Find the video device by filename, and close it.
2407 * The video device is closed by path during an inotify event, where we don't have the
2408 * additional context about the video device fd, or the associated input device.
2409 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002410void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002411 // A video device may be owned by an existing input device, or it may be stored in
2412 // the mUnattachedVideoDevices queue. Check both locations.
Chris Ye989bb932020-07-04 16:18:59 -07002413 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002414 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002415 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002416 device->videoDevice = nullptr;
2417 return;
2418 }
2419 }
Siarhei Vishniakouf47c339e2021-12-30 11:22:26 -08002420 std::erase_if(mUnattachedVideoDevices,
2421 [&devicePath](const std::unique_ptr<TouchVideoDevice>& videoDevice) {
2422 return videoDevice->getPath() == devicePath;
2423 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08002424}
2425
2426void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002427 mUnattachedVideoDevices.clear();
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002428 while (!mDevices.empty()) {
2429 closeDeviceLocked(*(mDevices.begin()->second));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002430 }
2431}
2432
Chris Ye989bb932020-07-04 16:18:59 -07002433void EventHub::closeDeviceLocked(Device& device) {
2434 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=%s", device.path.c_str(),
2435 device.identifier.name.c_str(), device.id, device.fd, device.classes.string().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002436
Chris Ye989bb932020-07-04 16:18:59 -07002437 if (device.id == mBuiltInKeyboardId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002438 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Chris Ye989bb932020-07-04 16:18:59 -07002439 device.path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002440 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
2441 }
2442
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002443 unregisterDeviceFromEpollLocked(device);
Chris Ye989bb932020-07-04 16:18:59 -07002444 if (device.videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002445 // This must be done after the video device is removed from epoll
Chris Ye989bb932020-07-04 16:18:59 -07002446 mUnattachedVideoDevices.push_back(std::move(device.videoDevice));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002447 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002448
Chris Ye989bb932020-07-04 16:18:59 -07002449 releaseControllerNumberLocked(device.controllerNumber);
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002450 device.controllerNumber = 0;
Chris Ye989bb932020-07-04 16:18:59 -07002451 device.close();
Chris Ye989bb932020-07-04 16:18:59 -07002452 mClosingDevices.push_back(std::move(mDevices[device.id]));
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002453
Chris Ye989bb932020-07-04 16:18:59 -07002454 mDevices.erase(device.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002455}
2456
2457status_t EventHub::readNotifyLocked() {
2458 int res;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002459 char event_buf[512];
2460 int event_size;
2461 int event_pos = 0;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002462 struct inotify_event* event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002463
2464 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
2465 res = read(mINotifyFd, event_buf, sizeof(event_buf));
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002466 if (res < (int)sizeof(*event)) {
2467 if (errno == EINTR) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002468 ALOGW("could not get event, %s\n", strerror(errno));
2469 return -1;
2470 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002471
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002472 while (res >= (int)sizeof(*event)) {
2473 event = (struct inotify_event*)(event_buf + event_pos);
2474 if (event->len) {
Usama Arifb27c8e62021-06-03 16:44:09 +01002475 if (event->wd == mDeviceInputWd) {
2476 std::string filename = std::string(DEVICE_INPUT_PATH) + "/" + event->name;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002477 if (event->mask & IN_CREATE) {
Chris Ye8594e192020-07-14 10:34:06 -07002478 openDeviceLocked(filename);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08002479 } else {
2480 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
Chris Ye8594e192020-07-14 10:34:06 -07002481 closeDeviceByPathLocked(filename);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08002482 }
Usama Arifb27c8e62021-06-03 16:44:09 +01002483 } else if (event->wd == mDeviceWd) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08002484 if (isV4lTouchNode(event->name)) {
Usama Arifb27c8e62021-06-03 16:44:09 +01002485 std::string filename = std::string(DEVICE_PATH) + "/" + event->name;
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002486 if (event->mask & IN_CREATE) {
2487 openVideoDeviceLocked(filename);
2488 } else {
2489 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
2490 closeVideoDeviceByPathLocked(filename);
2491 }
Usama Arifb27c8e62021-06-03 16:44:09 +01002492 } else if (strcmp(event->name, "input") == 0 && event->mask & IN_CREATE) {
2493 addDeviceInputInotify();
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08002494 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002495 } else {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08002496 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event->wd);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002497 }
2498 }
2499 event_size = sizeof(*event) + event->len;
2500 res -= event_size;
2501 event_pos += event_size;
2502 }
2503 return 0;
2504}
2505
Chris Ye8594e192020-07-14 10:34:06 -07002506status_t EventHub::scanDirLocked(const std::string& dirname) {
2507 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2508 openDeviceLocked(entry.path());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002509 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002510 return 0;
2511}
2512
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002513/**
2514 * Look for all dirname/v4l-touch* devices, and open them.
2515 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002516status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Chris Ye8594e192020-07-14 10:34:06 -07002517 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2518 if (isV4lTouchNode(entry.path())) {
2519 ALOGI("Found touch video device %s", entry.path().c_str());
2520 openVideoDeviceLocked(entry.path());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002521 }
2522 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002523 return OK;
2524}
2525
Michael Wrightd02c5b62014-02-10 15:10:22 -08002526void EventHub::requestReopenDevices() {
2527 ALOGV("requestReopenDevices() called");
2528
Chris Ye87143712020-11-10 05:05:58 +00002529 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002530 mNeedToReopenDevices = true;
2531}
2532
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002533void EventHub::dump(std::string& dump) {
2534 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002535
2536 { // acquire lock
Chris Ye87143712020-11-10 05:05:58 +00002537 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002538
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002539 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002540
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002541 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002542
Chris Ye989bb932020-07-04 16:18:59 -07002543 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002544 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002545 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002546 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002547 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002548 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002549 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002550 }
Chris Ye1b0c7342020-07-28 21:57:03 -07002551 dump += StringPrintf(INDENT3 "Classes: %s\n", device->classes.string().c_str());
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002552 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002553 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002554 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
2555 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002556 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002557 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002558 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002559 "product=0x%04x, version=0x%04x\n",
2560 device->identifier.bus, device->identifier.vendor,
2561 device->identifier.product, device->identifier.version);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002562 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002563 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002564 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002565 device->keyMap.keyCharacterMapFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002566 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002567 device->configurationFile.c_str());
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002568 dump += INDENT3 "VideoDevice: ";
2569 if (device->videoDevice) {
2570 dump += device->videoDevice->dump() + "\n";
2571 } else {
2572 dump += "<none>\n";
2573 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002574 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002575
2576 dump += INDENT "Unattached video devices:\n";
2577 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
2578 dump += INDENT2 + videoDevice->dump() + "\n";
2579 }
2580 if (mUnattachedVideoDevices.empty()) {
2581 dump += INDENT2 "<none>\n";
2582 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002583 } // release lock
2584}
2585
2586void EventHub::monitor() {
2587 // Acquire and release the lock to ensure that the event hub has not deadlocked.
Chris Ye1c2e0892020-11-30 21:41:44 -08002588 std::unique_lock<std::mutex> lock(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002589}
2590
Michael Wrightd02c5b62014-02-10 15:10:22 -08002591}; // namespace android