blob: db5032d51ea03c08a2be1db024a30c8a22079106 [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 Vishniakouef1564c2022-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
464 return false;
465}
466
467void EventHub::Device::loadConfigurationLocked() {
468 configurationFile =
469 getInputDeviceConfigurationFilePathByDeviceIdentifier(identifier,
470 InputDeviceConfigurationFileType::
471 CONFIGURATION);
472 if (configurationFile.empty()) {
473 ALOGD("No input device configuration file found for device '%s'.", identifier.name.c_str());
474 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500475 android::base::Result<std::unique_ptr<PropertyMap>> propertyMap =
476 PropertyMap::load(configurationFile.c_str());
477 if (!propertyMap.ok()) {
Chris Ye989bb932020-07-04 16:18:59 -0700478 ALOGE("Error loading input device configuration file for device '%s'. "
479 "Using default configuration.",
480 identifier.name.c_str());
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500481 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500482 configuration = std::move(*propertyMap);
Chris Ye989bb932020-07-04 16:18:59 -0700483 }
484 }
485}
486
487bool EventHub::Device::loadVirtualKeyMapLocked() {
488 // The virtual key map is supplied by the kernel as a system board property file.
489 std::string propPath = "/sys/board_properties/virtualkeys.";
490 propPath += identifier.getCanonicalName();
491 if (access(propPath.c_str(), R_OK)) {
492 return false;
493 }
494 virtualKeyMap = VirtualKeyMap::load(propPath);
495 return virtualKeyMap != nullptr;
496}
497
498status_t EventHub::Device::loadKeyMapLocked() {
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500499 return keyMap.load(identifier, configuration.get());
Chris Ye989bb932020-07-04 16:18:59 -0700500}
501
502bool EventHub::Device::isExternalDeviceLocked() {
503 if (configuration) {
504 bool value;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700505 if (configuration->tryGetProperty("device.internal", value)) {
Chris Ye989bb932020-07-04 16:18:59 -0700506 return !value;
507 }
508 }
509 return identifier.bus == BUS_USB || identifier.bus == BUS_BLUETOOTH;
510}
511
512bool EventHub::Device::deviceHasMicLocked() {
513 if (configuration) {
514 bool value;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700515 if (configuration->tryGetProperty("audio.mic", value)) {
Chris Ye989bb932020-07-04 16:18:59 -0700516 return value;
517 }
518 }
519 return false;
520}
521
522void EventHub::Device::setLedStateLocked(int32_t led, bool on) {
523 int32_t sc;
524 if (hasValidFd() && mapLed(led, &sc) != NAME_NOT_FOUND) {
525 struct input_event ev;
526 ev.time.tv_sec = 0;
527 ev.time.tv_usec = 0;
528 ev.type = EV_LED;
529 ev.code = sc;
530 ev.value = on ? 1 : 0;
531
532 ssize_t nWrite;
533 do {
534 nWrite = write(fd, &ev, sizeof(struct input_event));
535 } while (nWrite == -1 && errno == EINTR);
536 }
537}
538
539void EventHub::Device::setLedForControllerLocked() {
540 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
541 setLedStateLocked(ALED_CONTROLLER_1 + i, controllerNumber == i + 1);
542 }
543}
544
545status_t EventHub::Device::mapLed(int32_t led, int32_t* outScanCode) const {
546 if (!keyMap.haveKeyLayout()) {
547 return NAME_NOT_FOUND;
548 }
549
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700550 std::optional<int32_t> scanCode = keyMap.keyLayoutMap->findScanCodeForLed(led);
551 if (scanCode.has_value()) {
552 if (*scanCode >= 0 && *scanCode <= LED_MAX && ledBitmask.test(*scanCode)) {
553 *outScanCode = *scanCode;
Chris Ye989bb932020-07-04 16:18:59 -0700554 return NO_ERROR;
555 }
556 }
557 return NAME_NOT_FOUND;
558}
559
Chris Ye3fdbfef2021-01-06 18:45:18 -0800560// Check the sysfs path for any input device batteries, returns true if battery found.
Chris Ye1dd2e5c2021-04-04 23:12:41 -0700561bool EventHub::AssociatedDevice::configureBatteryLocked() {
Chris Yee2b1e5c2021-03-10 22:45:12 -0800562 nextBatteryId = 0;
563 // Check if device has any battery.
564 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::POWER_SUPPLY);
565 for (const auto& nodePath : paths) {
566 RawBatteryInfo info;
567 info.id = ++nextBatteryId;
568 info.path = nodePath;
569 info.name = nodePath.filename();
570
571 // Scan the path for all the files
572 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
573 const auto& files = allFilesInPath(nodePath);
574 for (const auto& file : files) {
575 const auto it = BATTERY_CLASSES.find(file.filename().string());
576 if (it != BATTERY_CLASSES.end()) {
577 info.flags |= it->second;
578 }
579 }
580 batteryInfos.insert_or_assign(info.id, info);
581 ALOGD("configureBatteryLocked rawBatteryId %d name %s", info.id, info.name.c_str());
Chris Ye3fdbfef2021-01-06 18:45:18 -0800582 }
Chris Yee2b1e5c2021-03-10 22:45:12 -0800583 return !batteryInfos.empty();
Chris Ye3fdbfef2021-01-06 18:45:18 -0800584}
585
586// Check the sysfs path for any input device lights, returns true if lights found.
Chris Ye1dd2e5c2021-04-04 23:12:41 -0700587bool EventHub::AssociatedDevice::configureLightsLocked() {
Chris Yee2b1e5c2021-03-10 22:45:12 -0800588 nextLightId = 0;
Chris Ye3fdbfef2021-01-06 18:45:18 -0800589 // Check if device has any lights.
Chris Yee2b1e5c2021-03-10 22:45:12 -0800590 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::LEDS);
Chris Ye3fdbfef2021-01-06 18:45:18 -0800591 for (const auto& nodePath : paths) {
592 RawLightInfo info;
593 info.id = ++nextLightId;
594 info.path = nodePath;
595 info.name = nodePath.filename();
596 info.maxBrightness = std::nullopt;
597 size_t nameStart = info.name.rfind(":");
598 if (nameStart != std::string::npos) {
599 // Trim the name to color name
600 info.name = info.name.substr(nameStart + 1);
601 // Set InputLightClass flag for colors
602 const auto it = LIGHT_CLASSES.find(info.name);
603 if (it != LIGHT_CLASSES.end()) {
604 info.flags |= it->second;
605 }
606 }
607 // Scan the path for all the files
608 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
609 const auto& files = allFilesInPath(nodePath);
610 for (const auto& file : files) {
611 const auto it = LIGHT_CLASSES.find(file.filename().string());
612 if (it != LIGHT_CLASSES.end()) {
613 info.flags |= it->second;
614 // If the node has maximum brightness, read it
615 if (it->second == InputLightClass::MAX_BRIGHTNESS) {
616 std::string str;
617 if (base::ReadFileToString(file, &str)) {
618 info.maxBrightness = std::stoi(str);
619 }
620 }
621 }
622 }
623 lightInfos.insert_or_assign(info.id, info);
Chris Yee2b1e5c2021-03-10 22:45:12 -0800624 ALOGD("configureLightsLocked rawLightId %d name %s", info.id, info.name.c_str());
Chris Ye3fdbfef2021-01-06 18:45:18 -0800625 }
626 return !lightInfos.empty();
627}
628
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100629/**
630 * Get the capabilities for the current process.
631 * Crashes the system if unable to create / check / destroy the capabilities object.
632 */
633class Capabilities final {
634public:
635 explicit Capabilities() {
636 mCaps = cap_get_proc();
637 LOG_ALWAYS_FATAL_IF(mCaps == nullptr, "Could not get capabilities of the current process");
638 }
639
640 /**
641 * Check whether the current process has a specific capability
642 * in the set of effective capabilities.
643 * Return CAP_SET if the process has the requested capability
644 * Return CAP_CLEAR otherwise.
645 */
646 cap_flag_value_t checkEffectiveCapability(cap_value_t capability) {
647 cap_flag_value_t value;
648 const int result = cap_get_flag(mCaps, capability, CAP_EFFECTIVE, &value);
649 LOG_ALWAYS_FATAL_IF(result == -1, "Could not obtain the requested capability");
650 return value;
651 }
652
653 ~Capabilities() {
654 const int result = cap_free(mCaps);
655 LOG_ALWAYS_FATAL_IF(result == -1, "Could not release the capabilities structure");
656 }
657
658private:
659 cap_t mCaps;
660};
661
662static void ensureProcessCanBlockSuspend() {
663 Capabilities capabilities;
664 const bool canBlockSuspend =
665 capabilities.checkEffectiveCapability(CAP_BLOCK_SUSPEND) == CAP_SET;
666 LOG_ALWAYS_FATAL_IF(!canBlockSuspend,
667 "Input must be able to block suspend to properly process events");
668}
669
Michael Wrightd02c5b62014-02-10 15:10:22 -0800670// --- EventHub ---
671
Michael Wrightd02c5b62014-02-10 15:10:22 -0800672const int EventHub::EPOLL_MAX_EVENTS;
673
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700674EventHub::EventHub(void)
675 : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
676 mNextDeviceId(1),
677 mControllerNumbers(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800678 mNeedToSendFinishedDeviceScan(false),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700679 mNeedToReopenDevices(false),
680 mNeedToScanDevices(true),
681 mPendingEventCount(0),
682 mPendingEventIndex(0),
683 mPendingINotify(false) {
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100684 ensureProcessCanBlockSuspend();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800685
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800686 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800687 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800688
Michael Wright8e9a8562022-02-09 13:44:29 +0000689 mINotifyFd = inotify_init1(IN_CLOEXEC);
Prabir Pradhan952e65b2022-06-23 17:49:55 +0000690 LOG_ALWAYS_FATAL_IF(mINotifyFd < 0, "Could not create inotify instance: %s", strerror(errno));
Usama Arifb27c8e62021-06-03 16:44:09 +0100691
692 std::error_code errorCode;
693 bool isDeviceInotifyAdded = false;
694 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
695 addDeviceInputInotify();
Philip Quinn39b81682019-01-09 22:20:39 -0800696 } else {
Usama Arifb27c8e62021-06-03 16:44:09 +0100697 addDeviceInotify();
698 isDeviceInotifyAdded = true;
699 if (errorCode) {
700 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
701 errorCode.message().c_str());
702 }
703 }
704
705 if (isV4lScanningEnabled() && !isDeviceInotifyAdded) {
706 addDeviceInotify();
707 } else {
Philip Quinn39b81682019-01-09 22:20:39 -0800708 ALOGI("Video device scanning disabled");
709 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800710
Siarhei Vishniakou2d0e9482019-09-24 12:52:47 +0100711 struct epoll_event eventItem = {};
712 eventItem.events = EPOLLIN | EPOLLWAKEUP;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700713 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800714 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800715 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
716
717 int wakeFds[2];
Michael Wright8e9a8562022-02-09 13:44:29 +0000718 result = pipe2(wakeFds, O_CLOEXEC);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800719 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
720
721 mWakeReadPipeFd = wakeFds[0];
722 mWakeWritePipeFd = wakeFds[1];
723
724 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
725 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700726 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800727
728 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
729 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700730 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800731
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700732 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800733 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
734 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700735 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800736}
737
738EventHub::~EventHub(void) {
739 closeAllDevicesLocked();
740
Michael Wrightd02c5b62014-02-10 15:10:22 -0800741 ::close(mEpollFd);
742 ::close(mINotifyFd);
743 ::close(mWakeReadPipeFd);
744 ::close(mWakeWritePipeFd);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800745}
746
Usama Arifb27c8e62021-06-03 16:44:09 +0100747/**
748 * On devices that don't have any input devices (like some development boards), the /dev/input
749 * directory will be absent. However, the user may still plug in an input device at a later time.
750 * Add watch for contents of /dev/input only when /dev/input appears.
751 */
752void EventHub::addDeviceInputInotify() {
753 mDeviceInputWd = inotify_add_watch(mINotifyFd, DEVICE_INPUT_PATH, IN_DELETE | IN_CREATE);
754 LOG_ALWAYS_FATAL_IF(mDeviceInputWd < 0, "Could not register INotify for %s: %s",
755 DEVICE_INPUT_PATH, strerror(errno));
756}
757
758void EventHub::addDeviceInotify() {
759 mDeviceWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
760 LOG_ALWAYS_FATAL_IF(mDeviceWd < 0, "Could not register INotify for %s: %s", DEVICE_PATH,
761 strerror(errno));
762}
763
Michael Wrightd02c5b62014-02-10 15:10:22 -0800764InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000765 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800766 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700767 return device != nullptr ? device->identifier : InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800768}
769
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700770ftl::Flags<InputDeviceClass> EventHub::getDeviceClasses(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000771 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800772 Device* device = getDeviceLocked(deviceId);
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700773 return device != nullptr ? device->classes : ftl::Flags<InputDeviceClass>(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800774}
775
776int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000777 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800778 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700779 return device != nullptr ? device->controllerNumber : 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800780}
781
782void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
Chris Ye87143712020-11-10 05:05:58 +0000783 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800784 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700785 if (device != nullptr && device->configuration) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800786 *outConfiguration = *device->configuration;
787 } else {
788 outConfiguration->clear();
789 }
790}
791
792status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700793 RawAbsoluteAxisInfo* outAxisInfo) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800794 outAxisInfo->clear();
795
796 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000797 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800798
799 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700800 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800801 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700802 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
803 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
804 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800805 return -errno;
806 }
807
808 if (info.minimum != info.maximum) {
809 outAxisInfo->valid = true;
810 outAxisInfo->minValue = info.minimum;
811 outAxisInfo->maxValue = info.maximum;
812 outAxisInfo->flat = info.flat;
813 outAxisInfo->fuzz = info.fuzz;
814 outAxisInfo->resolution = info.resolution;
815 }
816 return OK;
817 }
818 }
819 return -1;
820}
821
822bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
823 if (axis >= 0 && axis <= REL_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000824 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800825 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700826 return device != nullptr ? device->relBitmask.test(axis) : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800827 }
828 return false;
829}
830
831bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
Chris Ye87143712020-11-10 05:05:58 +0000832 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800833
Chris Ye989bb932020-07-04 16:18:59 -0700834 Device* device = getDeviceLocked(deviceId);
835 return property >= 0 && property <= INPUT_PROP_MAX && device != nullptr
836 ? device->propBitmask.test(property)
837 : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800838}
839
Chris Yef59a2f42020-10-16 12:55:26 -0700840bool EventHub::hasMscEvent(int32_t deviceId, int mscEvent) const {
841 std::scoped_lock _l(mLock);
842
843 Device* device = getDeviceLocked(deviceId);
844 return mscEvent >= 0 && mscEvent <= MSC_MAX && device != nullptr
845 ? device->mscBitmask.test(mscEvent)
846 : false;
847}
848
Michael Wrightd02c5b62014-02-10 15:10:22 -0800849int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
850 if (scanCode >= 0 && scanCode <= KEY_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000851 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800852
853 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700854 if (device != nullptr && device->hasValidFd() && device->keyBitmask.test(scanCode)) {
855 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
856 return device->keyState.test(scanCode) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800857 }
858 }
859 }
860 return AKEY_STATE_UNKNOWN;
861}
862
863int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
Chris Ye87143712020-11-10 05:05:58 +0000864 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800865
866 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700867 if (device != nullptr && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700868 std::vector<int32_t> scanCodes = device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800869 if (scanCodes.size() != 0) {
Chris Ye66fbac32020-07-06 20:36:43 -0700870 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800871 for (size_t i = 0; i < scanCodes.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800872 int32_t sc = scanCodes[i];
Chris Ye66fbac32020-07-06 20:36:43 -0700873 if (sc >= 0 && sc <= KEY_MAX && device->keyState.test(sc)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874 return AKEY_STATE_DOWN;
875 }
876 }
877 return AKEY_STATE_UP;
878 }
879 }
880 }
881 return AKEY_STATE_UNKNOWN;
882}
883
Philip Junker4af3b3d2021-12-14 10:36:55 +0100884int32_t EventHub::getKeyCodeForKeyLocation(int32_t deviceId, int32_t locationKeyCode) const {
885 std::scoped_lock _l(mLock);
886
887 Device* device = getDeviceLocked(deviceId);
888 if (device == nullptr || !device->hasValidFd() || device->keyMap.keyCharacterMap == nullptr ||
889 device->keyMap.keyLayoutMap == nullptr) {
890 return AKEYCODE_UNKNOWN;
891 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700892 std::vector<int32_t> scanCodes =
893 device->keyMap.keyLayoutMap->findScanCodesForKey(locationKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +0100894 if (scanCodes.empty()) {
895 ALOGW("Failed to get key code for key location: no scan code maps to key code %d for input"
896 "device %d",
897 locationKeyCode, deviceId);
898 return AKEYCODE_UNKNOWN;
899 }
900 if (scanCodes.size() > 1) {
901 ALOGW("Multiple scan codes map to the same key code %d, returning only the first match",
902 locationKeyCode);
903 }
904 int32_t outKeyCode;
905 status_t mapKeyRes =
906 device->getKeyCharacterMap()->mapKey(scanCodes[0], 0 /*usageCode*/, &outKeyCode);
907 switch (mapKeyRes) {
908 case OK:
909 return outKeyCode;
910 case NAME_NOT_FOUND:
911 // key character map doesn't re-map this scanCode, hence the keyCode remains the same
912 return locationKeyCode;
913 default:
914 ALOGW("Failed to get key code for key location: Key character map returned error %s",
915 statusToString(mapKeyRes).c_str());
916 return AKEYCODE_UNKNOWN;
917 }
918}
919
Michael Wrightd02c5b62014-02-10 15:10:22 -0800920int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
921 if (sw >= 0 && sw <= SW_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000922 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800923
924 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700925 if (device != nullptr && device->hasValidFd() && device->swBitmask.test(sw)) {
926 if (device->readDeviceBitMask(EVIOCGSW(0), device->swState) >= 0) {
927 return device->swState.test(sw) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800928 }
929 }
930 }
931 return AKEY_STATE_UNKNOWN;
932}
933
934status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
935 *outValue = 0;
936
937 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000938 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800939
940 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700941 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800942 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700943 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
944 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
945 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800946 return -errno;
947 }
948
949 *outValue = info.value;
950 return OK;
951 }
952 }
953 return -1;
954}
955
Siarhei Vishniakou74007942022-06-13 13:57:47 -0700956bool EventHub::markSupportedKeyCodes(int32_t deviceId, const std::vector<int32_t>& keyCodes,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700957 uint8_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +0000958 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800959
960 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700961 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -0700962 for (size_t codeIndex = 0; codeIndex < keyCodes.size(); codeIndex++) {
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700963 std::vector<int32_t> scanCodes =
964 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCodes[codeIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800965
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700966 // check the possible scan codes identified by the layout map against the
967 // map of codes actually emitted by the driver
Siarhei Vishniakou74007942022-06-13 13:57:47 -0700968 for (const int32_t scanCode : scanCodes) {
969 if (device->keyBitmask.test(scanCode)) {
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700970 outFlags[codeIndex] = 1;
971 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800972 }
973 }
974 }
975 return true;
976 }
977 return false;
978}
979
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700980status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
981 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +0000982 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800983 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700984 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800985
Chris Ye66fbac32020-07-06 20:36:43 -0700986 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800987 // Check the key character map first.
Chris Ye3a1e4462020-08-12 10:13:15 -0700988 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
989 if (kcm) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800990 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
991 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700992 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800993 }
994 }
995
996 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700997 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800998 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700999 status = NO_ERROR;
1000 }
1001 }
1002
1003 if (status == NO_ERROR) {
Chris Ye3a1e4462020-08-12 10:13:15 -07001004 if (kcm) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001005 kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState);
1006 } else {
1007 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001008 }
1009 }
1010 }
1011
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001012 if (status != NO_ERROR) {
1013 *outKeycode = 0;
1014 *outFlags = 0;
1015 *outMetaState = metaState;
1016 }
1017
1018 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001019}
1020
1021status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
Chris Ye87143712020-11-10 05:05:58 +00001022 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001023 Device* device = getDeviceLocked(deviceId);
1024
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001025 if (device == nullptr || !device->keyMap.haveKeyLayout()) {
1026 return NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001027 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001028 std::optional<AxisInfo> info = device->keyMap.keyLayoutMap->mapAxis(scanCode);
1029 if (!info.has_value()) {
1030 return NAME_NOT_FOUND;
1031 }
1032 *outAxisInfo = *info;
1033 return NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001034}
1035
Chris Yef59a2f42020-10-16 12:55:26 -07001036base::Result<std::pair<InputDeviceSensorType, int32_t>> EventHub::mapSensor(int32_t deviceId,
1037 int32_t absCode) {
1038 std::scoped_lock _l(mLock);
1039 Device* device = getDeviceLocked(deviceId);
1040
1041 if (device != nullptr && device->keyMap.haveKeyLayout()) {
1042 return device->keyMap.keyLayoutMap->mapSensor(absCode);
1043 }
1044 return Errorf("Device not found or device has no key layout.");
1045}
1046
Chris Yee2b1e5c2021-03-10 22:45:12 -08001047// Gets the battery info map from battery ID to RawBatteryInfo of the miscellaneous device
1048// associated with the device ID. Returns an empty map if no miscellaneous device found.
1049const std::unordered_map<int32_t, RawBatteryInfo>& EventHub::getBatteryInfoLocked(
1050 int32_t deviceId) const {
1051 static const std::unordered_map<int32_t, RawBatteryInfo> EMPTY_BATTERY_INFO = {};
1052 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001053 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001054 return EMPTY_BATTERY_INFO;
1055 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001056 return device->associatedDevice->batteryInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001057}
1058
1059const std::vector<int32_t> EventHub::getRawBatteryIds(int32_t deviceId) {
1060 std::scoped_lock _l(mLock);
1061 std::vector<int32_t> batteryIds;
1062
Prabir Pradhan51894782022-08-23 16:29:10 +00001063 for (const auto& [id, info] : getBatteryInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001064 batteryIds.push_back(id);
1065 }
1066
1067 return batteryIds;
1068}
1069
1070std::optional<RawBatteryInfo> EventHub::getRawBatteryInfo(int32_t deviceId, int32_t batteryId) {
1071 std::scoped_lock _l(mLock);
1072
1073 const auto infos = getBatteryInfoLocked(deviceId);
1074
1075 auto it = infos.find(batteryId);
1076 if (it != infos.end()) {
1077 return it->second;
1078 }
1079
1080 return std::nullopt;
1081}
1082
1083// Gets the light info map from light ID to RawLightInfo of the miscellaneous device associated
Prabir Pradhan51894782022-08-23 16:29:10 +00001084// with the device ID. Returns an empty map if no miscellaneous device found.
Chris Yee2b1e5c2021-03-10 22:45:12 -08001085const std::unordered_map<int32_t, RawLightInfo>& EventHub::getLightInfoLocked(
1086 int32_t deviceId) const {
1087 static const std::unordered_map<int32_t, RawLightInfo> EMPTY_LIGHT_INFO = {};
1088 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001089 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001090 return EMPTY_LIGHT_INFO;
1091 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001092 return device->associatedDevice->lightInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001093}
1094
Chris Ye3fdbfef2021-01-06 18:45:18 -08001095const std::vector<int32_t> EventHub::getRawLightIds(int32_t deviceId) {
1096 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001097 std::vector<int32_t> lightIds;
1098
Prabir Pradhan51894782022-08-23 16:29:10 +00001099 for (const auto& [id, info] : getLightInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001100 lightIds.push_back(id);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001101 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001102
Chris Ye3fdbfef2021-01-06 18:45:18 -08001103 return lightIds;
1104}
1105
1106std::optional<RawLightInfo> EventHub::getRawLightInfo(int32_t deviceId, int32_t lightId) {
1107 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001108
Chris Yee2b1e5c2021-03-10 22:45:12 -08001109 const auto infos = getLightInfoLocked(deviceId);
1110
1111 auto it = infos.find(lightId);
1112 if (it != infos.end()) {
1113 return it->second;
Chris Ye3fdbfef2021-01-06 18:45:18 -08001114 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001115
Chris Ye3fdbfef2021-01-06 18:45:18 -08001116 return std::nullopt;
1117}
1118
1119std::optional<int32_t> EventHub::getLightBrightness(int32_t deviceId, int32_t lightId) {
1120 std::scoped_lock _l(mLock);
1121
Chris Yee2b1e5c2021-03-10 22:45:12 -08001122 const auto infos = getLightInfoLocked(deviceId);
1123 auto it = infos.find(lightId);
1124 if (it == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001125 return std::nullopt;
1126 }
1127 std::string buffer;
1128 if (!base::ReadFileToString(it->second.path / LIGHT_NODES.at(InputLightClass::BRIGHTNESS),
1129 &buffer)) {
1130 return std::nullopt;
1131 }
1132 return std::stoi(buffer);
1133}
1134
1135std::optional<std::unordered_map<LightColor, int32_t>> EventHub::getLightIntensities(
1136 int32_t deviceId, int32_t lightId) {
1137 std::scoped_lock _l(mLock);
1138
Chris Yee2b1e5c2021-03-10 22:45:12 -08001139 const auto infos = getLightInfoLocked(deviceId);
1140 auto lightIt = infos.find(lightId);
1141 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001142 return std::nullopt;
1143 }
1144
1145 auto ret =
1146 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1147
1148 if (!ret.has_value()) {
1149 return std::nullopt;
1150 }
1151 std::array<LightColor, COLOR_NUM> colors = ret.value();
1152
1153 std::string intensityStr;
1154 if (!base::ReadFileToString(lightIt->second.path /
1155 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY),
1156 &intensityStr)) {
1157 return std::nullopt;
1158 }
1159
1160 // Intensity node outputs 3 color values
1161 std::regex intensityPattern("([0-9]+)\\s([0-9]+)\\s([0-9]+)[\\n]");
1162 std::smatch results;
1163
1164 if (!std::regex_match(intensityStr, results, intensityPattern)) {
1165 return std::nullopt;
1166 }
1167 std::unordered_map<LightColor, int32_t> intensities;
1168 for (size_t i = 1; i < results.size(); i++) {
1169 int value = std::stoi(results[i].str());
1170 intensities.emplace(colors[i - 1], value);
1171 }
1172 return intensities;
1173}
1174
1175void EventHub::setLightBrightness(int32_t deviceId, int32_t lightId, int32_t brightness) {
1176 std::scoped_lock _l(mLock);
1177
Chris Yee2b1e5c2021-03-10 22:45:12 -08001178 const auto infos = getLightInfoLocked(deviceId);
1179 auto lightIt = infos.find(lightId);
1180 if (lightIt == infos.end()) {
1181 ALOGE("%s lightId %d not found ", __func__, lightId);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001182 return;
1183 }
1184
1185 if (!base::WriteStringToFile(std::to_string(brightness),
1186 lightIt->second.path /
1187 LIGHT_NODES.at(InputLightClass::BRIGHTNESS))) {
1188 ALOGE("Can not write to file, error: %s", strerror(errno));
1189 }
1190}
1191
1192void EventHub::setLightIntensities(int32_t deviceId, int32_t lightId,
1193 std::unordered_map<LightColor, int32_t> intensities) {
1194 std::scoped_lock _l(mLock);
1195
Chris Yee2b1e5c2021-03-10 22:45:12 -08001196 const auto infos = getLightInfoLocked(deviceId);
1197 auto lightIt = infos.find(lightId);
1198 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001199 ALOGE("Light Id %d does not exist.", lightId);
1200 return;
1201 }
1202
1203 auto ret =
1204 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1205
1206 if (!ret.has_value()) {
1207 return;
1208 }
1209 std::array<LightColor, COLOR_NUM> colors = ret.value();
1210
1211 std::string rgbStr;
1212 for (size_t i = 0; i < COLOR_NUM; i++) {
1213 auto it = intensities.find(colors[i]);
1214 if (it != intensities.end()) {
1215 rgbStr += std::to_string(it->second);
1216 // Insert space between colors
1217 if (i < COLOR_NUM - 1) {
1218 rgbStr += " ";
1219 }
1220 }
1221 }
1222 // Append new line
1223 rgbStr += "\n";
1224
1225 if (!base::WriteStringToFile(rgbStr,
1226 lightIt->second.path /
1227 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY))) {
1228 ALOGE("Can not write to file, error: %s", strerror(errno));
1229 }
1230}
1231
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001232void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Chris Ye87143712020-11-10 05:05:58 +00001233 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001234
1235 mExcludedDevices = devices;
1236}
1237
1238bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
Chris Ye87143712020-11-10 05:05:58 +00001239 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001240 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001241 if (device != nullptr && scanCode >= 0 && scanCode <= KEY_MAX) {
1242 return device->keyBitmask.test(scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243 }
1244 return false;
1245}
1246
Arthur Hungcb40a002021-08-03 14:31:01 +00001247bool EventHub::hasKeyCode(int32_t deviceId, int32_t keyCode) const {
1248 std::scoped_lock _l(mLock);
1249 Device* device = getDeviceLocked(deviceId);
1250 if (device != nullptr) {
1251 return device->hasKeycodeLocked(keyCode);
1252 }
1253 return false;
1254}
1255
Michael Wrightd02c5b62014-02-10 15:10:22 -08001256bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
Chris Ye87143712020-11-10 05:05:58 +00001257 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001258 Device* device = getDeviceLocked(deviceId);
1259 int32_t sc;
Chris Ye989bb932020-07-04 16:18:59 -07001260 if (device != nullptr && device->mapLed(led, &sc) == NO_ERROR) {
Chris Ye66fbac32020-07-06 20:36:43 -07001261 return device->ledBitmask.test(sc);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001262 }
1263 return false;
1264}
1265
1266void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
Chris Ye87143712020-11-10 05:05:58 +00001267 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001268 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -07001269 if (device != nullptr && device->hasValidFd()) {
1270 device->setLedStateLocked(led, on);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001271 }
1272}
1273
1274void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001275 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001276 outVirtualKeys.clear();
1277
Chris Ye87143712020-11-10 05:05:58 +00001278 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001279 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001280 if (device != nullptr && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001281 const std::vector<VirtualKeyDefinition> virtualKeys =
1282 device->virtualKeyMap->getVirtualKeys();
1283 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001284 }
1285}
1286
Chris Ye3a1e4462020-08-12 10:13:15 -07001287const std::shared_ptr<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001288 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001289 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001290 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001291 return device->getKeyCharacterMap();
1292 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001293 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001294}
1295
Chris Ye3a1e4462020-08-12 10:13:15 -07001296bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, std::shared_ptr<KeyCharacterMap> map) {
Chris Ye87143712020-11-10 05:05:58 +00001297 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001298 Device* device = getDeviceLocked(deviceId);
Philip Junker90bc9492021-12-10 18:39:42 +01001299 if (device == nullptr || map == nullptr || device->keyMap.keyCharacterMap == nullptr) {
1300 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001301 }
Philip Junker90bc9492021-12-10 18:39:42 +01001302 device->keyMap.keyCharacterMap->combine(*map);
1303 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001304}
1305
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001306static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
1307 std::string rawDescriptor;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001308 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001309 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001310 if (!identifier.uniqueId.empty()) {
1311 rawDescriptor += "uniqueId:";
1312 rawDescriptor += identifier.uniqueId;
Josh Bartel938632f2022-07-19 15:34:22 -05001313 }
1314 if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001315 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001316 }
1317
1318 if (identifier.vendor == 0 && identifier.product == 0) {
1319 // If we don't know the vendor and product id, then the device is probably
1320 // built-in so we need to rely on other information to uniquely identify
1321 // the input device. Usually we try to avoid relying on the device name or
1322 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001323 if (!identifier.name.empty()) {
1324 rawDescriptor += "name:";
1325 rawDescriptor += identifier.name;
1326 } else if (!identifier.location.empty()) {
1327 rawDescriptor += "location:";
1328 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001329 }
1330 }
1331 identifier.descriptor = sha1(rawDescriptor);
1332 return rawDescriptor;
1333}
1334
1335void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
1336 // Compute a device descriptor that uniquely identifies the device.
1337 // The descriptor is assumed to be a stable identifier. Its value should not
1338 // change between reboots, reconnections, firmware updates or new releases
1339 // of Android. In practice we sometimes get devices that cannot be uniquely
1340 // identified. In this case we enforce uniqueness between connected devices.
1341 // Ideally, we also want the descriptor to be short and relatively opaque.
Josh Bartel938632f2022-07-19 15:34:22 -05001342 // Note that we explicitly do not use the path or location for external devices
1343 // as their path or location will change as they are plugged/unplugged or moved
1344 // to different ports. We do fallback to using name and location in the case of
1345 // internal devices which are detected by the vendor and product being 0 in
1346 // generateDescriptor. If two identical descriptors are detected we will fallback
1347 // to using a 'nonce' and incrementing it until the new descriptor no longer has
1348 // a match with any existing descriptors.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001349
1350 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001351 std::string rawDescriptor = generateDescriptor(identifier);
Josh Bartel938632f2022-07-19 15:34:22 -05001352 // Enforce that the generated descriptor is unique.
1353 while (hasDeviceWithDescriptorLocked(identifier.descriptor)) {
1354 identifier.nonce++;
1355 rawDescriptor = generateDescriptor(identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001356 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001357 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001358 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001359}
1360
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001361void EventHub::vibrate(int32_t deviceId, const VibrationElement& element) {
Chris Ye87143712020-11-10 05:05:58 +00001362 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001363 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001364 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001365 ff_effect effect;
1366 memset(&effect, 0, sizeof(effect));
1367 effect.type = FF_RUMBLE;
1368 effect.id = device->ffEffectId;
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001369 // evdev FF_RUMBLE effect only supports two channels of vibration.
Chris Ye6393a262020-08-04 19:41:36 -07001370 effect.u.rumble.strong_magnitude = element.getMagnitude(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1371 effect.u.rumble.weak_magnitude = element.getMagnitude(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001372 effect.replay.length = element.duration.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001373 effect.replay.delay = 0;
1374 if (ioctl(device->fd, EVIOCSFF, &effect)) {
1375 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001376 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001377 return;
1378 }
1379 device->ffEffectId = effect.id;
1380
1381 struct input_event ev;
1382 ev.time.tv_sec = 0;
1383 ev.time.tv_usec = 0;
1384 ev.type = EV_FF;
1385 ev.code = device->ffEffectId;
1386 ev.value = 1;
1387 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1388 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001389 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001390 return;
1391 }
1392 device->ffEffectPlaying = true;
1393 }
1394}
1395
1396void EventHub::cancelVibrate(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001397 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001398 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001399 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001400 if (device->ffEffectPlaying) {
1401 device->ffEffectPlaying = false;
1402
1403 struct input_event ev;
1404 ev.time.tv_sec = 0;
1405 ev.time.tv_usec = 0;
1406 ev.type = EV_FF;
1407 ev.code = device->ffEffectId;
1408 ev.value = 0;
1409 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1410 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001411 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001412 return;
1413 }
1414 }
1415 }
1416}
1417
Chris Ye87143712020-11-10 05:05:58 +00001418std::vector<int32_t> EventHub::getVibratorIds(int32_t deviceId) {
1419 std::scoped_lock _l(mLock);
1420 std::vector<int32_t> vibrators;
1421 Device* device = getDeviceLocked(deviceId);
1422 if (device != nullptr && device->hasValidFd() &&
1423 device->classes.test(InputDeviceClass::VIBRATOR)) {
1424 vibrators.push_back(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1425 vibrators.push_back(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
1426 }
1427 return vibrators;
1428}
1429
Josh Bartel938632f2022-07-19 15:34:22 -05001430/**
1431 * Checks both mDevices and mOpeningDevices for a device with the descriptor passed.
1432 */
1433bool EventHub::hasDeviceWithDescriptorLocked(const std::string& descriptor) const {
1434 for (const auto& device : mOpeningDevices) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001435 if (descriptor == device->identifier.descriptor) {
Josh Bartel938632f2022-07-19 15:34:22 -05001436 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001437 }
1438 }
Josh Bartel938632f2022-07-19 15:34:22 -05001439
1440 for (const auto& [id, device] : mDevices) {
1441 if (descriptor == device->identifier.descriptor) {
1442 return true;
1443 }
1444 }
1445 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001446}
1447
1448EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001449 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001450 deviceId = mBuiltInKeyboardId;
1451 }
Chris Ye989bb932020-07-04 16:18:59 -07001452 const auto& it = mDevices.find(deviceId);
1453 return it != mDevices.end() ? it->second.get() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001454}
1455
Chris Ye8594e192020-07-14 10:34:06 -07001456EventHub::Device* EventHub::getDeviceByPathLocked(const std::string& devicePath) const {
Chris Ye989bb932020-07-04 16:18:59 -07001457 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001458 if (device->path == devicePath) {
Chris Ye989bb932020-07-04 16:18:59 -07001459 return device.get();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001460 }
1461 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001462 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001463}
1464
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001465/**
1466 * The file descriptor could be either input device, or a video device (associated with a
1467 * specific input device). Check both cases here, and return the device that this event
1468 * belongs to. Caller can compare the fd's once more to determine event type.
1469 * Looks through all input devices, and only attached video devices. Unattached video
1470 * devices are ignored.
1471 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001472EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
Chris Ye989bb932020-07-04 16:18:59 -07001473 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001474 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001475 // This is an input device event
Chris Ye989bb932020-07-04 16:18:59 -07001476 return device.get();
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001477 }
1478 if (device->videoDevice && device->videoDevice->getFd() == fd) {
1479 // This is a video device event
Chris Ye989bb932020-07-04 16:18:59 -07001480 return device.get();
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001481 }
1482 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001483 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
1484 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001485 return nullptr;
1486}
1487
Chris Yee2b1e5c2021-03-10 22:45:12 -08001488std::optional<int32_t> EventHub::getBatteryCapacity(int32_t deviceId, int32_t batteryId) const {
Kim Low03ea0352020-11-06 12:45:07 -08001489 std::scoped_lock _l(mLock);
Kim Low03ea0352020-11-06 12:45:07 -08001490
Chris Yee2b1e5c2021-03-10 22:45:12 -08001491 const auto infos = getBatteryInfoLocked(deviceId);
1492 auto it = infos.find(batteryId);
1493 if (it == infos.end()) {
Kim Low03ea0352020-11-06 12:45:07 -08001494 return std::nullopt;
1495 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001496 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001497
1498 // Some devices report battery capacity as an integer through the "capacity" file
Chris Yee2b1e5c2021-03-10 22:45:12 -08001499 if (base::ReadFileToString(it->second.path / BATTERY_NODES.at(InputBatteryClass::CAPACITY),
1500 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001501 return std::stoi(base::Trim(buffer));
Kim Low03ea0352020-11-06 12:45:07 -08001502 }
1503
1504 // Other devices report capacity as an enum value POWER_SUPPLY_CAPACITY_LEVEL_XXX
1505 // These values are taken from kernel source code include/linux/power_supply.h
Chris Yee2b1e5c2021-03-10 22:45:12 -08001506 if (base::ReadFileToString(it->second.path /
1507 BATTERY_NODES.at(InputBatteryClass::CAPACITY_LEVEL),
1508 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001509 // Remove any white space such as trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001510 const auto levelIt = BATTERY_LEVEL.find(base::Trim(buffer));
1511 if (levelIt != BATTERY_LEVEL.end()) {
1512 return levelIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001513 }
1514 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001515
Kim Low03ea0352020-11-06 12:45:07 -08001516 return std::nullopt;
1517}
1518
Chris Yee2b1e5c2021-03-10 22:45:12 -08001519std::optional<int32_t> EventHub::getBatteryStatus(int32_t deviceId, int32_t batteryId) const {
Kim Low03ea0352020-11-06 12:45:07 -08001520 std::scoped_lock _l(mLock);
Chris Yee2b1e5c2021-03-10 22:45:12 -08001521 const auto infos = getBatteryInfoLocked(deviceId);
1522 auto it = infos.find(batteryId);
1523 if (it == infos.end()) {
Kim Low03ea0352020-11-06 12:45:07 -08001524 return std::nullopt;
1525 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001526 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001527
Chris Yee2b1e5c2021-03-10 22:45:12 -08001528 if (!base::ReadFileToString(it->second.path / BATTERY_NODES.at(InputBatteryClass::STATUS),
1529 &buffer)) {
Kim Low03ea0352020-11-06 12:45:07 -08001530 ALOGE("Failed to read sysfs battery info: %s", strerror(errno));
1531 return std::nullopt;
1532 }
1533
Chris Yed1936772021-02-22 10:30:40 -08001534 // Remove white space like trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001535 const auto statusIt = BATTERY_STATUS.find(base::Trim(buffer));
1536 if (statusIt != BATTERY_STATUS.end()) {
1537 return statusIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001538 }
1539
1540 return std::nullopt;
1541}
1542
Michael Wrightd02c5b62014-02-10 15:10:22 -08001543size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
1544 ALOG_ASSERT(bufferSize >= 1);
1545
Chris Ye87143712020-11-10 05:05:58 +00001546 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001547
1548 struct input_event readBuffer[bufferSize];
1549
1550 RawEvent* event = buffer;
1551 size_t capacity = bufferSize;
1552 bool awoken = false;
1553 for (;;) {
1554 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
1555
1556 // Reopen input devices if needed.
1557 if (mNeedToReopenDevices) {
1558 mNeedToReopenDevices = false;
1559
1560 ALOGI("Reopening all input devices due to a configuration change.");
1561
1562 closeAllDevicesLocked();
1563 mNeedToScanDevices = true;
1564 break; // return to the caller before we actually rescan
1565 }
1566
1567 // Report any devices that had last been added/removed.
Chris Ye989bb932020-07-04 16:18:59 -07001568 for (auto it = mClosingDevices.begin(); it != mClosingDevices.end();) {
1569 std::unique_ptr<Device> device = std::move(*it);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001570 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001571 event->when = now;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001572 event->deviceId = (device->id == mBuiltInKeyboardId)
1573 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
1574 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001575 event->type = DEVICE_REMOVED;
1576 event += 1;
Chris Ye989bb932020-07-04 16:18:59 -07001577 it = mClosingDevices.erase(it);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001578 mNeedToSendFinishedDeviceScan = true;
1579 if (--capacity == 0) {
1580 break;
1581 }
1582 }
1583
1584 if (mNeedToScanDevices) {
1585 mNeedToScanDevices = false;
1586 scanDevicesLocked();
1587 mNeedToSendFinishedDeviceScan = true;
1588 }
1589
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001590 while (!mOpeningDevices.empty()) {
1591 std::unique_ptr<Device> device = std::move(*mOpeningDevices.rbegin());
1592 mOpeningDevices.pop_back();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001593 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001594 event->when = now;
1595 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1596 event->type = DEVICE_ADDED;
1597 event += 1;
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001598
1599 // Try to find a matching video device by comparing device names
1600 for (auto it = mUnattachedVideoDevices.begin(); it != mUnattachedVideoDevices.end();
1601 it++) {
1602 std::unique_ptr<TouchVideoDevice>& videoDevice = *it;
Chris Yed3fef462021-03-07 17:10:08 -08001603 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001604 // videoDevice was transferred to 'device'
1605 it = mUnattachedVideoDevices.erase(it);
1606 break;
1607 }
1608 }
1609
1610 auto [dev_it, inserted] = mDevices.insert_or_assign(device->id, std::move(device));
1611 if (!inserted) {
Chris Ye989bb932020-07-04 16:18:59 -07001612 ALOGW("Device id %d exists, replaced.", device->id);
1613 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001614 mNeedToSendFinishedDeviceScan = true;
1615 if (--capacity == 0) {
1616 break;
1617 }
1618 }
1619
1620 if (mNeedToSendFinishedDeviceScan) {
1621 mNeedToSendFinishedDeviceScan = false;
1622 event->when = now;
1623 event->type = FINISHED_DEVICE_SCAN;
1624 event += 1;
1625 if (--capacity == 0) {
1626 break;
1627 }
1628 }
1629
1630 // Grab the next input event.
1631 bool deviceChanged = false;
1632 while (mPendingEventIndex < mPendingEventCount) {
1633 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001634 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001635 if (eventItem.events & EPOLLIN) {
1636 mPendingINotify = true;
1637 } else {
1638 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
1639 }
1640 continue;
1641 }
1642
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001643 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001644 if (eventItem.events & EPOLLIN) {
1645 ALOGV("awoken after wake()");
1646 awoken = true;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001647 char wakeReadBuffer[16];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001648 ssize_t nRead;
1649 do {
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001650 nRead = read(mWakeReadPipeFd, wakeReadBuffer, sizeof(wakeReadBuffer));
1651 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(wakeReadBuffer));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001652 } else {
1653 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001654 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001655 }
1656 continue;
1657 }
1658
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001659 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Chris Ye989bb932020-07-04 16:18:59 -07001660 if (device == nullptr) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001661 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
1662 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001663 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001664 continue;
1665 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001666 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
1667 if (eventItem.events & EPOLLIN) {
1668 size_t numFrames = device->videoDevice->readAndQueueFrames();
1669 if (numFrames == 0) {
1670 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001671 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001672 }
1673 } else if (eventItem.events & EPOLLHUP) {
1674 // TODO(b/121395353) - consider adding EPOLLRDHUP
1675 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001676 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001677 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1678 device->videoDevice = nullptr;
1679 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001680 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1681 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001682 ALOG_ASSERT(!DEBUG);
1683 }
1684 continue;
1685 }
1686 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -08001687 if (eventItem.events & EPOLLIN) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001688 int32_t readSize =
1689 read(device->fd, readBuffer, sizeof(struct input_event) * capacity);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001690 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
1691 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -07001692 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001693 " bufferSize: %zu capacity: %zu errno: %d)\n",
1694 device->fd, readSize, bufferSize, capacity, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001695 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001696 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001697 } else if (readSize < 0) {
1698 if (errno != EAGAIN && errno != EINTR) {
1699 ALOGW("could not get event (errno=%d)", errno);
1700 }
1701 } else if ((readSize % sizeof(struct input_event)) != 0) {
1702 ALOGE("could not get event (wrong size: %d)", readSize);
1703 } else {
1704 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1705
1706 size_t count = size_t(readSize) / sizeof(struct input_event);
1707 for (size_t i = 0; i < count; i++) {
1708 struct input_event& iev = readBuffer[i];
Siarhei Vishniakou592bac22018-11-08 19:42:38 -08001709 event->when = processEventTimestamp(iev);
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001710 event->readTime = systemTime(SYSTEM_TIME_MONOTONIC);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001711 event->deviceId = deviceId;
1712 event->type = iev.type;
1713 event->code = iev.code;
1714 event->value = iev.value;
1715 event += 1;
1716 capacity -= 1;
1717 }
1718 if (capacity == 0) {
1719 // The result buffer is full. Reset the pending event index
1720 // so we will try to read the device again on the next iteration.
1721 mPendingEventIndex -= 1;
1722 break;
1723 }
1724 }
1725 } else if (eventItem.events & EPOLLHUP) {
1726 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001727 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001728 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001729 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001730 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001731 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1732 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001733 }
1734 }
1735
1736 // readNotify() will modify the list of devices so this must be done after
1737 // processing all other events to ensure that we read all remaining events
1738 // before closing the devices.
1739 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
1740 mPendingINotify = false;
Prabir Pradhan952e65b2022-06-23 17:49:55 +00001741 const auto res = readNotifyLocked();
1742 if (!res.ok()) {
1743 ALOGW("Failed to read from inotify: %s", res.error().message().c_str());
1744 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001745 deviceChanged = true;
1746 }
1747
1748 // Report added or removed devices immediately.
1749 if (deviceChanged) {
1750 continue;
1751 }
1752
1753 // Return now if we have collected any events or if we were explicitly awoken.
1754 if (event != buffer || awoken) {
1755 break;
1756 }
1757
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001758 // Poll for events.
1759 // When a device driver has pending (unread) events, it acquires
1760 // a kernel wake lock. Once the last pending event has been read, the device
1761 // driver will release the kernel wake lock, but the epoll will hold the wakelock,
1762 // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
1763 // is called again for the same fd that produced the event.
1764 // Thus the system can only sleep if there are no events pending or
1765 // currently being processed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001766 //
1767 // The timeout is advisory only. If the device is asleep, it will not wake just to
1768 // service the timeout.
1769 mPendingEventIndex = 0;
1770
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001771 mLock.unlock(); // release lock before poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001772
1773 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1774
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001775 mLock.lock(); // reacquire lock after poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001776
1777 if (pollResult == 0) {
1778 // Timed out.
1779 mPendingEventCount = 0;
1780 break;
1781 }
1782
1783 if (pollResult < 0) {
1784 // An error occurred.
1785 mPendingEventCount = 0;
1786
1787 // Sleep after errors to avoid locking up the system.
1788 // Hopefully the error is transient.
1789 if (errno != EINTR) {
1790 ALOGW("poll failed (errno=%d)\n", errno);
1791 usleep(100000);
1792 }
1793 } else {
1794 // Some events occurred.
1795 mPendingEventCount = size_t(pollResult);
1796 }
1797 }
1798
1799 // All done, return the number of events we read.
1800 return event - buffer;
1801}
1802
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001803std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001804 std::scoped_lock _l(mLock);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001805
1806 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001807 if (device == nullptr || !device->videoDevice) {
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001808 return {};
1809 }
1810 return device->videoDevice->consumeFrames();
1811}
1812
Michael Wrightd02c5b62014-02-10 15:10:22 -08001813void EventHub::wake() {
1814 ALOGV("wake() called");
1815
1816 ssize_t nWrite;
1817 do {
1818 nWrite = write(mWakeWritePipeFd, "W", 1);
1819 } while (nWrite == -1 && errno == EINTR);
1820
1821 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001822 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001823 }
1824}
1825
1826void EventHub::scanDevicesLocked() {
Usama Arifb27c8e62021-06-03 16:44:09 +01001827 status_t result;
1828 std::error_code errorCode;
1829
1830 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
1831 result = scanDirLocked(DEVICE_INPUT_PATH);
1832 if (result < 0) {
1833 ALOGE("scan dir failed for %s", DEVICE_INPUT_PATH);
1834 }
1835 } else {
1836 if (errorCode) {
1837 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
1838 errorCode.message().c_str());
1839 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001840 }
Philip Quinn39b81682019-01-09 22:20:39 -08001841 if (isV4lScanningEnabled()) {
Usama Arifb27c8e62021-06-03 16:44:09 +01001842 result = scanVideoDirLocked(DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08001843 if (result != OK) {
Usama Arifb27c8e62021-06-03 16:44:09 +01001844 ALOGE("scan video dir failed for %s", DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08001845 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001846 }
Chris Ye989bb932020-07-04 16:18:59 -07001847 if (mDevices.find(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) == mDevices.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001848 createVirtualKeyboardLocked();
1849 }
1850}
1851
1852// ----------------------------------------------------------------------------
1853
Michael Wrightd02c5b62014-02-10 15:10:22 -08001854static const int32_t GAMEPAD_KEYCODES[] = {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001855 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C, //
1856 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z, //
1857 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1, //
1858 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2, //
1859 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR, //
1860 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE, //
Michael Wrightd02c5b62014-02-10 15:10:22 -08001861};
1862
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001863status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001864 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001865 struct epoll_event eventItem = {};
1866 eventItem.events = EPOLLIN | EPOLLWAKEUP;
1867 eventItem.data.fd = fd;
1868 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1869 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001870 return -errno;
1871 }
1872 return OK;
1873}
1874
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001875status_t EventHub::unregisterFdFromEpoll(int fd) {
1876 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
1877 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
1878 return -errno;
1879 }
1880 return OK;
1881}
1882
Chris Ye989bb932020-07-04 16:18:59 -07001883status_t EventHub::registerDeviceForEpollLocked(Device& device) {
1884 status_t result = registerFdForEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001885 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07001886 ALOGE("Could not add input device fd to epoll for device %" PRId32, device.id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001887 return result;
1888 }
Chris Ye989bb932020-07-04 16:18:59 -07001889 if (device.videoDevice) {
1890 registerVideoDeviceForEpollLocked(*device.videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001891 }
1892 return result;
1893}
1894
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001895void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
1896 status_t result = registerFdForEpoll(videoDevice.getFd());
1897 if (result != OK) {
1898 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
1899 }
1900}
1901
Chris Ye989bb932020-07-04 16:18:59 -07001902status_t EventHub::unregisterDeviceFromEpollLocked(Device& device) {
1903 if (device.hasValidFd()) {
1904 status_t result = unregisterFdFromEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001905 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07001906 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device.id);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001907 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001908 }
1909 }
Chris Ye989bb932020-07-04 16:18:59 -07001910 if (device.videoDevice) {
1911 unregisterVideoDeviceFromEpollLocked(*device.videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001912 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001913 return OK;
1914}
1915
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001916void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
1917 if (videoDevice.hasValidFd()) {
1918 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
1919 if (result != OK) {
1920 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001921 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001922 }
1923 }
1924}
1925
Chris Yed3fef462021-03-07 17:10:08 -08001926void EventHub::reportDeviceAddedForStatisticsLocked(const InputDeviceIdentifier& identifier,
Dominik Laskowski2f01d772022-03-23 16:01:29 -07001927 ftl::Flags<InputDeviceClass> classes) {
Chris Ye657c2f02021-05-25 16:24:37 -07001928 SHA256_CTX ctx;
1929 SHA256_Init(&ctx);
1930 SHA256_Update(&ctx, reinterpret_cast<const uint8_t*>(identifier.uniqueId.c_str()),
1931 identifier.uniqueId.size());
1932 std::array<uint8_t, SHA256_DIGEST_LENGTH> digest;
1933 SHA256_Final(digest.data(), &ctx);
1934
1935 std::string obfuscatedId;
1936 for (size_t i = 0; i < OBFUSCATED_LENGTH; i++) {
1937 obfuscatedId += StringPrintf("%02x", digest[i]);
1938 }
1939
Chris Yed3fef462021-03-07 17:10:08 -08001940 android::util::stats_write(android::util::INPUTDEVICE_REGISTERED, identifier.name.c_str(),
1941 identifier.vendor, identifier.product, identifier.version,
Chris Ye657c2f02021-05-25 16:24:37 -07001942 identifier.bus, obfuscatedId.c_str(), classes.get());
Chris Yed3fef462021-03-07 17:10:08 -08001943}
1944
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00001945void EventHub::openDeviceLocked(const std::string& devicePath) {
1946 // If an input device happens to register around the time when EventHub's constructor runs, it
1947 // is possible that the same input event node (for example, /dev/input/event3) will be noticed
1948 // in both 'inotify' callback and also in the 'scanDirLocked' pass. To prevent duplicate devices
1949 // from getting registered, ensure that this path is not already covered by an existing device.
1950 for (const auto& [deviceId, device] : mDevices) {
1951 if (device->path == devicePath) {
1952 return; // device was already registered
1953 }
1954 }
1955
Michael Wrightd02c5b62014-02-10 15:10:22 -08001956 char buffer[80];
1957
Chris Ye8594e192020-07-14 10:34:06 -07001958 ALOGV("Opening device: %s", devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001959
Chris Ye8594e192020-07-14 10:34:06 -07001960 int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001961 if (fd < 0) {
Chris Ye8594e192020-07-14 10:34:06 -07001962 ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00001963 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001964 }
1965
1966 InputDeviceIdentifier identifier;
1967
1968 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001969 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Chris Ye8594e192020-07-14 10:34:06 -07001970 ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001971 } else {
1972 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001973 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001974 }
1975
1976 // Check to see if the device is on our excluded list
1977 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001978 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001979 if (identifier.name == item) {
Chris Ye8594e192020-07-14 10:34:06 -07001980 ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001981 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00001982 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001983 }
1984 }
1985
1986 // Get device driver version.
1987 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001988 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Chris Ye8594e192020-07-14 10:34:06 -07001989 ALOGE("could not get driver version for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001990 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00001991 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001992 }
1993
1994 // Get device identifier.
1995 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001996 if (ioctl(fd, EVIOCGID, &inputId)) {
Chris Ye8594e192020-07-14 10:34:06 -07001997 ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001998 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00001999 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002000 }
2001 identifier.bus = inputId.bustype;
2002 identifier.product = inputId.product;
2003 identifier.vendor = inputId.vendor;
2004 identifier.version = inputId.version;
2005
2006 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002007 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
2008 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002009 } else {
2010 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002011 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002012 }
2013
2014 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002015 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
2016 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002017 } else {
2018 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002019 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002020 }
2021
2022 // Fill in the descriptor.
2023 assignDescriptorLocked(identifier);
2024
Michael Wrightd02c5b62014-02-10 15:10:22 -08002025 // Allocate device. (The device object takes ownership of the fd at this point.)
2026 int32_t deviceId = mNextDeviceId++;
Chris Ye989bb932020-07-04 16:18:59 -07002027 std::unique_ptr<Device> device = std::make_unique<Device>(fd, deviceId, devicePath, identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002028
Chris Ye8594e192020-07-14 10:34:06 -07002029 ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002030 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002031 " vendor %04x\n"
2032 " product %04x\n"
2033 " version %04x\n",
2034 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002035 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
2036 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
2037 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
2038 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002039 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
2040 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002041
2042 // Load the configuration file for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002043 device->loadConfigurationLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002044
Chris Yee2b1e5c2021-03-10 22:45:12 -08002045 // Check the sysfs root path
Prabir Pradhan51894782022-08-23 16:29:10 +00002046 const std::optional<std::filesystem::path> sysfsRootPath = getSysfsRootPath(devicePath.c_str());
Chris Yee2b1e5c2021-03-10 22:45:12 -08002047 if (sysfsRootPath.has_value()) {
Chris Ye1dd2e5c2021-04-04 23:12:41 -07002048 std::shared_ptr<AssociatedDevice> associatedDevice;
2049 for (const auto& [id, dev] : mDevices) {
Prabir Pradhan51894782022-08-23 16:29:10 +00002050 if (dev->associatedDevice && dev->associatedDevice->sysfsRootPath == *sysfsRootPath) {
Chris Ye1dd2e5c2021-04-04 23:12:41 -07002051 associatedDevice = dev->associatedDevice;
2052 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08002053 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07002054 if (!associatedDevice) {
2055 associatedDevice = std::make_shared<AssociatedDevice>(sysfsRootPath.value());
Prabir Pradhan51894782022-08-23 16:29:10 +00002056 associatedDevice->configureBatteryLocked();
2057 associatedDevice->configureLightsLocked();
Chris Ye1dd2e5c2021-04-04 23:12:41 -07002058 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08002059
Chris Ye1dd2e5c2021-04-04 23:12:41 -07002060 device->associatedDevice = associatedDevice;
Chris Yee2b1e5c2021-03-10 22:45:12 -08002061 }
Chris Ye3fdbfef2021-01-06 18:45:18 -08002062
Michael Wrightd02c5b62014-02-10 15:10:22 -08002063 // Figure out the kinds of events the device reports.
Chris Ye66fbac32020-07-06 20:36:43 -07002064 device->readDeviceBitMask(EVIOCGBIT(EV_KEY, 0), device->keyBitmask);
2065 device->readDeviceBitMask(EVIOCGBIT(EV_ABS, 0), device->absBitmask);
2066 device->readDeviceBitMask(EVIOCGBIT(EV_REL, 0), device->relBitmask);
2067 device->readDeviceBitMask(EVIOCGBIT(EV_SW, 0), device->swBitmask);
2068 device->readDeviceBitMask(EVIOCGBIT(EV_LED, 0), device->ledBitmask);
2069 device->readDeviceBitMask(EVIOCGBIT(EV_FF, 0), device->ffBitmask);
Chris Yef59a2f42020-10-16 12:55:26 -07002070 device->readDeviceBitMask(EVIOCGBIT(EV_MSC, 0), device->mscBitmask);
Chris Ye66fbac32020-07-06 20:36:43 -07002071 device->readDeviceBitMask(EVIOCGPROP(0), device->propBitmask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002072
2073 // See if this is a keyboard. Ignore everything in the button range except for
2074 // joystick and gamepad buttons which are handled like keyboards for the most part.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002075 bool haveKeyboardKeys =
Chris Ye66fbac32020-07-06 20:36:43 -07002076 device->keyBitmask.any(0, BTN_MISC) || device->keyBitmask.any(BTN_WHEEL, KEY_MAX + 1);
2077 bool haveGamepadButtons = device->keyBitmask.any(BTN_MISC, BTN_MOUSE) ||
2078 device->keyBitmask.any(BTN_JOYSTICK, BTN_DIGI);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002079 if (haveKeyboardKeys || haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002080 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002081 }
2082
2083 // See if this is a cursor device such as a trackball or mouse.
Chris Ye66fbac32020-07-06 20:36:43 -07002084 if (device->keyBitmask.test(BTN_MOUSE) && device->relBitmask.test(REL_X) &&
2085 device->relBitmask.test(REL_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002086 device->classes |= InputDeviceClass::CURSOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002087 }
2088
Prashant Malani1941ff52015-08-11 18:29:28 -07002089 // See if this is a rotary encoder type device.
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07002090 std::string deviceType;
2091 if (device->configuration && device->configuration->tryGetProperty("device.type", deviceType)) {
2092 if (deviceType == "rotaryEncoder") {
Chris Ye1b0c7342020-07-28 21:57:03 -07002093 device->classes |= InputDeviceClass::ROTARY_ENCODER;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002094 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002095 }
2096
Michael Wrightd02c5b62014-02-10 15:10:22 -08002097 // See if this is a touch pad.
2098 // Is this a new modern multi-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002099 if (device->absBitmask.test(ABS_MT_POSITION_X) && device->absBitmask.test(ABS_MT_POSITION_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002100 // Some joysticks such as the PS3 controller report axes that conflict
2101 // with the ABS_MT range. Try to confirm that the device really is
2102 // a touch screen.
Chris Ye66fbac32020-07-06 20:36:43 -07002103 if (device->keyBitmask.test(BTN_TOUCH) || !haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002104 device->classes |= (InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002105 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002106 // Is this an old style single-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002107 } else if (device->keyBitmask.test(BTN_TOUCH) && device->absBitmask.test(ABS_X) &&
2108 device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002109 device->classes |= InputDeviceClass::TOUCH;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002110 // Is this a BT stylus?
Chris Ye66fbac32020-07-06 20:36:43 -07002111 } else if ((device->absBitmask.test(ABS_PRESSURE) || device->keyBitmask.test(BTN_TOUCH)) &&
2112 !device->absBitmask.test(ABS_X) && !device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002113 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -07002114 // Keyboard will try to claim some of the buttons but we really want to reserve those so we
2115 // can fuse it with the touch screen data, so just take them back. Note this means an
2116 // external stylus cannot also be a keyboard device.
Chris Ye1b0c7342020-07-28 21:57:03 -07002117 device->classes &= ~InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002118 }
2119
2120 // See if this device is a joystick.
2121 // Assumes that joysticks always have gamepad buttons in order to distinguish them
2122 // from other devices such as accelerometers that also have absolute axes.
2123 if (haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002124 auto assumedClasses = device->classes | InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002125 for (int i = 0; i <= ABS_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002126 if (device->absBitmask.test(i) &&
Chris Ye1b0c7342020-07-28 21:57:03 -07002127 (getAbsAxisUsage(i, assumedClasses).test(InputDeviceClass::JOYSTICK))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002128 device->classes = assumedClasses;
2129 break;
2130 }
2131 }
2132 }
2133
Chris Yef59a2f42020-10-16 12:55:26 -07002134 // Check whether this device is an accelerometer.
2135 if (device->propBitmask.test(INPUT_PROP_ACCELEROMETER)) {
2136 device->classes |= InputDeviceClass::SENSOR;
2137 }
2138
Michael Wrightd02c5b62014-02-10 15:10:22 -08002139 // Check whether this device has switches.
2140 for (int i = 0; i <= SW_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002141 if (device->swBitmask.test(i)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002142 device->classes |= InputDeviceClass::SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002143 break;
2144 }
2145 }
2146
2147 // Check whether this device supports the vibrator.
Chris Ye66fbac32020-07-06 20:36:43 -07002148 if (device->ffBitmask.test(FF_RUMBLE)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002149 device->classes |= InputDeviceClass::VIBRATOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002150 }
2151
2152 // Configure virtual keys.
Chris Ye1b0c7342020-07-28 21:57:03 -07002153 if ((device->classes.test(InputDeviceClass::TOUCH))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002154 // Load the virtual keys for the touch screen, if any.
2155 // We do this now so that we can make sure to load the keymap if necessary.
Chris Ye989bb932020-07-04 16:18:59 -07002156 bool success = device->loadVirtualKeyMapLocked();
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06002157 if (success) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002158 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002159 }
2160 }
2161
2162 // Load the key map.
Chris Yef59a2f42020-10-16 12:55:26 -07002163 // We need to do this for joysticks too because the key layout may specify axes, and for
2164 // sensor as well because the key layout may specify the axes to sensor data mapping.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002165 status_t keyMapStatus = NAME_NOT_FOUND;
Chris Yef59a2f42020-10-16 12:55:26 -07002166 if (device->classes.any(InputDeviceClass::KEYBOARD | InputDeviceClass::JOYSTICK |
2167 InputDeviceClass::SENSOR)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002168 // Load the keymap for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002169 keyMapStatus = device->loadKeyMapLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002170 }
2171
2172 // Configure the keyboard, gamepad or virtual keyboard.
Chris Ye1b0c7342020-07-28 21:57:03 -07002173 if (device->classes.test(InputDeviceClass::KEYBOARD)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002174 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002175 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002176 isEligibleBuiltInKeyboard(device->identifier, device->configuration.get(),
2177 &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002178 mBuiltInKeyboardId = device->id;
2179 }
2180
2181 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
Chris Ye989bb932020-07-04 16:18:59 -07002182 if (device->hasKeycodeLocked(AKEYCODE_Q)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002183 device->classes |= InputDeviceClass::ALPHAKEY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002184 }
2185
2186 // See if this device has a DPAD.
Chris Ye989bb932020-07-04 16:18:59 -07002187 if (device->hasKeycodeLocked(AKEYCODE_DPAD_UP) &&
2188 device->hasKeycodeLocked(AKEYCODE_DPAD_DOWN) &&
2189 device->hasKeycodeLocked(AKEYCODE_DPAD_LEFT) &&
2190 device->hasKeycodeLocked(AKEYCODE_DPAD_RIGHT) &&
2191 device->hasKeycodeLocked(AKEYCODE_DPAD_CENTER)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002192 device->classes |= InputDeviceClass::DPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002193 }
2194
2195 // See if this device has a gamepad.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002196 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES) / sizeof(GAMEPAD_KEYCODES[0]); i++) {
Chris Ye989bb932020-07-04 16:18:59 -07002197 if (device->hasKeycodeLocked(GAMEPAD_KEYCODES[i])) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002198 device->classes |= InputDeviceClass::GAMEPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002199 break;
2200 }
2201 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002202 }
2203
2204 // If the device isn't recognized as something we handle, don't monitor it.
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002205 if (device->classes == ftl::Flags<InputDeviceClass>(0)) {
Chris Ye8594e192020-07-14 10:34:06 -07002206 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002207 device->identifier.name.c_str());
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002208 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002209 }
2210
Chris Ye3fdbfef2021-01-06 18:45:18 -08002211 // Classify InputDeviceClass::BATTERY.
Prabir Pradhan51894782022-08-23 16:29:10 +00002212 if (device->associatedDevice && !device->associatedDevice->batteryInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002213 device->classes |= InputDeviceClass::BATTERY;
2214 }
Kim Low03ea0352020-11-06 12:45:07 -08002215
Chris Ye3fdbfef2021-01-06 18:45:18 -08002216 // Classify InputDeviceClass::LIGHT.
Prabir Pradhan51894782022-08-23 16:29:10 +00002217 if (device->associatedDevice && !device->associatedDevice->lightInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002218 device->classes |= InputDeviceClass::LIGHT;
Kim Low03ea0352020-11-06 12:45:07 -08002219 }
2220
Tim Kilbourn063ff532015-04-08 10:26:18 -07002221 // Determine whether the device has a mic.
Chris Ye989bb932020-07-04 16:18:59 -07002222 if (device->deviceHasMicLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002223 device->classes |= InputDeviceClass::MIC;
Tim Kilbourn063ff532015-04-08 10:26:18 -07002224 }
2225
Michael Wrightd02c5b62014-02-10 15:10:22 -08002226 // Determine whether the device is external or internal.
Chris Ye989bb932020-07-04 16:18:59 -07002227 if (device->isExternalDeviceLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002228 device->classes |= InputDeviceClass::EXTERNAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002229 }
2230
Chris Ye1b0c7342020-07-28 21:57:03 -07002231 if (device->classes.any(InputDeviceClass::JOYSTICK | InputDeviceClass::DPAD) &&
2232 device->classes.test(InputDeviceClass::GAMEPAD)) {
Chris Ye989bb932020-07-04 16:18:59 -07002233 device->controllerNumber = getNextControllerNumberLocked(device->identifier.name);
2234 device->setLedForControllerLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002235 }
2236
Chris Ye989bb932020-07-04 16:18:59 -07002237 if (registerDeviceForEpollLocked(*device) != OK) {
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002238 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002239 }
2240
Chris Ye989bb932020-07-04 16:18:59 -07002241 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002242
Chris Ye1b0c7342020-07-28 21:57:03 -07002243 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=%s, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002244 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Chris Ye1b0c7342020-07-28 21:57:03 -07002245 deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(),
2246 device->classes.string().c_str(), device->configurationFile.c_str(),
2247 device->keyMap.keyLayoutFile.c_str(), device->keyMap.keyCharacterMapFile.c_str(),
2248 toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002249
Chris Ye989bb932020-07-04 16:18:59 -07002250 addDeviceLocked(std::move(device));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002251}
2252
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002253void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
2254 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
2255 if (!videoDevice) {
2256 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
2257 return;
2258 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002259 // Transfer ownership of this video device to a matching input device
Chris Ye989bb932020-07-04 16:18:59 -07002260 for (const auto& [id, device] : mDevices) {
Chris Yed3fef462021-03-07 17:10:08 -08002261 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002262 return; // 'device' now owns 'videoDevice'
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002263 }
2264 }
2265
2266 // Couldn't find a matching input device, so just add it to a temporary holding queue.
2267 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002268 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002269 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002270 mUnattachedVideoDevices.push_back(std::move(videoDevice));
2271}
2272
Chris Yed3fef462021-03-07 17:10:08 -08002273bool EventHub::tryAddVideoDeviceLocked(EventHub::Device& device,
2274 std::unique_ptr<TouchVideoDevice>& videoDevice) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002275 if (videoDevice->getName() != device.identifier.name) {
2276 return false;
2277 }
2278 device.videoDevice = std::move(videoDevice);
2279 if (device.enabled) {
2280 registerVideoDeviceForEpollLocked(*device.videoDevice);
2281 }
2282 return true;
2283}
2284
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002285bool EventHub::isDeviceEnabled(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002286 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002287 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002288 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002289 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2290 return false;
2291 }
2292 return device->enabled;
2293}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002294
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002295status_t EventHub::enableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002296 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002297 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002298 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002299 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2300 return BAD_VALUE;
2301 }
2302 if (device->enabled) {
2303 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
2304 return OK;
2305 }
2306 status_t result = device->enable();
2307 if (result != OK) {
2308 ALOGE("Failed to enable device %" PRId32, deviceId);
2309 return result;
2310 }
2311
Chris Ye989bb932020-07-04 16:18:59 -07002312 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002313
Chris Ye989bb932020-07-04 16:18:59 -07002314 return registerDeviceForEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002315}
2316
2317status_t EventHub::disableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002318 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002319 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002320 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002321 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2322 return BAD_VALUE;
2323 }
2324 if (!device->enabled) {
2325 ALOGW("Duplicate call to %s, input device already disabled", __func__);
2326 return OK;
2327 }
Chris Ye989bb932020-07-04 16:18:59 -07002328 unregisterDeviceFromEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002329 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002330}
2331
2332void EventHub::createVirtualKeyboardLocked() {
2333 InputDeviceIdentifier identifier;
2334 identifier.name = "Virtual";
2335 identifier.uniqueId = "<virtual>";
2336 assignDescriptorLocked(identifier);
2337
Chris Ye989bb932020-07-04 16:18:59 -07002338 std::unique_ptr<Device> device =
2339 std::make_unique<Device>(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
2340 identifier);
Chris Ye1b0c7342020-07-28 21:57:03 -07002341 device->classes = InputDeviceClass::KEYBOARD | InputDeviceClass::ALPHAKEY |
2342 InputDeviceClass::DPAD | InputDeviceClass::VIRTUAL;
Chris Ye989bb932020-07-04 16:18:59 -07002343 device->loadKeyMapLocked();
2344 addDeviceLocked(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002345}
2346
Chris Ye989bb932020-07-04 16:18:59 -07002347void EventHub::addDeviceLocked(std::unique_ptr<Device> device) {
Chris Yed3fef462021-03-07 17:10:08 -08002348 reportDeviceAddedForStatisticsLocked(device->identifier, device->classes);
Chris Ye989bb932020-07-04 16:18:59 -07002349 mOpeningDevices.push_back(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002350}
2351
Chris Ye989bb932020-07-04 16:18:59 -07002352int32_t EventHub::getNextControllerNumberLocked(const std::string& name) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002353 if (mControllerNumbers.isFull()) {
2354 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Chris Ye989bb932020-07-04 16:18:59 -07002355 name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002356 return 0;
2357 }
2358 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
2359 // one
2360 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
2361}
2362
Chris Ye989bb932020-07-04 16:18:59 -07002363void EventHub::releaseControllerNumberLocked(int32_t num) {
2364 if (num > 0) {
2365 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002366 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002367}
2368
Chris Ye8594e192020-07-14 10:34:06 -07002369void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002370 Device* device = getDeviceByPathLocked(devicePath);
Chris Ye989bb932020-07-04 16:18:59 -07002371 if (device != nullptr) {
2372 closeDeviceLocked(*device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002373 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002374 }
Chris Ye8594e192020-07-14 10:34:06 -07002375 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002376}
2377
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002378/**
2379 * Find the video device by filename, and close it.
2380 * The video device is closed by path during an inotify event, where we don't have the
2381 * additional context about the video device fd, or the associated input device.
2382 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002383void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002384 // A video device may be owned by an existing input device, or it may be stored in
2385 // the mUnattachedVideoDevices queue. Check both locations.
Chris Ye989bb932020-07-04 16:18:59 -07002386 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002387 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002388 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002389 device->videoDevice = nullptr;
2390 return;
2391 }
2392 }
Siarhei Vishniakouf47c339e2021-12-30 11:22:26 -08002393 std::erase_if(mUnattachedVideoDevices,
2394 [&devicePath](const std::unique_ptr<TouchVideoDevice>& videoDevice) {
2395 return videoDevice->getPath() == devicePath;
2396 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08002397}
2398
2399void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002400 mUnattachedVideoDevices.clear();
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002401 while (!mDevices.empty()) {
2402 closeDeviceLocked(*(mDevices.begin()->second));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002403 }
2404}
2405
Chris Ye989bb932020-07-04 16:18:59 -07002406void EventHub::closeDeviceLocked(Device& device) {
2407 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=%s", device.path.c_str(),
2408 device.identifier.name.c_str(), device.id, device.fd, device.classes.string().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002409
Chris Ye989bb932020-07-04 16:18:59 -07002410 if (device.id == mBuiltInKeyboardId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002411 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Chris Ye989bb932020-07-04 16:18:59 -07002412 device.path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002413 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
2414 }
2415
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002416 unregisterDeviceFromEpollLocked(device);
Chris Ye989bb932020-07-04 16:18:59 -07002417 if (device.videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002418 // This must be done after the video device is removed from epoll
Chris Ye989bb932020-07-04 16:18:59 -07002419 mUnattachedVideoDevices.push_back(std::move(device.videoDevice));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002420 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002421
Chris Ye989bb932020-07-04 16:18:59 -07002422 releaseControllerNumberLocked(device.controllerNumber);
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002423 device.controllerNumber = 0;
Chris Ye989bb932020-07-04 16:18:59 -07002424 device.close();
Chris Ye989bb932020-07-04 16:18:59 -07002425 mClosingDevices.push_back(std::move(mDevices[device.id]));
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002426
Chris Ye989bb932020-07-04 16:18:59 -07002427 mDevices.erase(device.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002428}
2429
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002430base::Result<void> EventHub::readNotifyLocked() {
2431 static constexpr auto EVENT_SIZE = static_cast<ssize_t>(sizeof(inotify_event));
2432 uint8_t eventBuffer[512];
2433 ssize_t sizeRead;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002434
2435 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002436 do {
2437 sizeRead = read(mINotifyFd, eventBuffer, sizeof(eventBuffer));
2438 } while (sizeRead < 0 && errno == EINTR);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002439
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002440 if (sizeRead < EVENT_SIZE) return Errorf("could not get event, %s", strerror(errno));
2441
2442 for (ssize_t eventPos = 0; sizeRead >= EVENT_SIZE;) {
2443 const inotify_event* event;
2444 event = (const inotify_event*)(eventBuffer + eventPos);
2445 if (event->len == 0) continue;
2446
2447 handleNotifyEventLocked(*event);
2448
2449 const ssize_t eventSize = EVENT_SIZE + event->len;
2450 sizeRead -= eventSize;
2451 eventPos += eventSize;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002452 }
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002453 return {};
2454}
2455
2456void EventHub::handleNotifyEventLocked(const inotify_event& event) {
2457 if (event.wd == mDeviceInputWd) {
2458 std::string filename = std::string(DEVICE_INPUT_PATH) + "/" + event.name;
2459 if (event.mask & IN_CREATE) {
2460 openDeviceLocked(filename);
2461 } else {
2462 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
2463 closeDeviceByPathLocked(filename);
2464 }
2465 } else if (event.wd == mDeviceWd) {
2466 if (isV4lTouchNode(event.name)) {
2467 std::string filename = std::string(DEVICE_PATH) + "/" + event.name;
2468 if (event.mask & IN_CREATE) {
2469 openVideoDeviceLocked(filename);
2470 } else {
2471 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
2472 closeVideoDeviceByPathLocked(filename);
2473 }
2474 } else if (strcmp(event.name, "input") == 0 && event.mask & IN_CREATE) {
2475 addDeviceInputInotify();
2476 }
2477 } else {
2478 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event.wd);
2479 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002480}
2481
Chris Ye8594e192020-07-14 10:34:06 -07002482status_t EventHub::scanDirLocked(const std::string& dirname) {
2483 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2484 openDeviceLocked(entry.path());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002485 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002486 return 0;
2487}
2488
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002489/**
2490 * Look for all dirname/v4l-touch* devices, and open them.
2491 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002492status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Chris Ye8594e192020-07-14 10:34:06 -07002493 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2494 if (isV4lTouchNode(entry.path())) {
2495 ALOGI("Found touch video device %s", entry.path().c_str());
2496 openVideoDeviceLocked(entry.path());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002497 }
2498 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002499 return OK;
2500}
2501
Michael Wrightd02c5b62014-02-10 15:10:22 -08002502void EventHub::requestReopenDevices() {
2503 ALOGV("requestReopenDevices() called");
2504
Chris Ye87143712020-11-10 05:05:58 +00002505 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002506 mNeedToReopenDevices = true;
2507}
2508
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002509void EventHub::dump(std::string& dump) {
2510 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002511
2512 { // acquire lock
Chris Ye87143712020-11-10 05:05:58 +00002513 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002514
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002515 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002516
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002517 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002518
Chris Ye989bb932020-07-04 16:18:59 -07002519 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002520 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002521 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002522 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002523 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002524 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002525 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002526 }
Chris Ye1b0c7342020-07-28 21:57:03 -07002527 dump += StringPrintf(INDENT3 "Classes: %s\n", device->classes.string().c_str());
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002528 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002529 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002530 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
2531 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002532 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002533 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002534 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002535 "product=0x%04x, version=0x%04x\n",
2536 device->identifier.bus, device->identifier.vendor,
2537 device->identifier.product, device->identifier.version);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002538 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002539 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002540 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002541 device->keyMap.keyCharacterMapFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002542 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002543 device->configurationFile.c_str());
Prabir Pradhan51894782022-08-23 16:29:10 +00002544 dump += StringPrintf(INDENT3 "VideoDevice: %s\n",
2545 device->videoDevice ? device->videoDevice->dump().c_str()
2546 : "<none>");
2547 dump += StringPrintf(INDENT3 "SysfsDevicePath: %s\n",
2548 device->associatedDevice
2549 ? device->associatedDevice->sysfsRootPath.c_str()
2550 : "<none>");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002551 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002552
2553 dump += INDENT "Unattached video devices:\n";
2554 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
2555 dump += INDENT2 + videoDevice->dump() + "\n";
2556 }
2557 if (mUnattachedVideoDevices.empty()) {
2558 dump += INDENT2 "<none>\n";
2559 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002560 } // release lock
2561}
2562
2563void EventHub::monitor() {
2564 // Acquire and release the lock to ensure that the event hub has not deadlocked.
Chris Ye1c2e0892020-11-30 21:41:44 -08002565 std::unique_lock<std::mutex> lock(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002566}
2567
Michael Wrightd02c5b62014-02-10 15:10:22 -08002568}; // namespace android