blob: 8bd3899469c99506d5dc8c7db5ca9166b228f79c [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;
Chris Ye1b0c7342020-07-28 21:57:03 -070063using namespace android::flag_operators;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080064
Michael Wrightd02c5b62014-02-10 15:10:22 -080065namespace android {
66
Usama Arifb27c8e62021-06-03 16:44:09 +010067static const char* DEVICE_INPUT_PATH = "/dev/input";
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080068// v4l2 devices go directly into /dev
Usama Arifb27c8e62021-06-03 16:44:09 +010069static const char* DEVICE_PATH = "/dev";
Michael Wrightd02c5b62014-02-10 15:10:22 -080070
Chris Ye657c2f02021-05-25 16:24:37 -070071static constexpr size_t OBFUSCATED_LENGTH = 8;
72
Chris Ye87143712020-11-10 05:05:58 +000073static constexpr int32_t FF_STRONG_MAGNITUDE_CHANNEL_IDX = 0;
74static constexpr int32_t FF_WEAK_MAGNITUDE_CHANNEL_IDX = 1;
Chris Ye6393a262020-08-04 19:41:36 -070075
Chris Yee2b1e5c2021-03-10 22:45:12 -080076// Mapping for input battery class node IDs lookup.
77// https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
78static const std::unordered_map<std::string, InputBatteryClass> BATTERY_CLASSES =
79 {{"capacity", InputBatteryClass::CAPACITY},
80 {"capacity_level", InputBatteryClass::CAPACITY_LEVEL},
81 {"status", InputBatteryClass::STATUS}};
82
83// Mapping for input battery class node names lookup.
84// https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
85static const std::unordered_map<InputBatteryClass, std::string> BATTERY_NODES =
86 {{InputBatteryClass::CAPACITY, "capacity"},
87 {InputBatteryClass::CAPACITY_LEVEL, "capacity_level"},
88 {InputBatteryClass::STATUS, "status"}};
89
Kim Low03ea0352020-11-06 12:45:07 -080090// must be kept in sync with definitions in kernel /drivers/power/supply/power_supply_sysfs.c
91static const std::unordered_map<std::string, int32_t> BATTERY_STATUS =
92 {{"Unknown", BATTERY_STATUS_UNKNOWN},
93 {"Charging", BATTERY_STATUS_CHARGING},
94 {"Discharging", BATTERY_STATUS_DISCHARGING},
95 {"Not charging", BATTERY_STATUS_NOT_CHARGING},
96 {"Full", BATTERY_STATUS_FULL}};
97
98// Mapping taken from
99// https://gitlab.freedesktop.org/upower/upower/-/blob/master/src/linux/up-device-supply.c#L484
100static const std::unordered_map<std::string, int32_t> BATTERY_LEVEL = {{"Critical", 5},
101 {"Low", 10},
102 {"Normal", 55},
103 {"High", 70},
104 {"Full", 100},
105 {"Unknown", 50}};
106
Chris Ye3fdbfef2021-01-06 18:45:18 -0800107// Mapping for input led class node names lookup.
108// https://www.kernel.org/doc/html/latest/leds/leds-class.html
109static const std::unordered_map<std::string, InputLightClass> LIGHT_CLASSES =
110 {{"red", InputLightClass::RED},
111 {"green", InputLightClass::GREEN},
112 {"blue", InputLightClass::BLUE},
113 {"global", InputLightClass::GLOBAL},
114 {"brightness", InputLightClass::BRIGHTNESS},
115 {"multi_index", InputLightClass::MULTI_INDEX},
116 {"multi_intensity", InputLightClass::MULTI_INTENSITY},
117 {"max_brightness", InputLightClass::MAX_BRIGHTNESS}};
118
119// Mapping for input multicolor led class node names.
120// https://www.kernel.org/doc/html/latest/leds/leds-class-multicolor.html
121static const std::unordered_map<InputLightClass, std::string> LIGHT_NODES =
122 {{InputLightClass::BRIGHTNESS, "brightness"},
123 {InputLightClass::MULTI_INDEX, "multi_index"},
124 {InputLightClass::MULTI_INTENSITY, "multi_intensity"}};
125
126// Mapping for light color name and the light color
127const std::unordered_map<std::string, LightColor> LIGHT_COLORS = {{"red", LightColor::RED},
128 {"green", LightColor::GREEN},
129 {"blue", LightColor::BLUE}};
130
Michael Wrightd02c5b62014-02-10 15:10:22 -0800131static inline const char* toString(bool value) {
132 return value ? "true" : "false";
133}
134
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100135static std::string sha1(const std::string& in) {
Dan Albert677d87e2014-06-16 17:31:28 -0700136 SHA_CTX ctx;
137 SHA1_Init(&ctx);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100138 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
Dan Albert677d87e2014-06-16 17:31:28 -0700139 u_char digest[SHA_DIGEST_LENGTH];
140 SHA1_Final(digest, &ctx);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800141
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100142 std::string out;
Dan Albert677d87e2014-06-16 17:31:28 -0700143 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100144 out += StringPrintf("%02x", digest[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800145 }
146 return out;
147}
148
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800149/**
150 * Return true if name matches "v4l-touch*"
151 */
Chris Ye8594e192020-07-14 10:34:06 -0700152static bool isV4lTouchNode(std::string name) {
153 return name.find("v4l-touch") != std::string::npos;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800154}
155
Philip Quinn39b81682019-01-09 22:20:39 -0800156/**
157 * Returns true if V4L devices should be scanned.
158 *
159 * The system property ro.input.video_enabled can be used to control whether
160 * EventHub scans and opens V4L devices. As V4L does not support multiple
161 * clients, EventHub effectively blocks access to these devices when it opens
Siarhei Vishniakou29f88492019-04-05 14:11:43 -0700162 * them.
163 *
164 * Setting this to "false" would prevent any video devices from being discovered and
165 * associated with input devices.
166 *
167 * This property can be used as follows:
168 * 1. To turn off features that are dependent on video device presence.
169 * 2. During testing and development, to allow other clients to read video devices
170 * directly from /dev.
Philip Quinn39b81682019-01-09 22:20:39 -0800171 */
172static bool isV4lScanningEnabled() {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700173 return property_get_bool("ro.input.video_enabled", true /* default_value */);
Philip Quinn39b81682019-01-09 22:20:39 -0800174}
175
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800176static nsecs_t processEventTimestamp(const struct input_event& event) {
177 // Use the time specified in the event instead of the current time
178 // so that downstream code can get more accurate estimates of
179 // event dispatch latency from the time the event is enqueued onto
180 // the evdev client buffer.
181 //
182 // The event's timestamp fortuitously uses the same monotonic clock
183 // time base as the rest of Android. The kernel event device driver
184 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
185 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
186 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
187 // system call that also queries ktime_get_ts().
188
189 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.time.tv_sec) +
190 microseconds_to_nanoseconds(event.time.tv_usec);
191 return inputEventTime;
192}
193
Kim Low03ea0352020-11-06 12:45:07 -0800194/**
195 * Returns the sysfs root path of the input device
196 *
197 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800198static std::optional<std::filesystem::path> getSysfsRootPath(const char* devicePath) {
Kim Low03ea0352020-11-06 12:45:07 -0800199 std::error_code errorCode;
200
201 // Stat the device path to get the major and minor number of the character file
202 struct stat statbuf;
203 if (stat(devicePath, &statbuf) == -1) {
204 ALOGE("Could not stat device %s due to error: %s.", devicePath, std::strerror(errno));
Chris Ye3fdbfef2021-01-06 18:45:18 -0800205 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800206 }
207
208 unsigned int major_num = major(statbuf.st_rdev);
209 unsigned int minor_num = minor(statbuf.st_rdev);
210
211 // Realpath "/sys/dev/char/{major}:{minor}" to get the sysfs path to the input event
212 auto sysfsPath = std::filesystem::path("/sys/dev/char/");
213 sysfsPath /= std::to_string(major_num) + ":" + std::to_string(minor_num);
214 sysfsPath = std::filesystem::canonical(sysfsPath, errorCode);
215
216 // Make sure nothing went wrong in call to canonical()
217 if (errorCode) {
218 ALOGW("Could not run filesystem::canonical() due to error %d : %s.", errorCode.value(),
219 errorCode.message().c_str());
Chris Ye3fdbfef2021-01-06 18:45:18 -0800220 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800221 }
222
223 // Continue to go up a directory until we reach a directory named "input"
224 while (sysfsPath != "/" && sysfsPath.filename() != "input") {
225 sysfsPath = sysfsPath.parent_path();
226 }
227
228 // Then go up one more and you will be at the sysfs root of the device
229 sysfsPath = sysfsPath.parent_path();
230
231 // Make sure we didn't reach root path and that directory actually exists
232 if (sysfsPath == "/" || !std::filesystem::exists(sysfsPath, errorCode)) {
233 if (errorCode) {
234 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
235 errorCode.message().c_str());
236 }
237
238 // Not found
Chris Ye3fdbfef2021-01-06 18:45:18 -0800239 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800240 }
241
242 return sysfsPath;
243}
244
245/**
Chris Ye3fdbfef2021-01-06 18:45:18 -0800246 * Returns the list of files under a specified path.
Kim Low03ea0352020-11-06 12:45:07 -0800247 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800248static std::vector<std::filesystem::path> allFilesInPath(const std::filesystem::path& path) {
249 std::vector<std::filesystem::path> nodes;
250 std::error_code errorCode;
251 auto iter = std::filesystem::directory_iterator(path, errorCode);
252 while (!errorCode && iter != std::filesystem::directory_iterator()) {
253 nodes.push_back(iter->path());
254 iter++;
255 }
256 return nodes;
257}
258
259/**
260 * Returns the list of files under a specified directory in a sysfs path.
261 * Example:
262 * findSysfsNodes(sysfsRootPath, SysfsClass::LEDS) will return all led nodes under "leds" directory
263 * in the sysfs path.
264 */
265static std::vector<std::filesystem::path> findSysfsNodes(const std::filesystem::path& sysfsRoot,
266 SysfsClass clazz) {
Dominik Laskowski75788452021-02-09 18:51:25 -0800267 std::string nodeStr = ftl::enum_string(clazz);
Chris Ye3fdbfef2021-01-06 18:45:18 -0800268 std::for_each(nodeStr.begin(), nodeStr.end(),
269 [](char& c) { c = std::tolower(static_cast<unsigned char>(c)); });
270 std::vector<std::filesystem::path> nodes;
271 for (auto path = sysfsRoot; path != "/" && nodes.empty(); path = path.parent_path()) {
272 nodes = allFilesInPath(path / nodeStr);
273 }
274 return nodes;
275}
276
277static std::optional<std::array<LightColor, COLOR_NUM>> getColorIndexArray(
278 std::filesystem::path path) {
279 std::string indexStr;
280 if (!base::ReadFileToString(path, &indexStr)) {
281 return std::nullopt;
282 }
283
284 // Parse the multi color LED index file, refer to kernel docs
285 // leds/leds-class-multicolor.html
286 std::regex indexPattern("(red|green|blue)\\s(red|green|blue)\\s(red|green|blue)[\\n]");
287 std::smatch results;
288 std::array<LightColor, COLOR_NUM> colors;
289 if (!std::regex_match(indexStr, results, indexPattern)) {
290 return std::nullopt;
291 }
292
293 for (size_t i = 1; i < results.size(); i++) {
294 const auto it = LIGHT_COLORS.find(results[i].str());
295 if (it != LIGHT_COLORS.end()) {
296 // intensities.emplace(it->second, 0);
297 colors[i - 1] = it->second;
Kim Low03ea0352020-11-06 12:45:07 -0800298 }
299 }
Chris Ye3fdbfef2021-01-06 18:45:18 -0800300 return colors;
Kim Low03ea0352020-11-06 12:45:07 -0800301}
302
Michael Wrightd02c5b62014-02-10 15:10:22 -0800303// --- Global Functions ---
304
Chris Ye1b0c7342020-07-28 21:57:03 -0700305Flags<InputDeviceClass> getAbsAxisUsage(int32_t axis, Flags<InputDeviceClass> deviceClasses) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800306 // Touch devices get dibs on touch-related axes.
Chris Ye1b0c7342020-07-28 21:57:03 -0700307 if (deviceClasses.test(InputDeviceClass::TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800308 switch (axis) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700309 case ABS_X:
310 case ABS_Y:
311 case ABS_PRESSURE:
312 case ABS_TOOL_WIDTH:
313 case ABS_DISTANCE:
314 case ABS_TILT_X:
315 case ABS_TILT_Y:
316 case ABS_MT_SLOT:
317 case ABS_MT_TOUCH_MAJOR:
318 case ABS_MT_TOUCH_MINOR:
319 case ABS_MT_WIDTH_MAJOR:
320 case ABS_MT_WIDTH_MINOR:
321 case ABS_MT_ORIENTATION:
322 case ABS_MT_POSITION_X:
323 case ABS_MT_POSITION_Y:
324 case ABS_MT_TOOL_TYPE:
325 case ABS_MT_BLOB_ID:
326 case ABS_MT_TRACKING_ID:
327 case ABS_MT_PRESSURE:
328 case ABS_MT_DISTANCE:
Chris Ye1b0c7342020-07-28 21:57:03 -0700329 return InputDeviceClass::TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800330 }
331 }
332
Chris Yef59a2f42020-10-16 12:55:26 -0700333 if (deviceClasses.test(InputDeviceClass::SENSOR)) {
334 switch (axis) {
335 case ABS_X:
336 case ABS_Y:
337 case ABS_Z:
338 case ABS_RX:
339 case ABS_RY:
340 case ABS_RZ:
341 return InputDeviceClass::SENSOR;
342 }
343 }
344
Michael Wright842500e2015-03-13 17:32:02 -0700345 // External stylus gets the pressure axis
Chris Ye1b0c7342020-07-28 21:57:03 -0700346 if (deviceClasses.test(InputDeviceClass::EXTERNAL_STYLUS)) {
Michael Wright842500e2015-03-13 17:32:02 -0700347 if (axis == ABS_PRESSURE) {
Chris Ye1b0c7342020-07-28 21:57:03 -0700348 return InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -0700349 }
350 }
351
Michael Wrightd02c5b62014-02-10 15:10:22 -0800352 // Joystick devices get the rest.
Chris Ye1b0c7342020-07-28 21:57:03 -0700353 return deviceClasses & InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800354}
355
356// --- EventHub::Device ---
357
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100358EventHub::Device::Device(int fd, int32_t id, const std::string& path,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700359 const InputDeviceIdentifier& identifier)
Chris Ye989bb932020-07-04 16:18:59 -0700360 : fd(fd),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700361 id(id),
362 path(path),
363 identifier(identifier),
364 classes(0),
365 configuration(nullptr),
366 virtualKeyMap(nullptr),
367 ffEffectPlaying(false),
368 ffEffectId(-1),
Chris Ye1dd2e5c2021-04-04 23:12:41 -0700369 associatedDevice(nullptr),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700370 controllerNumber(0),
371 enabled(true),
Chris Ye66fbac32020-07-06 20:36:43 -0700372 isVirtual(fd < 0) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800373
374EventHub::Device::~Device() {
375 close();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800376}
377
378void EventHub::Device::close() {
379 if (fd >= 0) {
380 ::close(fd);
381 fd = -1;
382 }
383}
384
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700385status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100386 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700387 if (fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100388 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700389 return -errno;
390 }
391 enabled = true;
392 return OK;
393}
394
395status_t EventHub::Device::disable() {
396 close();
397 enabled = false;
398 return OK;
399}
400
Chris Ye989bb932020-07-04 16:18:59 -0700401bool EventHub::Device::hasValidFd() const {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700402 return !isVirtual && enabled;
403}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800404
Chris Ye3a1e4462020-08-12 10:13:15 -0700405const std::shared_ptr<KeyCharacterMap> EventHub::Device::getKeyCharacterMap() const {
Chris Ye989bb932020-07-04 16:18:59 -0700406 return keyMap.keyCharacterMap;
407}
408
409template <std::size_t N>
410status_t EventHub::Device::readDeviceBitMask(unsigned long ioctlCode, BitArray<N>& bitArray) {
411 if (!hasValidFd()) {
412 return BAD_VALUE;
413 }
414 if ((_IOC_SIZE(ioctlCode) == 0)) {
415 ioctlCode |= _IOC(0, 0, 0, bitArray.bytes());
416 }
417
418 typename BitArray<N>::Buffer buffer;
419 status_t ret = ioctl(fd, ioctlCode, buffer.data());
420 bitArray.loadFromBuffer(buffer);
421 return ret;
422}
423
424void EventHub::Device::configureFd() {
425 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
426 if (classes.test(InputDeviceClass::KEYBOARD)) {
427 // Disable kernel key repeat since we handle it ourselves
428 unsigned int repeatRate[] = {0, 0};
429 if (ioctl(fd, EVIOCSREP, repeatRate)) {
430 ALOGW("Unable to disable kernel key repeat for %s: %s", path.c_str(), strerror(errno));
431 }
432 }
433
434 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
435 // associated with input events. This is important because the input system
436 // uses the timestamps extensively and assumes they were recorded using the monotonic
437 // clock.
438 int clockId = CLOCK_MONOTONIC;
Chris Yef59a2f42020-10-16 12:55:26 -0700439 if (classes.test(InputDeviceClass::SENSOR)) {
440 // Each new sensor event should use the same time base as
441 // SystemClock.elapsedRealtimeNanos().
442 clockId = CLOCK_BOOTTIME;
443 }
Chris Ye989bb932020-07-04 16:18:59 -0700444 bool usingClockIoctl = !ioctl(fd, EVIOCSCLOCKID, &clockId);
445 ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
446}
447
448bool EventHub::Device::hasKeycodeLocked(int keycode) const {
449 if (!keyMap.haveKeyLayout()) {
450 return false;
451 }
452
453 std::vector<int32_t> scanCodes;
454 keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes);
455 const size_t N = scanCodes.size();
456 for (size_t i = 0; i < N && i <= KEY_MAX; i++) {
457 int32_t sc = scanCodes[i];
458 if (sc >= 0 && sc <= KEY_MAX && keyBitmask.test(sc)) {
459 return true;
460 }
461 }
462
463 return false;
464}
465
466void EventHub::Device::loadConfigurationLocked() {
467 configurationFile =
468 getInputDeviceConfigurationFilePathByDeviceIdentifier(identifier,
469 InputDeviceConfigurationFileType::
470 CONFIGURATION);
471 if (configurationFile.empty()) {
472 ALOGD("No input device configuration file found for device '%s'.", identifier.name.c_str());
473 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500474 android::base::Result<std::unique_ptr<PropertyMap>> propertyMap =
475 PropertyMap::load(configurationFile.c_str());
476 if (!propertyMap.ok()) {
Chris Ye989bb932020-07-04 16:18:59 -0700477 ALOGE("Error loading input device configuration file for device '%s'. "
478 "Using default configuration.",
479 identifier.name.c_str());
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500480 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500481 configuration = std::move(*propertyMap);
Chris Ye989bb932020-07-04 16:18:59 -0700482 }
483 }
484}
485
486bool EventHub::Device::loadVirtualKeyMapLocked() {
487 // The virtual key map is supplied by the kernel as a system board property file.
488 std::string propPath = "/sys/board_properties/virtualkeys.";
489 propPath += identifier.getCanonicalName();
490 if (access(propPath.c_str(), R_OK)) {
491 return false;
492 }
493 virtualKeyMap = VirtualKeyMap::load(propPath);
494 return virtualKeyMap != nullptr;
495}
496
497status_t EventHub::Device::loadKeyMapLocked() {
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500498 return keyMap.load(identifier, configuration.get());
Chris Ye989bb932020-07-04 16:18:59 -0700499}
500
501bool EventHub::Device::isExternalDeviceLocked() {
502 if (configuration) {
503 bool value;
504 if (configuration->tryGetProperty(String8("device.internal"), value)) {
505 return !value;
506 }
507 }
508 return identifier.bus == BUS_USB || identifier.bus == BUS_BLUETOOTH;
509}
510
511bool EventHub::Device::deviceHasMicLocked() {
512 if (configuration) {
513 bool value;
514 if (configuration->tryGetProperty(String8("audio.mic"), value)) {
515 return value;
516 }
517 }
518 return false;
519}
520
521void EventHub::Device::setLedStateLocked(int32_t led, bool on) {
522 int32_t sc;
523 if (hasValidFd() && mapLed(led, &sc) != NAME_NOT_FOUND) {
524 struct input_event ev;
525 ev.time.tv_sec = 0;
526 ev.time.tv_usec = 0;
527 ev.type = EV_LED;
528 ev.code = sc;
529 ev.value = on ? 1 : 0;
530
531 ssize_t nWrite;
532 do {
533 nWrite = write(fd, &ev, sizeof(struct input_event));
534 } while (nWrite == -1 && errno == EINTR);
535 }
536}
537
538void EventHub::Device::setLedForControllerLocked() {
539 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
540 setLedStateLocked(ALED_CONTROLLER_1 + i, controllerNumber == i + 1);
541 }
542}
543
544status_t EventHub::Device::mapLed(int32_t led, int32_t* outScanCode) const {
545 if (!keyMap.haveKeyLayout()) {
546 return NAME_NOT_FOUND;
547 }
548
549 int32_t scanCode;
550 if (keyMap.keyLayoutMap->findScanCodeForLed(led, &scanCode) != NAME_NOT_FOUND) {
551 if (scanCode >= 0 && scanCode <= LED_MAX && ledBitmask.test(scanCode)) {
552 *outScanCode = scanCode;
553 return NO_ERROR;
554 }
555 }
556 return NAME_NOT_FOUND;
557}
558
Chris Ye3fdbfef2021-01-06 18:45:18 -0800559// Check the sysfs path for any input device batteries, returns true if battery found.
Chris Ye1dd2e5c2021-04-04 23:12:41 -0700560bool EventHub::AssociatedDevice::configureBatteryLocked() {
Chris Yee2b1e5c2021-03-10 22:45:12 -0800561 nextBatteryId = 0;
562 // Check if device has any battery.
563 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::POWER_SUPPLY);
564 for (const auto& nodePath : paths) {
565 RawBatteryInfo info;
566 info.id = ++nextBatteryId;
567 info.path = nodePath;
568 info.name = nodePath.filename();
569
570 // Scan the path for all the files
571 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
572 const auto& files = allFilesInPath(nodePath);
573 for (const auto& file : files) {
574 const auto it = BATTERY_CLASSES.find(file.filename().string());
575 if (it != BATTERY_CLASSES.end()) {
576 info.flags |= it->second;
577 }
578 }
579 batteryInfos.insert_or_assign(info.id, info);
580 ALOGD("configureBatteryLocked rawBatteryId %d name %s", info.id, info.name.c_str());
Chris Ye3fdbfef2021-01-06 18:45:18 -0800581 }
Chris Yee2b1e5c2021-03-10 22:45:12 -0800582 return !batteryInfos.empty();
Chris Ye3fdbfef2021-01-06 18:45:18 -0800583}
584
585// Check the sysfs path for any input device lights, returns true if lights found.
Chris Ye1dd2e5c2021-04-04 23:12:41 -0700586bool EventHub::AssociatedDevice::configureLightsLocked() {
Chris Yee2b1e5c2021-03-10 22:45:12 -0800587 nextLightId = 0;
Chris Ye3fdbfef2021-01-06 18:45:18 -0800588 // Check if device has any lights.
Chris Yee2b1e5c2021-03-10 22:45:12 -0800589 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::LEDS);
Chris Ye3fdbfef2021-01-06 18:45:18 -0800590 for (const auto& nodePath : paths) {
591 RawLightInfo info;
592 info.id = ++nextLightId;
593 info.path = nodePath;
594 info.name = nodePath.filename();
595 info.maxBrightness = std::nullopt;
596 size_t nameStart = info.name.rfind(":");
597 if (nameStart != std::string::npos) {
598 // Trim the name to color name
599 info.name = info.name.substr(nameStart + 1);
600 // Set InputLightClass flag for colors
601 const auto it = LIGHT_CLASSES.find(info.name);
602 if (it != LIGHT_CLASSES.end()) {
603 info.flags |= it->second;
604 }
605 }
606 // Scan the path for all the files
607 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
608 const auto& files = allFilesInPath(nodePath);
609 for (const auto& file : files) {
610 const auto it = LIGHT_CLASSES.find(file.filename().string());
611 if (it != LIGHT_CLASSES.end()) {
612 info.flags |= it->second;
613 // If the node has maximum brightness, read it
614 if (it->second == InputLightClass::MAX_BRIGHTNESS) {
615 std::string str;
616 if (base::ReadFileToString(file, &str)) {
617 info.maxBrightness = std::stoi(str);
618 }
619 }
620 }
621 }
622 lightInfos.insert_or_assign(info.id, info);
Chris Yee2b1e5c2021-03-10 22:45:12 -0800623 ALOGD("configureLightsLocked rawLightId %d name %s", info.id, info.name.c_str());
Chris Ye3fdbfef2021-01-06 18:45:18 -0800624 }
625 return !lightInfos.empty();
626}
627
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100628/**
629 * Get the capabilities for the current process.
630 * Crashes the system if unable to create / check / destroy the capabilities object.
631 */
632class Capabilities final {
633public:
634 explicit Capabilities() {
635 mCaps = cap_get_proc();
636 LOG_ALWAYS_FATAL_IF(mCaps == nullptr, "Could not get capabilities of the current process");
637 }
638
639 /**
640 * Check whether the current process has a specific capability
641 * in the set of effective capabilities.
642 * Return CAP_SET if the process has the requested capability
643 * Return CAP_CLEAR otherwise.
644 */
645 cap_flag_value_t checkEffectiveCapability(cap_value_t capability) {
646 cap_flag_value_t value;
647 const int result = cap_get_flag(mCaps, capability, CAP_EFFECTIVE, &value);
648 LOG_ALWAYS_FATAL_IF(result == -1, "Could not obtain the requested capability");
649 return value;
650 }
651
652 ~Capabilities() {
653 const int result = cap_free(mCaps);
654 LOG_ALWAYS_FATAL_IF(result == -1, "Could not release the capabilities structure");
655 }
656
657private:
658 cap_t mCaps;
659};
660
661static void ensureProcessCanBlockSuspend() {
662 Capabilities capabilities;
663 const bool canBlockSuspend =
664 capabilities.checkEffectiveCapability(CAP_BLOCK_SUSPEND) == CAP_SET;
665 LOG_ALWAYS_FATAL_IF(!canBlockSuspend,
666 "Input must be able to block suspend to properly process events");
667}
668
Michael Wrightd02c5b62014-02-10 15:10:22 -0800669// --- EventHub ---
670
Michael Wrightd02c5b62014-02-10 15:10:22 -0800671const int EventHub::EPOLL_MAX_EVENTS;
672
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700673EventHub::EventHub(void)
674 : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
675 mNextDeviceId(1),
676 mControllerNumbers(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800677 mNeedToSendFinishedDeviceScan(false),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700678 mNeedToReopenDevices(false),
679 mNeedToScanDevices(true),
680 mPendingEventCount(0),
681 mPendingEventIndex(0),
682 mPendingINotify(false) {
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100683 ensureProcessCanBlockSuspend();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800684
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800685 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800686 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800687
Michael Wright8e9a8562022-02-09 13:44:29 +0000688 mINotifyFd = inotify_init1(IN_CLOEXEC);
Usama Arifb27c8e62021-06-03 16:44:09 +0100689
690 std::error_code errorCode;
691 bool isDeviceInotifyAdded = false;
692 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
693 addDeviceInputInotify();
Philip Quinn39b81682019-01-09 22:20:39 -0800694 } else {
Usama Arifb27c8e62021-06-03 16:44:09 +0100695 addDeviceInotify();
696 isDeviceInotifyAdded = true;
697 if (errorCode) {
698 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
699 errorCode.message().c_str());
700 }
701 }
702
703 if (isV4lScanningEnabled() && !isDeviceInotifyAdded) {
704 addDeviceInotify();
705 } else {
Philip Quinn39b81682019-01-09 22:20:39 -0800706 ALOGI("Video device scanning disabled");
707 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800708
Siarhei Vishniakou2d0e9482019-09-24 12:52:47 +0100709 struct epoll_event eventItem = {};
710 eventItem.events = EPOLLIN | EPOLLWAKEUP;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700711 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800712 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800713 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
714
715 int wakeFds[2];
Michael Wright8e9a8562022-02-09 13:44:29 +0000716 result = pipe2(wakeFds, O_CLOEXEC);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800717 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
718
719 mWakeReadPipeFd = wakeFds[0];
720 mWakeWritePipeFd = wakeFds[1];
721
722 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
723 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700724 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800725
726 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
727 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700728 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800729
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700730 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800731 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
732 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700733 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800734}
735
736EventHub::~EventHub(void) {
737 closeAllDevicesLocked();
738
Michael Wrightd02c5b62014-02-10 15:10:22 -0800739 ::close(mEpollFd);
740 ::close(mINotifyFd);
741 ::close(mWakeReadPipeFd);
742 ::close(mWakeWritePipeFd);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800743}
744
Usama Arifb27c8e62021-06-03 16:44:09 +0100745/**
746 * On devices that don't have any input devices (like some development boards), the /dev/input
747 * directory will be absent. However, the user may still plug in an input device at a later time.
748 * Add watch for contents of /dev/input only when /dev/input appears.
749 */
750void EventHub::addDeviceInputInotify() {
751 mDeviceInputWd = inotify_add_watch(mINotifyFd, DEVICE_INPUT_PATH, IN_DELETE | IN_CREATE);
752 LOG_ALWAYS_FATAL_IF(mDeviceInputWd < 0, "Could not register INotify for %s: %s",
753 DEVICE_INPUT_PATH, strerror(errno));
754}
755
756void EventHub::addDeviceInotify() {
757 mDeviceWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
758 LOG_ALWAYS_FATAL_IF(mDeviceWd < 0, "Could not register INotify for %s: %s", DEVICE_PATH,
759 strerror(errno));
760}
761
Michael Wrightd02c5b62014-02-10 15:10:22 -0800762InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000763 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800764 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700765 return device != nullptr ? device->identifier : InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800766}
767
Chris Ye1b0c7342020-07-28 21:57:03 -0700768Flags<InputDeviceClass> EventHub::getDeviceClasses(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000769 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800770 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700771 return device != nullptr ? device->classes : Flags<InputDeviceClass>(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800772}
773
774int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000775 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800776 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700777 return device != nullptr ? device->controllerNumber : 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800778}
779
780void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
Chris Ye87143712020-11-10 05:05:58 +0000781 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800782 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700783 if (device != nullptr && device->configuration) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800784 *outConfiguration = *device->configuration;
785 } else {
786 outConfiguration->clear();
787 }
788}
789
790status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700791 RawAbsoluteAxisInfo* outAxisInfo) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800792 outAxisInfo->clear();
793
794 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000795 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800796
797 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700798 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800799 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700800 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
801 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
802 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800803 return -errno;
804 }
805
806 if (info.minimum != info.maximum) {
807 outAxisInfo->valid = true;
808 outAxisInfo->minValue = info.minimum;
809 outAxisInfo->maxValue = info.maximum;
810 outAxisInfo->flat = info.flat;
811 outAxisInfo->fuzz = info.fuzz;
812 outAxisInfo->resolution = info.resolution;
813 }
814 return OK;
815 }
816 }
817 return -1;
818}
819
820bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
821 if (axis >= 0 && axis <= REL_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000822 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800823 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700824 return device != nullptr ? device->relBitmask.test(axis) : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800825 }
826 return false;
827}
828
829bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
Chris Ye87143712020-11-10 05:05:58 +0000830 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800831
Chris Ye989bb932020-07-04 16:18:59 -0700832 Device* device = getDeviceLocked(deviceId);
833 return property >= 0 && property <= INPUT_PROP_MAX && device != nullptr
834 ? device->propBitmask.test(property)
835 : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800836}
837
Chris Yef59a2f42020-10-16 12:55:26 -0700838bool EventHub::hasMscEvent(int32_t deviceId, int mscEvent) const {
839 std::scoped_lock _l(mLock);
840
841 Device* device = getDeviceLocked(deviceId);
842 return mscEvent >= 0 && mscEvent <= MSC_MAX && device != nullptr
843 ? device->mscBitmask.test(mscEvent)
844 : false;
845}
846
Michael Wrightd02c5b62014-02-10 15:10:22 -0800847int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
848 if (scanCode >= 0 && scanCode <= KEY_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000849 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800850
851 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700852 if (device != nullptr && device->hasValidFd() && device->keyBitmask.test(scanCode)) {
853 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
854 return device->keyState.test(scanCode) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800855 }
856 }
857 }
858 return AKEY_STATE_UNKNOWN;
859}
860
861int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
Chris Ye87143712020-11-10 05:05:58 +0000862 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800863
864 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700865 if (device != nullptr && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800866 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800867 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode, &scanCodes);
868 if (scanCodes.size() != 0) {
Chris Ye66fbac32020-07-06 20:36:43 -0700869 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800870 for (size_t i = 0; i < scanCodes.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800871 int32_t sc = scanCodes[i];
Chris Ye66fbac32020-07-06 20:36:43 -0700872 if (sc >= 0 && sc <= KEY_MAX && device->keyState.test(sc)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800873 return AKEY_STATE_DOWN;
874 }
875 }
876 return AKEY_STATE_UP;
877 }
878 }
879 }
880 return AKEY_STATE_UNKNOWN;
881}
882
Philip Junker4af3b3d2021-12-14 10:36:55 +0100883int32_t EventHub::getKeyCodeForKeyLocation(int32_t deviceId, int32_t locationKeyCode) const {
884 std::scoped_lock _l(mLock);
885
886 Device* device = getDeviceLocked(deviceId);
887 if (device == nullptr || !device->hasValidFd() || device->keyMap.keyCharacterMap == nullptr ||
888 device->keyMap.keyLayoutMap == nullptr) {
889 return AKEYCODE_UNKNOWN;
890 }
891 std::vector<int32_t> scanCodes;
892 device->keyMap.keyLayoutMap->findScanCodesForKey(locationKeyCode, &scanCodes);
893 if (scanCodes.empty()) {
894 ALOGW("Failed to get key code for key location: no scan code maps to key code %d for input"
895 "device %d",
896 locationKeyCode, deviceId);
897 return AKEYCODE_UNKNOWN;
898 }
899 if (scanCodes.size() > 1) {
900 ALOGW("Multiple scan codes map to the same key code %d, returning only the first match",
901 locationKeyCode);
902 }
903 int32_t outKeyCode;
904 status_t mapKeyRes =
905 device->getKeyCharacterMap()->mapKey(scanCodes[0], 0 /*usageCode*/, &outKeyCode);
906 switch (mapKeyRes) {
907 case OK:
908 return outKeyCode;
909 case NAME_NOT_FOUND:
910 // key character map doesn't re-map this scanCode, hence the keyCode remains the same
911 return locationKeyCode;
912 default:
913 ALOGW("Failed to get key code for key location: Key character map returned error %s",
914 statusToString(mapKeyRes).c_str());
915 return AKEYCODE_UNKNOWN;
916 }
917}
918
Michael Wrightd02c5b62014-02-10 15:10:22 -0800919int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
920 if (sw >= 0 && sw <= SW_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000921 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800922
923 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700924 if (device != nullptr && device->hasValidFd() && device->swBitmask.test(sw)) {
925 if (device->readDeviceBitMask(EVIOCGSW(0), device->swState) >= 0) {
926 return device->swState.test(sw) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800927 }
928 }
929 }
930 return AKEY_STATE_UNKNOWN;
931}
932
933status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
934 *outValue = 0;
935
936 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000937 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800938
939 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700940 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800941 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700942 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
943 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
944 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800945 return -errno;
946 }
947
948 *outValue = info.value;
949 return OK;
950 }
951 }
952 return -1;
953}
954
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700955bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes, const int32_t* keyCodes,
956 uint8_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +0000957 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800958
959 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700960 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800961 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800962 for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) {
963 scanCodes.clear();
964
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700965 status_t err = device->keyMap.keyLayoutMap->findScanCodesForKey(keyCodes[codeIndex],
966 &scanCodes);
967 if (!err) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800968 // check the possible scan codes identified by the layout map against the
969 // map of codes actually emitted by the driver
970 for (size_t sc = 0; sc < scanCodes.size(); sc++) {
Chris Ye66fbac32020-07-06 20:36:43 -0700971 if (device->keyBitmask.test(scanCodes[sc])) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800972 outFlags[codeIndex] = 1;
973 break;
974 }
975 }
976 }
977 }
978 return true;
979 }
980 return false;
981}
982
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700983status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
984 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +0000985 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800986 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700987 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800988
Chris Ye66fbac32020-07-06 20:36:43 -0700989 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800990 // Check the key character map first.
Chris Ye3a1e4462020-08-12 10:13:15 -0700991 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
992 if (kcm) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800993 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
994 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700995 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800996 }
997 }
998
999 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001000 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -08001001 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001002 status = NO_ERROR;
1003 }
1004 }
1005
1006 if (status == NO_ERROR) {
Chris Ye3a1e4462020-08-12 10:13:15 -07001007 if (kcm) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001008 kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState);
1009 } else {
1010 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001011 }
1012 }
1013 }
1014
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001015 if (status != NO_ERROR) {
1016 *outKeycode = 0;
1017 *outFlags = 0;
1018 *outMetaState = metaState;
1019 }
1020
1021 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001022}
1023
1024status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
Chris Ye87143712020-11-10 05:05:58 +00001025 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026 Device* device = getDeviceLocked(deviceId);
1027
Chris Ye66fbac32020-07-06 20:36:43 -07001028 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001029 status_t err = device->keyMap.keyLayoutMap->mapAxis(scanCode, outAxisInfo);
1030 if (err == NO_ERROR) {
1031 return NO_ERROR;
1032 }
1033 }
1034
1035 return NAME_NOT_FOUND;
1036}
1037
Chris Yef59a2f42020-10-16 12:55:26 -07001038base::Result<std::pair<InputDeviceSensorType, int32_t>> EventHub::mapSensor(int32_t deviceId,
1039 int32_t absCode) {
1040 std::scoped_lock _l(mLock);
1041 Device* device = getDeviceLocked(deviceId);
1042
1043 if (device != nullptr && device->keyMap.haveKeyLayout()) {
1044 return device->keyMap.keyLayoutMap->mapSensor(absCode);
1045 }
1046 return Errorf("Device not found or device has no key layout.");
1047}
1048
Chris Yee2b1e5c2021-03-10 22:45:12 -08001049// Gets the battery info map from battery ID to RawBatteryInfo of the miscellaneous device
1050// associated with the device ID. Returns an empty map if no miscellaneous device found.
1051const std::unordered_map<int32_t, RawBatteryInfo>& EventHub::getBatteryInfoLocked(
1052 int32_t deviceId) const {
1053 static const std::unordered_map<int32_t, RawBatteryInfo> EMPTY_BATTERY_INFO = {};
1054 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001055 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001056 return EMPTY_BATTERY_INFO;
1057 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001058 return device->associatedDevice->batteryInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001059}
1060
1061const std::vector<int32_t> EventHub::getRawBatteryIds(int32_t deviceId) {
1062 std::scoped_lock _l(mLock);
1063 std::vector<int32_t> batteryIds;
1064
1065 for (const auto [id, info] : getBatteryInfoLocked(deviceId)) {
1066 batteryIds.push_back(id);
1067 }
1068
1069 return batteryIds;
1070}
1071
1072std::optional<RawBatteryInfo> EventHub::getRawBatteryInfo(int32_t deviceId, int32_t batteryId) {
1073 std::scoped_lock _l(mLock);
1074
1075 const auto infos = getBatteryInfoLocked(deviceId);
1076
1077 auto it = infos.find(batteryId);
1078 if (it != infos.end()) {
1079 return it->second;
1080 }
1081
1082 return std::nullopt;
1083}
1084
1085// Gets the light info map from light ID to RawLightInfo of the miscellaneous device associated
1086// with the deivice ID. Returns an empty map if no miscellaneous device found.
1087const std::unordered_map<int32_t, RawLightInfo>& EventHub::getLightInfoLocked(
1088 int32_t deviceId) const {
1089 static const std::unordered_map<int32_t, RawLightInfo> EMPTY_LIGHT_INFO = {};
1090 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001091 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001092 return EMPTY_LIGHT_INFO;
1093 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001094 return device->associatedDevice->lightInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001095}
1096
Chris Ye3fdbfef2021-01-06 18:45:18 -08001097const std::vector<int32_t> EventHub::getRawLightIds(int32_t deviceId) {
1098 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001099 std::vector<int32_t> lightIds;
1100
Chris Yee2b1e5c2021-03-10 22:45:12 -08001101 for (const auto [id, info] : getLightInfoLocked(deviceId)) {
1102 lightIds.push_back(id);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001103 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001104
Chris Ye3fdbfef2021-01-06 18:45:18 -08001105 return lightIds;
1106}
1107
1108std::optional<RawLightInfo> EventHub::getRawLightInfo(int32_t deviceId, int32_t lightId) {
1109 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001110
Chris Yee2b1e5c2021-03-10 22:45:12 -08001111 const auto infos = getLightInfoLocked(deviceId);
1112
1113 auto it = infos.find(lightId);
1114 if (it != infos.end()) {
1115 return it->second;
Chris Ye3fdbfef2021-01-06 18:45:18 -08001116 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001117
Chris Ye3fdbfef2021-01-06 18:45:18 -08001118 return std::nullopt;
1119}
1120
1121std::optional<int32_t> EventHub::getLightBrightness(int32_t deviceId, int32_t lightId) {
1122 std::scoped_lock _l(mLock);
1123
Chris Yee2b1e5c2021-03-10 22:45:12 -08001124 const auto infos = getLightInfoLocked(deviceId);
1125 auto it = infos.find(lightId);
1126 if (it == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001127 return std::nullopt;
1128 }
1129 std::string buffer;
1130 if (!base::ReadFileToString(it->second.path / LIGHT_NODES.at(InputLightClass::BRIGHTNESS),
1131 &buffer)) {
1132 return std::nullopt;
1133 }
1134 return std::stoi(buffer);
1135}
1136
1137std::optional<std::unordered_map<LightColor, int32_t>> EventHub::getLightIntensities(
1138 int32_t deviceId, int32_t lightId) {
1139 std::scoped_lock _l(mLock);
1140
Chris Yee2b1e5c2021-03-10 22:45:12 -08001141 const auto infos = getLightInfoLocked(deviceId);
1142 auto lightIt = infos.find(lightId);
1143 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001144 return std::nullopt;
1145 }
1146
1147 auto ret =
1148 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1149
1150 if (!ret.has_value()) {
1151 return std::nullopt;
1152 }
1153 std::array<LightColor, COLOR_NUM> colors = ret.value();
1154
1155 std::string intensityStr;
1156 if (!base::ReadFileToString(lightIt->second.path /
1157 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY),
1158 &intensityStr)) {
1159 return std::nullopt;
1160 }
1161
1162 // Intensity node outputs 3 color values
1163 std::regex intensityPattern("([0-9]+)\\s([0-9]+)\\s([0-9]+)[\\n]");
1164 std::smatch results;
1165
1166 if (!std::regex_match(intensityStr, results, intensityPattern)) {
1167 return std::nullopt;
1168 }
1169 std::unordered_map<LightColor, int32_t> intensities;
1170 for (size_t i = 1; i < results.size(); i++) {
1171 int value = std::stoi(results[i].str());
1172 intensities.emplace(colors[i - 1], value);
1173 }
1174 return intensities;
1175}
1176
1177void EventHub::setLightBrightness(int32_t deviceId, int32_t lightId, int32_t brightness) {
1178 std::scoped_lock _l(mLock);
1179
Chris Yee2b1e5c2021-03-10 22:45:12 -08001180 const auto infos = getLightInfoLocked(deviceId);
1181 auto lightIt = infos.find(lightId);
1182 if (lightIt == infos.end()) {
1183 ALOGE("%s lightId %d not found ", __func__, lightId);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001184 return;
1185 }
1186
1187 if (!base::WriteStringToFile(std::to_string(brightness),
1188 lightIt->second.path /
1189 LIGHT_NODES.at(InputLightClass::BRIGHTNESS))) {
1190 ALOGE("Can not write to file, error: %s", strerror(errno));
1191 }
1192}
1193
1194void EventHub::setLightIntensities(int32_t deviceId, int32_t lightId,
1195 std::unordered_map<LightColor, int32_t> intensities) {
1196 std::scoped_lock _l(mLock);
1197
Chris Yee2b1e5c2021-03-10 22:45:12 -08001198 const auto infos = getLightInfoLocked(deviceId);
1199 auto lightIt = infos.find(lightId);
1200 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001201 ALOGE("Light Id %d does not exist.", lightId);
1202 return;
1203 }
1204
1205 auto ret =
1206 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1207
1208 if (!ret.has_value()) {
1209 return;
1210 }
1211 std::array<LightColor, COLOR_NUM> colors = ret.value();
1212
1213 std::string rgbStr;
1214 for (size_t i = 0; i < COLOR_NUM; i++) {
1215 auto it = intensities.find(colors[i]);
1216 if (it != intensities.end()) {
1217 rgbStr += std::to_string(it->second);
1218 // Insert space between colors
1219 if (i < COLOR_NUM - 1) {
1220 rgbStr += " ";
1221 }
1222 }
1223 }
1224 // Append new line
1225 rgbStr += "\n";
1226
1227 if (!base::WriteStringToFile(rgbStr,
1228 lightIt->second.path /
1229 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY))) {
1230 ALOGE("Can not write to file, error: %s", strerror(errno));
1231 }
1232}
1233
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001234void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Chris Ye87143712020-11-10 05:05:58 +00001235 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001236
1237 mExcludedDevices = devices;
1238}
1239
1240bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
Chris Ye87143712020-11-10 05:05:58 +00001241 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001242 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001243 if (device != nullptr && scanCode >= 0 && scanCode <= KEY_MAX) {
1244 return device->keyBitmask.test(scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001245 }
1246 return false;
1247}
1248
Arthur Hungcb40a002021-08-03 14:31:01 +00001249bool EventHub::hasKeyCode(int32_t deviceId, int32_t keyCode) const {
1250 std::scoped_lock _l(mLock);
1251 Device* device = getDeviceLocked(deviceId);
1252 if (device != nullptr) {
1253 return device->hasKeycodeLocked(keyCode);
1254 }
1255 return false;
1256}
1257
Michael Wrightd02c5b62014-02-10 15:10:22 -08001258bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
Chris Ye87143712020-11-10 05:05:58 +00001259 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001260 Device* device = getDeviceLocked(deviceId);
1261 int32_t sc;
Chris Ye989bb932020-07-04 16:18:59 -07001262 if (device != nullptr && device->mapLed(led, &sc) == NO_ERROR) {
Chris Ye66fbac32020-07-06 20:36:43 -07001263 return device->ledBitmask.test(sc);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001264 }
1265 return false;
1266}
1267
1268void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
Chris Ye87143712020-11-10 05:05:58 +00001269 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001270 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -07001271 if (device != nullptr && device->hasValidFd()) {
1272 device->setLedStateLocked(led, on);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001273 }
1274}
1275
1276void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001277 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001278 outVirtualKeys.clear();
1279
Chris Ye87143712020-11-10 05:05:58 +00001280 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001281 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001282 if (device != nullptr && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001283 const std::vector<VirtualKeyDefinition> virtualKeys =
1284 device->virtualKeyMap->getVirtualKeys();
1285 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001286 }
1287}
1288
Chris Ye3a1e4462020-08-12 10:13:15 -07001289const std::shared_ptr<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001290 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001291 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001292 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001293 return device->getKeyCharacterMap();
1294 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001295 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001296}
1297
Chris Ye3a1e4462020-08-12 10:13:15 -07001298bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, std::shared_ptr<KeyCharacterMap> map) {
Chris Ye87143712020-11-10 05:05:58 +00001299 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001300 Device* device = getDeviceLocked(deviceId);
Philip Junker90bc9492021-12-10 18:39:42 +01001301 if (device == nullptr || map == nullptr || device->keyMap.keyCharacterMap == nullptr) {
1302 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001303 }
Philip Junker90bc9492021-12-10 18:39:42 +01001304 device->keyMap.keyCharacterMap->combine(*map);
1305 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001306}
1307
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001308static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
1309 std::string rawDescriptor;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001310 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001311 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001312 if (!identifier.uniqueId.empty()) {
1313 rawDescriptor += "uniqueId:";
1314 rawDescriptor += identifier.uniqueId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001315 } else if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001316 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001317 }
1318
1319 if (identifier.vendor == 0 && identifier.product == 0) {
1320 // If we don't know the vendor and product id, then the device is probably
1321 // built-in so we need to rely on other information to uniquely identify
1322 // the input device. Usually we try to avoid relying on the device name or
1323 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001324 if (!identifier.name.empty()) {
1325 rawDescriptor += "name:";
1326 rawDescriptor += identifier.name;
1327 } else if (!identifier.location.empty()) {
1328 rawDescriptor += "location:";
1329 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001330 }
1331 }
1332 identifier.descriptor = sha1(rawDescriptor);
1333 return rawDescriptor;
1334}
1335
1336void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
1337 // Compute a device descriptor that uniquely identifies the device.
1338 // The descriptor is assumed to be a stable identifier. Its value should not
1339 // change between reboots, reconnections, firmware updates or new releases
1340 // of Android. In practice we sometimes get devices that cannot be uniquely
1341 // identified. In this case we enforce uniqueness between connected devices.
1342 // Ideally, we also want the descriptor to be short and relatively opaque.
1343
1344 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001345 std::string rawDescriptor = generateDescriptor(identifier);
1346 if (identifier.uniqueId.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001347 // If it didn't have a unique id check for conflicts and enforce
1348 // uniqueness if necessary.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001349 while (getDeviceByDescriptorLocked(identifier.descriptor) != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001350 identifier.nonce++;
1351 rawDescriptor = generateDescriptor(identifier);
1352 }
1353 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001354 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001355 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001356}
1357
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001358void EventHub::vibrate(int32_t deviceId, const VibrationElement& element) {
Chris Ye87143712020-11-10 05:05:58 +00001359 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001360 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001361 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001362 ff_effect effect;
1363 memset(&effect, 0, sizeof(effect));
1364 effect.type = FF_RUMBLE;
1365 effect.id = device->ffEffectId;
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001366 // evdev FF_RUMBLE effect only supports two channels of vibration.
Chris Ye6393a262020-08-04 19:41:36 -07001367 effect.u.rumble.strong_magnitude = element.getMagnitude(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1368 effect.u.rumble.weak_magnitude = element.getMagnitude(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001369 effect.replay.length = element.duration.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001370 effect.replay.delay = 0;
1371 if (ioctl(device->fd, EVIOCSFF, &effect)) {
1372 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001373 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001374 return;
1375 }
1376 device->ffEffectId = effect.id;
1377
1378 struct input_event ev;
1379 ev.time.tv_sec = 0;
1380 ev.time.tv_usec = 0;
1381 ev.type = EV_FF;
1382 ev.code = device->ffEffectId;
1383 ev.value = 1;
1384 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1385 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001386 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001387 return;
1388 }
1389 device->ffEffectPlaying = true;
1390 }
1391}
1392
1393void EventHub::cancelVibrate(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001394 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001395 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001396 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001397 if (device->ffEffectPlaying) {
1398 device->ffEffectPlaying = false;
1399
1400 struct input_event ev;
1401 ev.time.tv_sec = 0;
1402 ev.time.tv_usec = 0;
1403 ev.type = EV_FF;
1404 ev.code = device->ffEffectId;
1405 ev.value = 0;
1406 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1407 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001408 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001409 return;
1410 }
1411 }
1412 }
1413}
1414
Chris Ye87143712020-11-10 05:05:58 +00001415std::vector<int32_t> EventHub::getVibratorIds(int32_t deviceId) {
1416 std::scoped_lock _l(mLock);
1417 std::vector<int32_t> vibrators;
1418 Device* device = getDeviceLocked(deviceId);
1419 if (device != nullptr && device->hasValidFd() &&
1420 device->classes.test(InputDeviceClass::VIBRATOR)) {
1421 vibrators.push_back(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1422 vibrators.push_back(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
1423 }
1424 return vibrators;
1425}
1426
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001427EventHub::Device* EventHub::getDeviceByDescriptorLocked(const std::string& descriptor) const {
Chris Ye989bb932020-07-04 16:18:59 -07001428 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001429 if (descriptor == device->identifier.descriptor) {
Chris Ye989bb932020-07-04 16:18:59 -07001430 return device.get();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001431 }
1432 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001433 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001434}
1435
1436EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001437 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001438 deviceId = mBuiltInKeyboardId;
1439 }
Chris Ye989bb932020-07-04 16:18:59 -07001440 const auto& it = mDevices.find(deviceId);
1441 return it != mDevices.end() ? it->second.get() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001442}
1443
Chris Ye8594e192020-07-14 10:34:06 -07001444EventHub::Device* EventHub::getDeviceByPathLocked(const std::string& devicePath) const {
Chris Ye989bb932020-07-04 16:18:59 -07001445 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001446 if (device->path == devicePath) {
Chris Ye989bb932020-07-04 16:18:59 -07001447 return device.get();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001448 }
1449 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001450 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001451}
1452
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001453/**
1454 * The file descriptor could be either input device, or a video device (associated with a
1455 * specific input device). Check both cases here, and return the device that this event
1456 * belongs to. Caller can compare the fd's once more to determine event type.
1457 * Looks through all input devices, and only attached video devices. Unattached video
1458 * devices are ignored.
1459 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001460EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
Chris Ye989bb932020-07-04 16:18:59 -07001461 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001462 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001463 // This is an input device event
Chris Ye989bb932020-07-04 16:18:59 -07001464 return device.get();
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001465 }
1466 if (device->videoDevice && device->videoDevice->getFd() == fd) {
1467 // This is a video device event
Chris Ye989bb932020-07-04 16:18:59 -07001468 return device.get();
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001469 }
1470 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001471 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
1472 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001473 return nullptr;
1474}
1475
Chris Yee2b1e5c2021-03-10 22:45:12 -08001476std::optional<int32_t> EventHub::getBatteryCapacity(int32_t deviceId, int32_t batteryId) const {
Kim Low03ea0352020-11-06 12:45:07 -08001477 std::scoped_lock _l(mLock);
Kim Low03ea0352020-11-06 12:45:07 -08001478
Chris Yee2b1e5c2021-03-10 22:45:12 -08001479 const auto infos = getBatteryInfoLocked(deviceId);
1480 auto it = infos.find(batteryId);
1481 if (it == infos.end()) {
Kim Low03ea0352020-11-06 12:45:07 -08001482 return std::nullopt;
1483 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001484 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001485
1486 // Some devices report battery capacity as an integer through the "capacity" file
Chris Yee2b1e5c2021-03-10 22:45:12 -08001487 if (base::ReadFileToString(it->second.path / BATTERY_NODES.at(InputBatteryClass::CAPACITY),
1488 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001489 return std::stoi(base::Trim(buffer));
Kim Low03ea0352020-11-06 12:45:07 -08001490 }
1491
1492 // Other devices report capacity as an enum value POWER_SUPPLY_CAPACITY_LEVEL_XXX
1493 // These values are taken from kernel source code include/linux/power_supply.h
Chris Yee2b1e5c2021-03-10 22:45:12 -08001494 if (base::ReadFileToString(it->second.path /
1495 BATTERY_NODES.at(InputBatteryClass::CAPACITY_LEVEL),
1496 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001497 // Remove any white space such as trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001498 const auto levelIt = BATTERY_LEVEL.find(base::Trim(buffer));
1499 if (levelIt != BATTERY_LEVEL.end()) {
1500 return levelIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001501 }
1502 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001503
Kim Low03ea0352020-11-06 12:45:07 -08001504 return std::nullopt;
1505}
1506
Chris Yee2b1e5c2021-03-10 22:45:12 -08001507std::optional<int32_t> EventHub::getBatteryStatus(int32_t deviceId, int32_t batteryId) const {
Kim Low03ea0352020-11-06 12:45:07 -08001508 std::scoped_lock _l(mLock);
Chris Yee2b1e5c2021-03-10 22:45:12 -08001509 const auto infos = getBatteryInfoLocked(deviceId);
1510 auto it = infos.find(batteryId);
1511 if (it == infos.end()) {
Kim Low03ea0352020-11-06 12:45:07 -08001512 return std::nullopt;
1513 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001514 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001515
Chris Yee2b1e5c2021-03-10 22:45:12 -08001516 if (!base::ReadFileToString(it->second.path / BATTERY_NODES.at(InputBatteryClass::STATUS),
1517 &buffer)) {
Kim Low03ea0352020-11-06 12:45:07 -08001518 ALOGE("Failed to read sysfs battery info: %s", strerror(errno));
1519 return std::nullopt;
1520 }
1521
Chris Yed1936772021-02-22 10:30:40 -08001522 // Remove white space like trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001523 const auto statusIt = BATTERY_STATUS.find(base::Trim(buffer));
1524 if (statusIt != BATTERY_STATUS.end()) {
1525 return statusIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001526 }
1527
1528 return std::nullopt;
1529}
1530
Michael Wrightd02c5b62014-02-10 15:10:22 -08001531size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
1532 ALOG_ASSERT(bufferSize >= 1);
1533
Chris Ye87143712020-11-10 05:05:58 +00001534 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001535
1536 struct input_event readBuffer[bufferSize];
1537
1538 RawEvent* event = buffer;
1539 size_t capacity = bufferSize;
1540 bool awoken = false;
1541 for (;;) {
1542 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
1543
1544 // Reopen input devices if needed.
1545 if (mNeedToReopenDevices) {
1546 mNeedToReopenDevices = false;
1547
1548 ALOGI("Reopening all input devices due to a configuration change.");
1549
1550 closeAllDevicesLocked();
1551 mNeedToScanDevices = true;
1552 break; // return to the caller before we actually rescan
1553 }
1554
1555 // Report any devices that had last been added/removed.
Chris Ye989bb932020-07-04 16:18:59 -07001556 for (auto it = mClosingDevices.begin(); it != mClosingDevices.end();) {
1557 std::unique_ptr<Device> device = std::move(*it);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001558 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001559 event->when = now;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001560 event->deviceId = (device->id == mBuiltInKeyboardId)
1561 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
1562 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001563 event->type = DEVICE_REMOVED;
1564 event += 1;
Chris Ye989bb932020-07-04 16:18:59 -07001565 it = mClosingDevices.erase(it);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001566 mNeedToSendFinishedDeviceScan = true;
1567 if (--capacity == 0) {
1568 break;
1569 }
1570 }
1571
1572 if (mNeedToScanDevices) {
1573 mNeedToScanDevices = false;
1574 scanDevicesLocked();
1575 mNeedToSendFinishedDeviceScan = true;
1576 }
1577
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001578 while (!mOpeningDevices.empty()) {
1579 std::unique_ptr<Device> device = std::move(*mOpeningDevices.rbegin());
1580 mOpeningDevices.pop_back();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001581 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001582 event->when = now;
1583 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1584 event->type = DEVICE_ADDED;
1585 event += 1;
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001586
1587 // Try to find a matching video device by comparing device names
1588 for (auto it = mUnattachedVideoDevices.begin(); it != mUnattachedVideoDevices.end();
1589 it++) {
1590 std::unique_ptr<TouchVideoDevice>& videoDevice = *it;
Chris Yed3fef462021-03-07 17:10:08 -08001591 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001592 // videoDevice was transferred to 'device'
1593 it = mUnattachedVideoDevices.erase(it);
1594 break;
1595 }
1596 }
1597
1598 auto [dev_it, inserted] = mDevices.insert_or_assign(device->id, std::move(device));
1599 if (!inserted) {
Chris Ye989bb932020-07-04 16:18:59 -07001600 ALOGW("Device id %d exists, replaced.", device->id);
1601 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001602 mNeedToSendFinishedDeviceScan = true;
1603 if (--capacity == 0) {
1604 break;
1605 }
1606 }
1607
1608 if (mNeedToSendFinishedDeviceScan) {
1609 mNeedToSendFinishedDeviceScan = false;
1610 event->when = now;
1611 event->type = FINISHED_DEVICE_SCAN;
1612 event += 1;
1613 if (--capacity == 0) {
1614 break;
1615 }
1616 }
1617
1618 // Grab the next input event.
1619 bool deviceChanged = false;
1620 while (mPendingEventIndex < mPendingEventCount) {
1621 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001622 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001623 if (eventItem.events & EPOLLIN) {
1624 mPendingINotify = true;
1625 } else {
1626 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
1627 }
1628 continue;
1629 }
1630
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001631 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001632 if (eventItem.events & EPOLLIN) {
1633 ALOGV("awoken after wake()");
1634 awoken = true;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001635 char wakeReadBuffer[16];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001636 ssize_t nRead;
1637 do {
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001638 nRead = read(mWakeReadPipeFd, wakeReadBuffer, sizeof(wakeReadBuffer));
1639 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(wakeReadBuffer));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001640 } else {
1641 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001642 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001643 }
1644 continue;
1645 }
1646
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001647 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Chris Ye989bb932020-07-04 16:18:59 -07001648 if (device == nullptr) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001649 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
1650 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001651 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001652 continue;
1653 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001654 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
1655 if (eventItem.events & EPOLLIN) {
1656 size_t numFrames = device->videoDevice->readAndQueueFrames();
1657 if (numFrames == 0) {
1658 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001659 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001660 }
1661 } else if (eventItem.events & EPOLLHUP) {
1662 // TODO(b/121395353) - consider adding EPOLLRDHUP
1663 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001664 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001665 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1666 device->videoDevice = nullptr;
1667 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001668 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1669 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001670 ALOG_ASSERT(!DEBUG);
1671 }
1672 continue;
1673 }
1674 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -08001675 if (eventItem.events & EPOLLIN) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001676 int32_t readSize =
1677 read(device->fd, readBuffer, sizeof(struct input_event) * capacity);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001678 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
1679 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -07001680 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001681 " bufferSize: %zu capacity: %zu errno: %d)\n",
1682 device->fd, readSize, bufferSize, capacity, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001683 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001684 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001685 } else if (readSize < 0) {
1686 if (errno != EAGAIN && errno != EINTR) {
1687 ALOGW("could not get event (errno=%d)", errno);
1688 }
1689 } else if ((readSize % sizeof(struct input_event)) != 0) {
1690 ALOGE("could not get event (wrong size: %d)", readSize);
1691 } else {
1692 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1693
1694 size_t count = size_t(readSize) / sizeof(struct input_event);
1695 for (size_t i = 0; i < count; i++) {
1696 struct input_event& iev = readBuffer[i];
Siarhei Vishniakou592bac22018-11-08 19:42:38 -08001697 event->when = processEventTimestamp(iev);
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001698 event->readTime = systemTime(SYSTEM_TIME_MONOTONIC);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001699 event->deviceId = deviceId;
1700 event->type = iev.type;
1701 event->code = iev.code;
1702 event->value = iev.value;
1703 event += 1;
1704 capacity -= 1;
1705 }
1706 if (capacity == 0) {
1707 // The result buffer is full. Reset the pending event index
1708 // so we will try to read the device again on the next iteration.
1709 mPendingEventIndex -= 1;
1710 break;
1711 }
1712 }
1713 } else if (eventItem.events & EPOLLHUP) {
1714 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001715 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001716 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001717 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001718 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001719 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1720 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001721 }
1722 }
1723
1724 // readNotify() will modify the list of devices so this must be done after
1725 // processing all other events to ensure that we read all remaining events
1726 // before closing the devices.
1727 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
1728 mPendingINotify = false;
1729 readNotifyLocked();
1730 deviceChanged = true;
1731 }
1732
1733 // Report added or removed devices immediately.
1734 if (deviceChanged) {
1735 continue;
1736 }
1737
1738 // Return now if we have collected any events or if we were explicitly awoken.
1739 if (event != buffer || awoken) {
1740 break;
1741 }
1742
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001743 // Poll for events.
1744 // When a device driver has pending (unread) events, it acquires
1745 // a kernel wake lock. Once the last pending event has been read, the device
1746 // driver will release the kernel wake lock, but the epoll will hold the wakelock,
1747 // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
1748 // is called again for the same fd that produced the event.
1749 // Thus the system can only sleep if there are no events pending or
1750 // currently being processed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001751 //
1752 // The timeout is advisory only. If the device is asleep, it will not wake just to
1753 // service the timeout.
1754 mPendingEventIndex = 0;
1755
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001756 mLock.unlock(); // release lock before poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001757
1758 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1759
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001760 mLock.lock(); // reacquire lock after poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001761
1762 if (pollResult == 0) {
1763 // Timed out.
1764 mPendingEventCount = 0;
1765 break;
1766 }
1767
1768 if (pollResult < 0) {
1769 // An error occurred.
1770 mPendingEventCount = 0;
1771
1772 // Sleep after errors to avoid locking up the system.
1773 // Hopefully the error is transient.
1774 if (errno != EINTR) {
1775 ALOGW("poll failed (errno=%d)\n", errno);
1776 usleep(100000);
1777 }
1778 } else {
1779 // Some events occurred.
1780 mPendingEventCount = size_t(pollResult);
1781 }
1782 }
1783
1784 // All done, return the number of events we read.
1785 return event - buffer;
1786}
1787
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001788std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001789 std::scoped_lock _l(mLock);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001790
1791 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001792 if (device == nullptr || !device->videoDevice) {
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001793 return {};
1794 }
1795 return device->videoDevice->consumeFrames();
1796}
1797
Michael Wrightd02c5b62014-02-10 15:10:22 -08001798void EventHub::wake() {
1799 ALOGV("wake() called");
1800
1801 ssize_t nWrite;
1802 do {
1803 nWrite = write(mWakeWritePipeFd, "W", 1);
1804 } while (nWrite == -1 && errno == EINTR);
1805
1806 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001807 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001808 }
1809}
1810
1811void EventHub::scanDevicesLocked() {
Usama Arifb27c8e62021-06-03 16:44:09 +01001812 status_t result;
1813 std::error_code errorCode;
1814
1815 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
1816 result = scanDirLocked(DEVICE_INPUT_PATH);
1817 if (result < 0) {
1818 ALOGE("scan dir failed for %s", DEVICE_INPUT_PATH);
1819 }
1820 } else {
1821 if (errorCode) {
1822 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
1823 errorCode.message().c_str());
1824 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001825 }
Philip Quinn39b81682019-01-09 22:20:39 -08001826 if (isV4lScanningEnabled()) {
Usama Arifb27c8e62021-06-03 16:44:09 +01001827 result = scanVideoDirLocked(DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08001828 if (result != OK) {
Usama Arifb27c8e62021-06-03 16:44:09 +01001829 ALOGE("scan video dir failed for %s", DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08001830 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001831 }
Chris Ye989bb932020-07-04 16:18:59 -07001832 if (mDevices.find(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) == mDevices.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001833 createVirtualKeyboardLocked();
1834 }
1835}
1836
1837// ----------------------------------------------------------------------------
1838
Michael Wrightd02c5b62014-02-10 15:10:22 -08001839static const int32_t GAMEPAD_KEYCODES[] = {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001840 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C, //
1841 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z, //
1842 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1, //
1843 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2, //
1844 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR, //
1845 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE, //
Michael Wrightd02c5b62014-02-10 15:10:22 -08001846};
1847
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001848status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001849 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001850 struct epoll_event eventItem = {};
1851 eventItem.events = EPOLLIN | EPOLLWAKEUP;
1852 eventItem.data.fd = fd;
1853 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1854 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001855 return -errno;
1856 }
1857 return OK;
1858}
1859
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001860status_t EventHub::unregisterFdFromEpoll(int fd) {
1861 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
1862 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
1863 return -errno;
1864 }
1865 return OK;
1866}
1867
Chris Ye989bb932020-07-04 16:18:59 -07001868status_t EventHub::registerDeviceForEpollLocked(Device& device) {
1869 status_t result = registerFdForEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001870 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07001871 ALOGE("Could not add input device fd to epoll for device %" PRId32, device.id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001872 return result;
1873 }
Chris Ye989bb932020-07-04 16:18:59 -07001874 if (device.videoDevice) {
1875 registerVideoDeviceForEpollLocked(*device.videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001876 }
1877 return result;
1878}
1879
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001880void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
1881 status_t result = registerFdForEpoll(videoDevice.getFd());
1882 if (result != OK) {
1883 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
1884 }
1885}
1886
Chris Ye989bb932020-07-04 16:18:59 -07001887status_t EventHub::unregisterDeviceFromEpollLocked(Device& device) {
1888 if (device.hasValidFd()) {
1889 status_t result = unregisterFdFromEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001890 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07001891 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device.id);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001892 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001893 }
1894 }
Chris Ye989bb932020-07-04 16:18:59 -07001895 if (device.videoDevice) {
1896 unregisterVideoDeviceFromEpollLocked(*device.videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001897 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001898 return OK;
1899}
1900
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001901void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
1902 if (videoDevice.hasValidFd()) {
1903 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
1904 if (result != OK) {
1905 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001906 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001907 }
1908 }
1909}
1910
Chris Yed3fef462021-03-07 17:10:08 -08001911void EventHub::reportDeviceAddedForStatisticsLocked(const InputDeviceIdentifier& identifier,
1912 Flags<InputDeviceClass> classes) {
Chris Ye657c2f02021-05-25 16:24:37 -07001913 SHA256_CTX ctx;
1914 SHA256_Init(&ctx);
1915 SHA256_Update(&ctx, reinterpret_cast<const uint8_t*>(identifier.uniqueId.c_str()),
1916 identifier.uniqueId.size());
1917 std::array<uint8_t, SHA256_DIGEST_LENGTH> digest;
1918 SHA256_Final(digest.data(), &ctx);
1919
1920 std::string obfuscatedId;
1921 for (size_t i = 0; i < OBFUSCATED_LENGTH; i++) {
1922 obfuscatedId += StringPrintf("%02x", digest[i]);
1923 }
1924
Chris Yed3fef462021-03-07 17:10:08 -08001925 android::util::stats_write(android::util::INPUTDEVICE_REGISTERED, identifier.name.c_str(),
1926 identifier.vendor, identifier.product, identifier.version,
Chris Ye657c2f02021-05-25 16:24:37 -07001927 identifier.bus, obfuscatedId.c_str(), classes.get());
Chris Yed3fef462021-03-07 17:10:08 -08001928}
1929
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00001930void EventHub::openDeviceLocked(const std::string& devicePath) {
1931 // If an input device happens to register around the time when EventHub's constructor runs, it
1932 // is possible that the same input event node (for example, /dev/input/event3) will be noticed
1933 // in both 'inotify' callback and also in the 'scanDirLocked' pass. To prevent duplicate devices
1934 // from getting registered, ensure that this path is not already covered by an existing device.
1935 for (const auto& [deviceId, device] : mDevices) {
1936 if (device->path == devicePath) {
1937 return; // device was already registered
1938 }
1939 }
1940
Michael Wrightd02c5b62014-02-10 15:10:22 -08001941 char buffer[80];
1942
Chris Ye8594e192020-07-14 10:34:06 -07001943 ALOGV("Opening device: %s", devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001944
Chris Ye8594e192020-07-14 10:34:06 -07001945 int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001946 if (fd < 0) {
Chris Ye8594e192020-07-14 10:34:06 -07001947 ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00001948 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001949 }
1950
1951 InputDeviceIdentifier identifier;
1952
1953 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001954 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Chris Ye8594e192020-07-14 10:34:06 -07001955 ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001956 } else {
1957 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001958 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001959 }
1960
1961 // Check to see if the device is on our excluded list
1962 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001963 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001964 if (identifier.name == item) {
Chris Ye8594e192020-07-14 10:34:06 -07001965 ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001966 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00001967 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001968 }
1969 }
1970
1971 // Get device driver version.
1972 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001973 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Chris Ye8594e192020-07-14 10:34:06 -07001974 ALOGE("could not get driver version for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001975 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00001976 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001977 }
1978
1979 // Get device identifier.
1980 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001981 if (ioctl(fd, EVIOCGID, &inputId)) {
Chris Ye8594e192020-07-14 10:34:06 -07001982 ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001983 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00001984 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001985 }
1986 identifier.bus = inputId.bustype;
1987 identifier.product = inputId.product;
1988 identifier.vendor = inputId.vendor;
1989 identifier.version = inputId.version;
1990
1991 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001992 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
1993 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001994 } else {
1995 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001996 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001997 }
1998
1999 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002000 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
2001 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002002 } else {
2003 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002004 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002005 }
2006
2007 // Fill in the descriptor.
2008 assignDescriptorLocked(identifier);
2009
Michael Wrightd02c5b62014-02-10 15:10:22 -08002010 // Allocate device. (The device object takes ownership of the fd at this point.)
2011 int32_t deviceId = mNextDeviceId++;
Chris Ye989bb932020-07-04 16:18:59 -07002012 std::unique_ptr<Device> device = std::make_unique<Device>(fd, deviceId, devicePath, identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002013
Chris Ye8594e192020-07-14 10:34:06 -07002014 ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002015 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002016 " vendor %04x\n"
2017 " product %04x\n"
2018 " version %04x\n",
2019 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002020 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
2021 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
2022 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
2023 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002024 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
2025 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002026
2027 // Load the configuration file for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002028 device->loadConfigurationLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002029
Chris Yee2b1e5c2021-03-10 22:45:12 -08002030 bool hasBattery = false;
2031 bool hasLights = false;
2032 // Check the sysfs root path
2033 std::optional<std::filesystem::path> sysfsRootPath = getSysfsRootPath(devicePath.c_str());
2034 if (sysfsRootPath.has_value()) {
Chris Ye1dd2e5c2021-04-04 23:12:41 -07002035 std::shared_ptr<AssociatedDevice> associatedDevice;
2036 for (const auto& [id, dev] : mDevices) {
2037 if (device->identifier.descriptor == dev->identifier.descriptor &&
2038 !dev->associatedDevice) {
2039 associatedDevice = dev->associatedDevice;
2040 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08002041 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07002042 if (!associatedDevice) {
2043 associatedDevice = std::make_shared<AssociatedDevice>(sysfsRootPath.value());
2044 }
2045 hasBattery = associatedDevice->configureBatteryLocked();
2046 hasLights = associatedDevice->configureLightsLocked();
Chris Yee2b1e5c2021-03-10 22:45:12 -08002047
Chris Ye1dd2e5c2021-04-04 23:12:41 -07002048 device->associatedDevice = associatedDevice;
Chris Yee2b1e5c2021-03-10 22:45:12 -08002049 }
Chris Ye3fdbfef2021-01-06 18:45:18 -08002050
Michael Wrightd02c5b62014-02-10 15:10:22 -08002051 // Figure out the kinds of events the device reports.
Chris Ye66fbac32020-07-06 20:36:43 -07002052 device->readDeviceBitMask(EVIOCGBIT(EV_KEY, 0), device->keyBitmask);
2053 device->readDeviceBitMask(EVIOCGBIT(EV_ABS, 0), device->absBitmask);
2054 device->readDeviceBitMask(EVIOCGBIT(EV_REL, 0), device->relBitmask);
2055 device->readDeviceBitMask(EVIOCGBIT(EV_SW, 0), device->swBitmask);
2056 device->readDeviceBitMask(EVIOCGBIT(EV_LED, 0), device->ledBitmask);
2057 device->readDeviceBitMask(EVIOCGBIT(EV_FF, 0), device->ffBitmask);
Chris Yef59a2f42020-10-16 12:55:26 -07002058 device->readDeviceBitMask(EVIOCGBIT(EV_MSC, 0), device->mscBitmask);
Chris Ye66fbac32020-07-06 20:36:43 -07002059 device->readDeviceBitMask(EVIOCGPROP(0), device->propBitmask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002060
2061 // See if this is a keyboard. Ignore everything in the button range except for
2062 // joystick and gamepad buttons which are handled like keyboards for the most part.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002063 bool haveKeyboardKeys =
Chris Ye66fbac32020-07-06 20:36:43 -07002064 device->keyBitmask.any(0, BTN_MISC) || device->keyBitmask.any(BTN_WHEEL, KEY_MAX + 1);
2065 bool haveGamepadButtons = device->keyBitmask.any(BTN_MISC, BTN_MOUSE) ||
2066 device->keyBitmask.any(BTN_JOYSTICK, BTN_DIGI);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002067 if (haveKeyboardKeys || haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002068 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002069 }
2070
2071 // See if this is a cursor device such as a trackball or mouse.
Chris Ye66fbac32020-07-06 20:36:43 -07002072 if (device->keyBitmask.test(BTN_MOUSE) && device->relBitmask.test(REL_X) &&
2073 device->relBitmask.test(REL_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002074 device->classes |= InputDeviceClass::CURSOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002075 }
2076
Prashant Malani1941ff52015-08-11 18:29:28 -07002077 // See if this is a rotary encoder type device.
2078 String8 deviceType = String8();
2079 if (device->configuration &&
2080 device->configuration->tryGetProperty(String8("device.type"), deviceType)) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002081 if (!deviceType.compare(String8("rotaryEncoder"))) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002082 device->classes |= InputDeviceClass::ROTARY_ENCODER;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002083 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002084 }
2085
Michael Wrightd02c5b62014-02-10 15:10:22 -08002086 // See if this is a touch pad.
2087 // Is this a new modern multi-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002088 if (device->absBitmask.test(ABS_MT_POSITION_X) && device->absBitmask.test(ABS_MT_POSITION_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002089 // Some joysticks such as the PS3 controller report axes that conflict
2090 // with the ABS_MT range. Try to confirm that the device really is
2091 // a touch screen.
Chris Ye66fbac32020-07-06 20:36:43 -07002092 if (device->keyBitmask.test(BTN_TOUCH) || !haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002093 device->classes |= (InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002094 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002095 // Is this an old style single-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002096 } else if (device->keyBitmask.test(BTN_TOUCH) && device->absBitmask.test(ABS_X) &&
2097 device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002098 device->classes |= InputDeviceClass::TOUCH;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002099 // Is this a BT stylus?
Chris Ye66fbac32020-07-06 20:36:43 -07002100 } else if ((device->absBitmask.test(ABS_PRESSURE) || device->keyBitmask.test(BTN_TOUCH)) &&
2101 !device->absBitmask.test(ABS_X) && !device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002102 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -07002103 // Keyboard will try to claim some of the buttons but we really want to reserve those so we
2104 // can fuse it with the touch screen data, so just take them back. Note this means an
2105 // external stylus cannot also be a keyboard device.
Chris Ye1b0c7342020-07-28 21:57:03 -07002106 device->classes &= ~InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002107 }
2108
2109 // See if this device is a joystick.
2110 // Assumes that joysticks always have gamepad buttons in order to distinguish them
2111 // from other devices such as accelerometers that also have absolute axes.
2112 if (haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002113 auto assumedClasses = device->classes | InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002114 for (int i = 0; i <= ABS_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002115 if (device->absBitmask.test(i) &&
Chris Ye1b0c7342020-07-28 21:57:03 -07002116 (getAbsAxisUsage(i, assumedClasses).test(InputDeviceClass::JOYSTICK))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002117 device->classes = assumedClasses;
2118 break;
2119 }
2120 }
2121 }
2122
Chris Yef59a2f42020-10-16 12:55:26 -07002123 // Check whether this device is an accelerometer.
2124 if (device->propBitmask.test(INPUT_PROP_ACCELEROMETER)) {
2125 device->classes |= InputDeviceClass::SENSOR;
2126 }
2127
Michael Wrightd02c5b62014-02-10 15:10:22 -08002128 // Check whether this device has switches.
2129 for (int i = 0; i <= SW_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002130 if (device->swBitmask.test(i)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002131 device->classes |= InputDeviceClass::SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002132 break;
2133 }
2134 }
2135
2136 // Check whether this device supports the vibrator.
Chris Ye66fbac32020-07-06 20:36:43 -07002137 if (device->ffBitmask.test(FF_RUMBLE)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002138 device->classes |= InputDeviceClass::VIBRATOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002139 }
2140
2141 // Configure virtual keys.
Chris Ye1b0c7342020-07-28 21:57:03 -07002142 if ((device->classes.test(InputDeviceClass::TOUCH))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002143 // Load the virtual keys for the touch screen, if any.
2144 // We do this now so that we can make sure to load the keymap if necessary.
Chris Ye989bb932020-07-04 16:18:59 -07002145 bool success = device->loadVirtualKeyMapLocked();
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06002146 if (success) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002147 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002148 }
2149 }
2150
2151 // Load the key map.
Chris Yef59a2f42020-10-16 12:55:26 -07002152 // We need to do this for joysticks too because the key layout may specify axes, and for
2153 // sensor as well because the key layout may specify the axes to sensor data mapping.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002154 status_t keyMapStatus = NAME_NOT_FOUND;
Chris Yef59a2f42020-10-16 12:55:26 -07002155 if (device->classes.any(InputDeviceClass::KEYBOARD | InputDeviceClass::JOYSTICK |
2156 InputDeviceClass::SENSOR)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002157 // Load the keymap for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002158 keyMapStatus = device->loadKeyMapLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002159 }
2160
2161 // Configure the keyboard, gamepad or virtual keyboard.
Chris Ye1b0c7342020-07-28 21:57:03 -07002162 if (device->classes.test(InputDeviceClass::KEYBOARD)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002163 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002164 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002165 isEligibleBuiltInKeyboard(device->identifier, device->configuration.get(),
2166 &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002167 mBuiltInKeyboardId = device->id;
2168 }
2169
2170 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
Chris Ye989bb932020-07-04 16:18:59 -07002171 if (device->hasKeycodeLocked(AKEYCODE_Q)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002172 device->classes |= InputDeviceClass::ALPHAKEY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002173 }
2174
2175 // See if this device has a DPAD.
Chris Ye989bb932020-07-04 16:18:59 -07002176 if (device->hasKeycodeLocked(AKEYCODE_DPAD_UP) &&
2177 device->hasKeycodeLocked(AKEYCODE_DPAD_DOWN) &&
2178 device->hasKeycodeLocked(AKEYCODE_DPAD_LEFT) &&
2179 device->hasKeycodeLocked(AKEYCODE_DPAD_RIGHT) &&
2180 device->hasKeycodeLocked(AKEYCODE_DPAD_CENTER)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002181 device->classes |= InputDeviceClass::DPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002182 }
2183
2184 // See if this device has a gamepad.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002185 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES) / sizeof(GAMEPAD_KEYCODES[0]); i++) {
Chris Ye989bb932020-07-04 16:18:59 -07002186 if (device->hasKeycodeLocked(GAMEPAD_KEYCODES[i])) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002187 device->classes |= InputDeviceClass::GAMEPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002188 break;
2189 }
2190 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002191 }
2192
2193 // If the device isn't recognized as something we handle, don't monitor it.
Chris Ye1b0c7342020-07-28 21:57:03 -07002194 if (device->classes == Flags<InputDeviceClass>(0)) {
Chris Ye8594e192020-07-14 10:34:06 -07002195 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002196 device->identifier.name.c_str());
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002197 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002198 }
2199
Chris Ye3fdbfef2021-01-06 18:45:18 -08002200 // Classify InputDeviceClass::BATTERY.
2201 if (hasBattery) {
2202 device->classes |= InputDeviceClass::BATTERY;
2203 }
Kim Low03ea0352020-11-06 12:45:07 -08002204
Chris Ye3fdbfef2021-01-06 18:45:18 -08002205 // Classify InputDeviceClass::LIGHT.
2206 if (hasLights) {
2207 device->classes |= InputDeviceClass::LIGHT;
Kim Low03ea0352020-11-06 12:45:07 -08002208 }
2209
Tim Kilbourn063ff532015-04-08 10:26:18 -07002210 // Determine whether the device has a mic.
Chris Ye989bb932020-07-04 16:18:59 -07002211 if (device->deviceHasMicLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002212 device->classes |= InputDeviceClass::MIC;
Tim Kilbourn063ff532015-04-08 10:26:18 -07002213 }
2214
Michael Wrightd02c5b62014-02-10 15:10:22 -08002215 // Determine whether the device is external or internal.
Chris Ye989bb932020-07-04 16:18:59 -07002216 if (device->isExternalDeviceLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002217 device->classes |= InputDeviceClass::EXTERNAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002218 }
2219
Chris Ye1b0c7342020-07-28 21:57:03 -07002220 if (device->classes.any(InputDeviceClass::JOYSTICK | InputDeviceClass::DPAD) &&
2221 device->classes.test(InputDeviceClass::GAMEPAD)) {
Chris Ye989bb932020-07-04 16:18:59 -07002222 device->controllerNumber = getNextControllerNumberLocked(device->identifier.name);
2223 device->setLedForControllerLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002224 }
2225
Chris Ye989bb932020-07-04 16:18:59 -07002226 if (registerDeviceForEpollLocked(*device) != OK) {
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002227 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002228 }
2229
Chris Ye989bb932020-07-04 16:18:59 -07002230 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002231
Chris Ye1b0c7342020-07-28 21:57:03 -07002232 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=%s, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002233 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Chris Ye1b0c7342020-07-28 21:57:03 -07002234 deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(),
2235 device->classes.string().c_str(), device->configurationFile.c_str(),
2236 device->keyMap.keyLayoutFile.c_str(), device->keyMap.keyCharacterMapFile.c_str(),
2237 toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002238
Chris Ye989bb932020-07-04 16:18:59 -07002239 addDeviceLocked(std::move(device));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002240}
2241
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002242void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
2243 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
2244 if (!videoDevice) {
2245 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
2246 return;
2247 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002248 // Transfer ownership of this video device to a matching input device
Chris Ye989bb932020-07-04 16:18:59 -07002249 for (const auto& [id, device] : mDevices) {
Chris Yed3fef462021-03-07 17:10:08 -08002250 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002251 return; // 'device' now owns 'videoDevice'
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002252 }
2253 }
2254
2255 // Couldn't find a matching input device, so just add it to a temporary holding queue.
2256 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002257 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002258 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002259 mUnattachedVideoDevices.push_back(std::move(videoDevice));
2260}
2261
Chris Yed3fef462021-03-07 17:10:08 -08002262bool EventHub::tryAddVideoDeviceLocked(EventHub::Device& device,
2263 std::unique_ptr<TouchVideoDevice>& videoDevice) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002264 if (videoDevice->getName() != device.identifier.name) {
2265 return false;
2266 }
2267 device.videoDevice = std::move(videoDevice);
2268 if (device.enabled) {
2269 registerVideoDeviceForEpollLocked(*device.videoDevice);
2270 }
2271 return true;
2272}
2273
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002274bool EventHub::isDeviceEnabled(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002275 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002276 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002277 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002278 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2279 return false;
2280 }
2281 return device->enabled;
2282}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002283
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002284status_t EventHub::enableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002285 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002286 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002287 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002288 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2289 return BAD_VALUE;
2290 }
2291 if (device->enabled) {
2292 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
2293 return OK;
2294 }
2295 status_t result = device->enable();
2296 if (result != OK) {
2297 ALOGE("Failed to enable device %" PRId32, deviceId);
2298 return result;
2299 }
2300
Chris Ye989bb932020-07-04 16:18:59 -07002301 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002302
Chris Ye989bb932020-07-04 16:18:59 -07002303 return registerDeviceForEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002304}
2305
2306status_t EventHub::disableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002307 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002308 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002309 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002310 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2311 return BAD_VALUE;
2312 }
2313 if (!device->enabled) {
2314 ALOGW("Duplicate call to %s, input device already disabled", __func__);
2315 return OK;
2316 }
Chris Ye989bb932020-07-04 16:18:59 -07002317 unregisterDeviceFromEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002318 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002319}
2320
2321void EventHub::createVirtualKeyboardLocked() {
2322 InputDeviceIdentifier identifier;
2323 identifier.name = "Virtual";
2324 identifier.uniqueId = "<virtual>";
2325 assignDescriptorLocked(identifier);
2326
Chris Ye989bb932020-07-04 16:18:59 -07002327 std::unique_ptr<Device> device =
2328 std::make_unique<Device>(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
2329 identifier);
Chris Ye1b0c7342020-07-28 21:57:03 -07002330 device->classes = InputDeviceClass::KEYBOARD | InputDeviceClass::ALPHAKEY |
2331 InputDeviceClass::DPAD | InputDeviceClass::VIRTUAL;
Chris Ye989bb932020-07-04 16:18:59 -07002332 device->loadKeyMapLocked();
2333 addDeviceLocked(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002334}
2335
Chris Ye989bb932020-07-04 16:18:59 -07002336void EventHub::addDeviceLocked(std::unique_ptr<Device> device) {
Chris Yed3fef462021-03-07 17:10:08 -08002337 reportDeviceAddedForStatisticsLocked(device->identifier, device->classes);
Chris Ye989bb932020-07-04 16:18:59 -07002338 mOpeningDevices.push_back(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002339}
2340
Chris Ye989bb932020-07-04 16:18:59 -07002341int32_t EventHub::getNextControllerNumberLocked(const std::string& name) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002342 if (mControllerNumbers.isFull()) {
2343 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Chris Ye989bb932020-07-04 16:18:59 -07002344 name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002345 return 0;
2346 }
2347 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
2348 // one
2349 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
2350}
2351
Chris Ye989bb932020-07-04 16:18:59 -07002352void EventHub::releaseControllerNumberLocked(int32_t num) {
2353 if (num > 0) {
2354 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002355 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002356}
2357
Chris Ye8594e192020-07-14 10:34:06 -07002358void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002359 Device* device = getDeviceByPathLocked(devicePath);
Chris Ye989bb932020-07-04 16:18:59 -07002360 if (device != nullptr) {
2361 closeDeviceLocked(*device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002362 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002363 }
Chris Ye8594e192020-07-14 10:34:06 -07002364 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002365}
2366
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002367/**
2368 * Find the video device by filename, and close it.
2369 * The video device is closed by path during an inotify event, where we don't have the
2370 * additional context about the video device fd, or the associated input device.
2371 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002372void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002373 // A video device may be owned by an existing input device, or it may be stored in
2374 // the mUnattachedVideoDevices queue. Check both locations.
Chris Ye989bb932020-07-04 16:18:59 -07002375 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002376 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002377 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002378 device->videoDevice = nullptr;
2379 return;
2380 }
2381 }
Siarhei Vishniakouf47c339e2021-12-30 11:22:26 -08002382 std::erase_if(mUnattachedVideoDevices,
2383 [&devicePath](const std::unique_ptr<TouchVideoDevice>& videoDevice) {
2384 return videoDevice->getPath() == devicePath;
2385 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08002386}
2387
2388void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002389 mUnattachedVideoDevices.clear();
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002390 while (!mDevices.empty()) {
2391 closeDeviceLocked(*(mDevices.begin()->second));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002392 }
2393}
2394
Chris Ye989bb932020-07-04 16:18:59 -07002395void EventHub::closeDeviceLocked(Device& device) {
2396 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=%s", device.path.c_str(),
2397 device.identifier.name.c_str(), device.id, device.fd, device.classes.string().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002398
Chris Ye989bb932020-07-04 16:18:59 -07002399 if (device.id == mBuiltInKeyboardId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002400 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Chris Ye989bb932020-07-04 16:18:59 -07002401 device.path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002402 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
2403 }
2404
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002405 unregisterDeviceFromEpollLocked(device);
Chris Ye989bb932020-07-04 16:18:59 -07002406 if (device.videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002407 // This must be done after the video device is removed from epoll
Chris Ye989bb932020-07-04 16:18:59 -07002408 mUnattachedVideoDevices.push_back(std::move(device.videoDevice));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002409 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002410
Chris Ye989bb932020-07-04 16:18:59 -07002411 releaseControllerNumberLocked(device.controllerNumber);
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002412 device.controllerNumber = 0;
Chris Ye989bb932020-07-04 16:18:59 -07002413 device.close();
Chris Ye989bb932020-07-04 16:18:59 -07002414 mClosingDevices.push_back(std::move(mDevices[device.id]));
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002415
Chris Ye989bb932020-07-04 16:18:59 -07002416 mDevices.erase(device.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002417}
2418
2419status_t EventHub::readNotifyLocked() {
2420 int res;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002421 char event_buf[512];
2422 int event_size;
2423 int event_pos = 0;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002424 struct inotify_event* event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002425
2426 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
2427 res = read(mINotifyFd, event_buf, sizeof(event_buf));
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002428 if (res < (int)sizeof(*event)) {
2429 if (errno == EINTR) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002430 ALOGW("could not get event, %s\n", strerror(errno));
2431 return -1;
2432 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002433
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002434 while (res >= (int)sizeof(*event)) {
2435 event = (struct inotify_event*)(event_buf + event_pos);
2436 if (event->len) {
Usama Arifb27c8e62021-06-03 16:44:09 +01002437 if (event->wd == mDeviceInputWd) {
2438 std::string filename = std::string(DEVICE_INPUT_PATH) + "/" + event->name;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002439 if (event->mask & IN_CREATE) {
Chris Ye8594e192020-07-14 10:34:06 -07002440 openDeviceLocked(filename);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08002441 } else {
2442 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
Chris Ye8594e192020-07-14 10:34:06 -07002443 closeDeviceByPathLocked(filename);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08002444 }
Usama Arifb27c8e62021-06-03 16:44:09 +01002445 } else if (event->wd == mDeviceWd) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08002446 if (isV4lTouchNode(event->name)) {
Usama Arifb27c8e62021-06-03 16:44:09 +01002447 std::string filename = std::string(DEVICE_PATH) + "/" + event->name;
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002448 if (event->mask & IN_CREATE) {
2449 openVideoDeviceLocked(filename);
2450 } else {
2451 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
2452 closeVideoDeviceByPathLocked(filename);
2453 }
Usama Arifb27c8e62021-06-03 16:44:09 +01002454 } else if (strcmp(event->name, "input") == 0 && event->mask & IN_CREATE) {
2455 addDeviceInputInotify();
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08002456 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002457 } else {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08002458 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event->wd);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002459 }
2460 }
2461 event_size = sizeof(*event) + event->len;
2462 res -= event_size;
2463 event_pos += event_size;
2464 }
2465 return 0;
2466}
2467
Chris Ye8594e192020-07-14 10:34:06 -07002468status_t EventHub::scanDirLocked(const std::string& dirname) {
2469 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2470 openDeviceLocked(entry.path());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002471 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002472 return 0;
2473}
2474
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002475/**
2476 * Look for all dirname/v4l-touch* devices, and open them.
2477 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002478status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Chris Ye8594e192020-07-14 10:34:06 -07002479 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2480 if (isV4lTouchNode(entry.path())) {
2481 ALOGI("Found touch video device %s", entry.path().c_str());
2482 openVideoDeviceLocked(entry.path());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002483 }
2484 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002485 return OK;
2486}
2487
Michael Wrightd02c5b62014-02-10 15:10:22 -08002488void EventHub::requestReopenDevices() {
2489 ALOGV("requestReopenDevices() called");
2490
Chris Ye87143712020-11-10 05:05:58 +00002491 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002492 mNeedToReopenDevices = true;
2493}
2494
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002495void EventHub::dump(std::string& dump) {
2496 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002497
2498 { // acquire lock
Chris Ye87143712020-11-10 05:05:58 +00002499 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002500
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002501 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002502
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002503 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002504
Chris Ye989bb932020-07-04 16:18:59 -07002505 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002506 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002507 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002508 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002509 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002510 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002511 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002512 }
Chris Ye1b0c7342020-07-28 21:57:03 -07002513 dump += StringPrintf(INDENT3 "Classes: %s\n", device->classes.string().c_str());
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002514 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002515 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002516 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
2517 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002518 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002519 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002520 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002521 "product=0x%04x, version=0x%04x\n",
2522 device->identifier.bus, device->identifier.vendor,
2523 device->identifier.product, device->identifier.version);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002524 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002525 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002526 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002527 device->keyMap.keyCharacterMapFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002528 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002529 device->configurationFile.c_str());
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002530 dump += INDENT3 "VideoDevice: ";
2531 if (device->videoDevice) {
2532 dump += device->videoDevice->dump() + "\n";
2533 } else {
2534 dump += "<none>\n";
2535 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002536 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002537
2538 dump += INDENT "Unattached video devices:\n";
2539 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
2540 dump += INDENT2 + videoDevice->dump() + "\n";
2541 }
2542 if (mUnattachedVideoDevices.empty()) {
2543 dump += INDENT2 "<none>\n";
2544 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002545 } // release lock
2546}
2547
2548void EventHub::monitor() {
2549 // Acquire and release the lock to ensure that the event hub has not deadlocked.
Chris Ye1c2e0892020-11-30 21:41:44 -08002550 std::unique_lock<std::mutex> lock(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002551}
2552
Michael Wrightd02c5b62014-02-10 15:10:22 -08002553}; // namespace android