blob: 1a7fcd5941566756719d5282cf3d89b3237beffc [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>
Chris Yed1936772021-02-22 10:30:40 -080040#include <android-base/strings.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080041#include <android-base/stringprintf.h>
Philip Quinn39b81682019-01-09 22:20:39 -080042#include <cutils/properties.h>
Chris Ye8594e192020-07-14 10:34:06 -070043#include <input/KeyCharacterMap.h>
44#include <input/KeyLayoutMap.h>
45#include <input/VirtualKeyMap.h>
Dan Albert677d87e2014-06-16 17:31:28 -070046#include <openssl/sha.h>
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070047#include <utils/Errors.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080048#include <utils/Log.h>
49#include <utils/Timers.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080050
Chris Ye8594e192020-07-14 10:34:06 -070051#include <filesystem>
Chris Ye3fdbfef2021-01-06 18:45:18 -080052#include <regex>
Chris Ye8594e192020-07-14 10:34:06 -070053
54#include "EventHub.h"
Michael Wrightd02c5b62014-02-10 15:10:22 -080055
Michael Wrightd02c5b62014-02-10 15:10:22 -080056#define INDENT " "
57#define INDENT2 " "
58#define INDENT3 " "
59
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080060using android::base::StringPrintf;
Chris Ye1b0c7342020-07-28 21:57:03 -070061using namespace android::flag_operators;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080062
Michael Wrightd02c5b62014-02-10 15:10:22 -080063namespace android {
64
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070065static const char* DEVICE_PATH = "/dev/input";
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080066// v4l2 devices go directly into /dev
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070067static const char* VIDEO_DEVICE_PATH = "/dev";
Michael Wrightd02c5b62014-02-10 15:10:22 -080068
Chris Ye87143712020-11-10 05:05:58 +000069static constexpr int32_t FF_STRONG_MAGNITUDE_CHANNEL_IDX = 0;
70static constexpr int32_t FF_WEAK_MAGNITUDE_CHANNEL_IDX = 1;
Chris Ye6393a262020-08-04 19:41:36 -070071
Kim Low03ea0352020-11-06 12:45:07 -080072// must be kept in sync with definitions in kernel /drivers/power/supply/power_supply_sysfs.c
73static const std::unordered_map<std::string, int32_t> BATTERY_STATUS =
74 {{"Unknown", BATTERY_STATUS_UNKNOWN},
75 {"Charging", BATTERY_STATUS_CHARGING},
76 {"Discharging", BATTERY_STATUS_DISCHARGING},
77 {"Not charging", BATTERY_STATUS_NOT_CHARGING},
78 {"Full", BATTERY_STATUS_FULL}};
79
80// Mapping taken from
81// https://gitlab.freedesktop.org/upower/upower/-/blob/master/src/linux/up-device-supply.c#L484
82static const std::unordered_map<std::string, int32_t> BATTERY_LEVEL = {{"Critical", 5},
83 {"Low", 10},
84 {"Normal", 55},
85 {"High", 70},
86 {"Full", 100},
87 {"Unknown", 50}};
88
Chris Ye3fdbfef2021-01-06 18:45:18 -080089// Mapping for input led class node names lookup.
90// https://www.kernel.org/doc/html/latest/leds/leds-class.html
91static const std::unordered_map<std::string, InputLightClass> LIGHT_CLASSES =
92 {{"red", InputLightClass::RED},
93 {"green", InputLightClass::GREEN},
94 {"blue", InputLightClass::BLUE},
95 {"global", InputLightClass::GLOBAL},
96 {"brightness", InputLightClass::BRIGHTNESS},
97 {"multi_index", InputLightClass::MULTI_INDEX},
98 {"multi_intensity", InputLightClass::MULTI_INTENSITY},
99 {"max_brightness", InputLightClass::MAX_BRIGHTNESS}};
100
101// Mapping for input multicolor led class node names.
102// https://www.kernel.org/doc/html/latest/leds/leds-class-multicolor.html
103static const std::unordered_map<InputLightClass, std::string> LIGHT_NODES =
104 {{InputLightClass::BRIGHTNESS, "brightness"},
105 {InputLightClass::MULTI_INDEX, "multi_index"},
106 {InputLightClass::MULTI_INTENSITY, "multi_intensity"}};
107
108// Mapping for light color name and the light color
109const std::unordered_map<std::string, LightColor> LIGHT_COLORS = {{"red", LightColor::RED},
110 {"green", LightColor::GREEN},
111 {"blue", LightColor::BLUE}};
112
Michael Wrightd02c5b62014-02-10 15:10:22 -0800113static inline const char* toString(bool value) {
114 return value ? "true" : "false";
115}
116
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100117static std::string sha1(const std::string& in) {
Dan Albert677d87e2014-06-16 17:31:28 -0700118 SHA_CTX ctx;
119 SHA1_Init(&ctx);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100120 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
Dan Albert677d87e2014-06-16 17:31:28 -0700121 u_char digest[SHA_DIGEST_LENGTH];
122 SHA1_Final(digest, &ctx);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800123
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100124 std::string out;
Dan Albert677d87e2014-06-16 17:31:28 -0700125 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100126 out += StringPrintf("%02x", digest[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800127 }
128 return out;
129}
130
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800131/**
132 * Return true if name matches "v4l-touch*"
133 */
Chris Ye8594e192020-07-14 10:34:06 -0700134static bool isV4lTouchNode(std::string name) {
135 return name.find("v4l-touch") != std::string::npos;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800136}
137
Philip Quinn39b81682019-01-09 22:20:39 -0800138/**
139 * Returns true if V4L devices should be scanned.
140 *
141 * The system property ro.input.video_enabled can be used to control whether
142 * EventHub scans and opens V4L devices. As V4L does not support multiple
143 * clients, EventHub effectively blocks access to these devices when it opens
Siarhei Vishniakou29f88492019-04-05 14:11:43 -0700144 * them.
145 *
146 * Setting this to "false" would prevent any video devices from being discovered and
147 * associated with input devices.
148 *
149 * This property can be used as follows:
150 * 1. To turn off features that are dependent on video device presence.
151 * 2. During testing and development, to allow other clients to read video devices
152 * directly from /dev.
Philip Quinn39b81682019-01-09 22:20:39 -0800153 */
154static bool isV4lScanningEnabled() {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700155 return property_get_bool("ro.input.video_enabled", true /* default_value */);
Philip Quinn39b81682019-01-09 22:20:39 -0800156}
157
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800158static nsecs_t processEventTimestamp(const struct input_event& event) {
159 // Use the time specified in the event instead of the current time
160 // so that downstream code can get more accurate estimates of
161 // event dispatch latency from the time the event is enqueued onto
162 // the evdev client buffer.
163 //
164 // The event's timestamp fortuitously uses the same monotonic clock
165 // time base as the rest of Android. The kernel event device driver
166 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
167 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
168 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
169 // system call that also queries ktime_get_ts().
170
171 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.time.tv_sec) +
172 microseconds_to_nanoseconds(event.time.tv_usec);
173 return inputEventTime;
174}
175
Kim Low03ea0352020-11-06 12:45:07 -0800176/**
177 * Returns the sysfs root path of the input device
178 *
179 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800180static std::optional<std::filesystem::path> getSysfsRootPath(const char* devicePath) {
Kim Low03ea0352020-11-06 12:45:07 -0800181 std::error_code errorCode;
182
183 // Stat the device path to get the major and minor number of the character file
184 struct stat statbuf;
185 if (stat(devicePath, &statbuf) == -1) {
186 ALOGE("Could not stat device %s due to error: %s.", devicePath, std::strerror(errno));
Chris Ye3fdbfef2021-01-06 18:45:18 -0800187 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800188 }
189
190 unsigned int major_num = major(statbuf.st_rdev);
191 unsigned int minor_num = minor(statbuf.st_rdev);
192
193 // Realpath "/sys/dev/char/{major}:{minor}" to get the sysfs path to the input event
194 auto sysfsPath = std::filesystem::path("/sys/dev/char/");
195 sysfsPath /= std::to_string(major_num) + ":" + std::to_string(minor_num);
196 sysfsPath = std::filesystem::canonical(sysfsPath, errorCode);
197
198 // Make sure nothing went wrong in call to canonical()
199 if (errorCode) {
200 ALOGW("Could not run filesystem::canonical() due to error %d : %s.", errorCode.value(),
201 errorCode.message().c_str());
Chris Ye3fdbfef2021-01-06 18:45:18 -0800202 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800203 }
204
205 // Continue to go up a directory until we reach a directory named "input"
206 while (sysfsPath != "/" && sysfsPath.filename() != "input") {
207 sysfsPath = sysfsPath.parent_path();
208 }
209
210 // Then go up one more and you will be at the sysfs root of the device
211 sysfsPath = sysfsPath.parent_path();
212
213 // Make sure we didn't reach root path and that directory actually exists
214 if (sysfsPath == "/" || !std::filesystem::exists(sysfsPath, errorCode)) {
215 if (errorCode) {
216 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
217 errorCode.message().c_str());
218 }
219
220 // Not found
Chris Ye3fdbfef2021-01-06 18:45:18 -0800221 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800222 }
223
224 return sysfsPath;
225}
226
227/**
Chris Ye3fdbfef2021-01-06 18:45:18 -0800228 * Returns the list of files under a specified path.
Kim Low03ea0352020-11-06 12:45:07 -0800229 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800230static std::vector<std::filesystem::path> allFilesInPath(const std::filesystem::path& path) {
231 std::vector<std::filesystem::path> nodes;
232 std::error_code errorCode;
233 auto iter = std::filesystem::directory_iterator(path, errorCode);
234 while (!errorCode && iter != std::filesystem::directory_iterator()) {
235 nodes.push_back(iter->path());
236 iter++;
237 }
238 return nodes;
239}
240
241/**
242 * Returns the list of files under a specified directory in a sysfs path.
243 * Example:
244 * findSysfsNodes(sysfsRootPath, SysfsClass::LEDS) will return all led nodes under "leds" directory
245 * in the sysfs path.
246 */
247static std::vector<std::filesystem::path> findSysfsNodes(const std::filesystem::path& sysfsRoot,
248 SysfsClass clazz) {
249 std::string nodeStr = NamedEnum::string(clazz);
250 std::for_each(nodeStr.begin(), nodeStr.end(),
251 [](char& c) { c = std::tolower(static_cast<unsigned char>(c)); });
252 std::vector<std::filesystem::path> nodes;
253 for (auto path = sysfsRoot; path != "/" && nodes.empty(); path = path.parent_path()) {
254 nodes = allFilesInPath(path / nodeStr);
255 }
256 return nodes;
257}
258
259static std::optional<std::array<LightColor, COLOR_NUM>> getColorIndexArray(
260 std::filesystem::path path) {
261 std::string indexStr;
262 if (!base::ReadFileToString(path, &indexStr)) {
263 return std::nullopt;
264 }
265
266 // Parse the multi color LED index file, refer to kernel docs
267 // leds/leds-class-multicolor.html
268 std::regex indexPattern("(red|green|blue)\\s(red|green|blue)\\s(red|green|blue)[\\n]");
269 std::smatch results;
270 std::array<LightColor, COLOR_NUM> colors;
271 if (!std::regex_match(indexStr, results, indexPattern)) {
272 return std::nullopt;
273 }
274
275 for (size_t i = 1; i < results.size(); i++) {
276 const auto it = LIGHT_COLORS.find(results[i].str());
277 if (it != LIGHT_COLORS.end()) {
278 // intensities.emplace(it->second, 0);
279 colors[i - 1] = it->second;
Kim Low03ea0352020-11-06 12:45:07 -0800280 }
281 }
Chris Ye3fdbfef2021-01-06 18:45:18 -0800282 return colors;
Kim Low03ea0352020-11-06 12:45:07 -0800283}
284
Michael Wrightd02c5b62014-02-10 15:10:22 -0800285// --- Global Functions ---
286
Chris Ye1b0c7342020-07-28 21:57:03 -0700287Flags<InputDeviceClass> getAbsAxisUsage(int32_t axis, Flags<InputDeviceClass> deviceClasses) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800288 // Touch devices get dibs on touch-related axes.
Chris Ye1b0c7342020-07-28 21:57:03 -0700289 if (deviceClasses.test(InputDeviceClass::TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800290 switch (axis) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700291 case ABS_X:
292 case ABS_Y:
293 case ABS_PRESSURE:
294 case ABS_TOOL_WIDTH:
295 case ABS_DISTANCE:
296 case ABS_TILT_X:
297 case ABS_TILT_Y:
298 case ABS_MT_SLOT:
299 case ABS_MT_TOUCH_MAJOR:
300 case ABS_MT_TOUCH_MINOR:
301 case ABS_MT_WIDTH_MAJOR:
302 case ABS_MT_WIDTH_MINOR:
303 case ABS_MT_ORIENTATION:
304 case ABS_MT_POSITION_X:
305 case ABS_MT_POSITION_Y:
306 case ABS_MT_TOOL_TYPE:
307 case ABS_MT_BLOB_ID:
308 case ABS_MT_TRACKING_ID:
309 case ABS_MT_PRESSURE:
310 case ABS_MT_DISTANCE:
Chris Ye1b0c7342020-07-28 21:57:03 -0700311 return InputDeviceClass::TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800312 }
313 }
314
Chris Yef59a2f42020-10-16 12:55:26 -0700315 if (deviceClasses.test(InputDeviceClass::SENSOR)) {
316 switch (axis) {
317 case ABS_X:
318 case ABS_Y:
319 case ABS_Z:
320 case ABS_RX:
321 case ABS_RY:
322 case ABS_RZ:
323 return InputDeviceClass::SENSOR;
324 }
325 }
326
Michael Wright842500e2015-03-13 17:32:02 -0700327 // External stylus gets the pressure axis
Chris Ye1b0c7342020-07-28 21:57:03 -0700328 if (deviceClasses.test(InputDeviceClass::EXTERNAL_STYLUS)) {
Michael Wright842500e2015-03-13 17:32:02 -0700329 if (axis == ABS_PRESSURE) {
Chris Ye1b0c7342020-07-28 21:57:03 -0700330 return InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -0700331 }
332 }
333
Michael Wrightd02c5b62014-02-10 15:10:22 -0800334 // Joystick devices get the rest.
Chris Ye1b0c7342020-07-28 21:57:03 -0700335 return deviceClasses & InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800336}
337
338// --- EventHub::Device ---
339
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100340EventHub::Device::Device(int fd, int32_t id, const std::string& path,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700341 const InputDeviceIdentifier& identifier)
Chris Ye989bb932020-07-04 16:18:59 -0700342 : fd(fd),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700343 id(id),
344 path(path),
345 identifier(identifier),
346 classes(0),
347 configuration(nullptr),
348 virtualKeyMap(nullptr),
349 ffEffectPlaying(false),
350 ffEffectId(-1),
Chris Ye3fdbfef2021-01-06 18:45:18 -0800351 nextLightId(0),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700352 controllerNumber(0),
353 enabled(true),
Chris Ye66fbac32020-07-06 20:36:43 -0700354 isVirtual(fd < 0) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800355
356EventHub::Device::~Device() {
357 close();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800358}
359
360void EventHub::Device::close() {
361 if (fd >= 0) {
362 ::close(fd);
363 fd = -1;
364 }
365}
366
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700367status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100368 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700369 if (fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100370 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700371 return -errno;
372 }
373 enabled = true;
374 return OK;
375}
376
377status_t EventHub::Device::disable() {
378 close();
379 enabled = false;
380 return OK;
381}
382
Chris Ye989bb932020-07-04 16:18:59 -0700383bool EventHub::Device::hasValidFd() const {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700384 return !isVirtual && enabled;
385}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800386
Chris Ye3a1e4462020-08-12 10:13:15 -0700387const std::shared_ptr<KeyCharacterMap> EventHub::Device::getKeyCharacterMap() const {
Chris Ye989bb932020-07-04 16:18:59 -0700388 return keyMap.keyCharacterMap;
389}
390
391template <std::size_t N>
392status_t EventHub::Device::readDeviceBitMask(unsigned long ioctlCode, BitArray<N>& bitArray) {
393 if (!hasValidFd()) {
394 return BAD_VALUE;
395 }
396 if ((_IOC_SIZE(ioctlCode) == 0)) {
397 ioctlCode |= _IOC(0, 0, 0, bitArray.bytes());
398 }
399
400 typename BitArray<N>::Buffer buffer;
401 status_t ret = ioctl(fd, ioctlCode, buffer.data());
402 bitArray.loadFromBuffer(buffer);
403 return ret;
404}
405
406void EventHub::Device::configureFd() {
407 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
408 if (classes.test(InputDeviceClass::KEYBOARD)) {
409 // Disable kernel key repeat since we handle it ourselves
410 unsigned int repeatRate[] = {0, 0};
411 if (ioctl(fd, EVIOCSREP, repeatRate)) {
412 ALOGW("Unable to disable kernel key repeat for %s: %s", path.c_str(), strerror(errno));
413 }
414 }
415
416 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
417 // associated with input events. This is important because the input system
418 // uses the timestamps extensively and assumes they were recorded using the monotonic
419 // clock.
420 int clockId = CLOCK_MONOTONIC;
Chris Yef59a2f42020-10-16 12:55:26 -0700421 if (classes.test(InputDeviceClass::SENSOR)) {
422 // Each new sensor event should use the same time base as
423 // SystemClock.elapsedRealtimeNanos().
424 clockId = CLOCK_BOOTTIME;
425 }
Chris Ye989bb932020-07-04 16:18:59 -0700426 bool usingClockIoctl = !ioctl(fd, EVIOCSCLOCKID, &clockId);
427 ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
428}
429
430bool EventHub::Device::hasKeycodeLocked(int keycode) const {
431 if (!keyMap.haveKeyLayout()) {
432 return false;
433 }
434
435 std::vector<int32_t> scanCodes;
436 keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes);
437 const size_t N = scanCodes.size();
438 for (size_t i = 0; i < N && i <= KEY_MAX; i++) {
439 int32_t sc = scanCodes[i];
440 if (sc >= 0 && sc <= KEY_MAX && keyBitmask.test(sc)) {
441 return true;
442 }
443 }
444
445 return false;
446}
447
448void EventHub::Device::loadConfigurationLocked() {
449 configurationFile =
450 getInputDeviceConfigurationFilePathByDeviceIdentifier(identifier,
451 InputDeviceConfigurationFileType::
452 CONFIGURATION);
453 if (configurationFile.empty()) {
454 ALOGD("No input device configuration file found for device '%s'.", identifier.name.c_str());
455 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500456 android::base::Result<std::unique_ptr<PropertyMap>> propertyMap =
457 PropertyMap::load(configurationFile.c_str());
458 if (!propertyMap.ok()) {
Chris Ye989bb932020-07-04 16:18:59 -0700459 ALOGE("Error loading input device configuration file for device '%s'. "
460 "Using default configuration.",
461 identifier.name.c_str());
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500462 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500463 configuration = std::move(*propertyMap);
Chris Ye989bb932020-07-04 16:18:59 -0700464 }
465 }
466}
467
468bool EventHub::Device::loadVirtualKeyMapLocked() {
469 // The virtual key map is supplied by the kernel as a system board property file.
470 std::string propPath = "/sys/board_properties/virtualkeys.";
471 propPath += identifier.getCanonicalName();
472 if (access(propPath.c_str(), R_OK)) {
473 return false;
474 }
475 virtualKeyMap = VirtualKeyMap::load(propPath);
476 return virtualKeyMap != nullptr;
477}
478
479status_t EventHub::Device::loadKeyMapLocked() {
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500480 return keyMap.load(identifier, configuration.get());
Chris Ye989bb932020-07-04 16:18:59 -0700481}
482
483bool EventHub::Device::isExternalDeviceLocked() {
484 if (configuration) {
485 bool value;
486 if (configuration->tryGetProperty(String8("device.internal"), value)) {
487 return !value;
488 }
489 }
490 return identifier.bus == BUS_USB || identifier.bus == BUS_BLUETOOTH;
491}
492
493bool EventHub::Device::deviceHasMicLocked() {
494 if (configuration) {
495 bool value;
496 if (configuration->tryGetProperty(String8("audio.mic"), value)) {
497 return value;
498 }
499 }
500 return false;
501}
502
503void EventHub::Device::setLedStateLocked(int32_t led, bool on) {
504 int32_t sc;
505 if (hasValidFd() && mapLed(led, &sc) != NAME_NOT_FOUND) {
506 struct input_event ev;
507 ev.time.tv_sec = 0;
508 ev.time.tv_usec = 0;
509 ev.type = EV_LED;
510 ev.code = sc;
511 ev.value = on ? 1 : 0;
512
513 ssize_t nWrite;
514 do {
515 nWrite = write(fd, &ev, sizeof(struct input_event));
516 } while (nWrite == -1 && errno == EINTR);
517 }
518}
519
520void EventHub::Device::setLedForControllerLocked() {
521 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
522 setLedStateLocked(ALED_CONTROLLER_1 + i, controllerNumber == i + 1);
523 }
524}
525
526status_t EventHub::Device::mapLed(int32_t led, int32_t* outScanCode) const {
527 if (!keyMap.haveKeyLayout()) {
528 return NAME_NOT_FOUND;
529 }
530
531 int32_t scanCode;
532 if (keyMap.keyLayoutMap->findScanCodeForLed(led, &scanCode) != NAME_NOT_FOUND) {
533 if (scanCode >= 0 && scanCode <= LED_MAX && ledBitmask.test(scanCode)) {
534 *outScanCode = scanCode;
535 return NO_ERROR;
536 }
537 }
538 return NAME_NOT_FOUND;
539}
540
Chris Ye3fdbfef2021-01-06 18:45:18 -0800541// Check the sysfs path for any input device batteries, returns true if battery found.
542bool EventHub::Device::configureBatteryLocked() {
543 if (!sysfsRootPath.has_value()) {
544 return false;
545 }
546 // Check if device has any batteries.
547 std::vector<std::filesystem::path> batteryPaths =
548 findSysfsNodes(sysfsRootPath.value(), SysfsClass::POWER_SUPPLY);
549 // We only support single battery for an input device, if multiple batteries exist only the
550 // first one is supported.
551 if (batteryPaths.empty()) {
552 // Set path to be empty
553 sysfsBatteryPath = std::nullopt;
554 return false;
555 }
556 // If a battery exists
557 sysfsBatteryPath = batteryPaths[0];
558 return true;
559}
560
561// Check the sysfs path for any input device lights, returns true if lights found.
562bool EventHub::Device::configureLightsLocked() {
563 if (!sysfsRootPath.has_value()) {
564 return false;
565 }
566 // Check if device has any lights.
567 const auto& paths = findSysfsNodes(sysfsRootPath.value(), SysfsClass::LEDS);
568 for (const auto& nodePath : paths) {
569 RawLightInfo info;
570 info.id = ++nextLightId;
571 info.path = nodePath;
572 info.name = nodePath.filename();
573 info.maxBrightness = std::nullopt;
574 size_t nameStart = info.name.rfind(":");
575 if (nameStart != std::string::npos) {
576 // Trim the name to color name
577 info.name = info.name.substr(nameStart + 1);
578 // Set InputLightClass flag for colors
579 const auto it = LIGHT_CLASSES.find(info.name);
580 if (it != LIGHT_CLASSES.end()) {
581 info.flags |= it->second;
582 }
583 }
584 // Scan the path for all the files
585 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
586 const auto& files = allFilesInPath(nodePath);
587 for (const auto& file : files) {
588 const auto it = LIGHT_CLASSES.find(file.filename().string());
589 if (it != LIGHT_CLASSES.end()) {
590 info.flags |= it->second;
591 // If the node has maximum brightness, read it
592 if (it->second == InputLightClass::MAX_BRIGHTNESS) {
593 std::string str;
594 if (base::ReadFileToString(file, &str)) {
595 info.maxBrightness = std::stoi(str);
596 }
597 }
598 }
599 }
600 lightInfos.insert_or_assign(info.id, info);
601 }
602 return !lightInfos.empty();
603}
604
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100605/**
606 * Get the capabilities for the current process.
607 * Crashes the system if unable to create / check / destroy the capabilities object.
608 */
609class Capabilities final {
610public:
611 explicit Capabilities() {
612 mCaps = cap_get_proc();
613 LOG_ALWAYS_FATAL_IF(mCaps == nullptr, "Could not get capabilities of the current process");
614 }
615
616 /**
617 * Check whether the current process has a specific capability
618 * in the set of effective capabilities.
619 * Return CAP_SET if the process has the requested capability
620 * Return CAP_CLEAR otherwise.
621 */
622 cap_flag_value_t checkEffectiveCapability(cap_value_t capability) {
623 cap_flag_value_t value;
624 const int result = cap_get_flag(mCaps, capability, CAP_EFFECTIVE, &value);
625 LOG_ALWAYS_FATAL_IF(result == -1, "Could not obtain the requested capability");
626 return value;
627 }
628
629 ~Capabilities() {
630 const int result = cap_free(mCaps);
631 LOG_ALWAYS_FATAL_IF(result == -1, "Could not release the capabilities structure");
632 }
633
634private:
635 cap_t mCaps;
636};
637
638static void ensureProcessCanBlockSuspend() {
639 Capabilities capabilities;
640 const bool canBlockSuspend =
641 capabilities.checkEffectiveCapability(CAP_BLOCK_SUSPEND) == CAP_SET;
642 LOG_ALWAYS_FATAL_IF(!canBlockSuspend,
643 "Input must be able to block suspend to properly process events");
644}
645
Michael Wrightd02c5b62014-02-10 15:10:22 -0800646// --- EventHub ---
647
Michael Wrightd02c5b62014-02-10 15:10:22 -0800648const int EventHub::EPOLL_MAX_EVENTS;
649
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700650EventHub::EventHub(void)
651 : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
652 mNextDeviceId(1),
653 mControllerNumbers(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800654 mNeedToSendFinishedDeviceScan(false),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700655 mNeedToReopenDevices(false),
656 mNeedToScanDevices(true),
657 mPendingEventCount(0),
658 mPendingEventIndex(0),
659 mPendingINotify(false) {
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100660 ensureProcessCanBlockSuspend();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800661
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800662 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800663 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800664
665 mINotifyFd = inotify_init();
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800666 mInputWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700667 LOG_ALWAYS_FATAL_IF(mInputWd < 0, "Could not register INotify for %s: %s", DEVICE_PATH,
668 strerror(errno));
Philip Quinn39b81682019-01-09 22:20:39 -0800669 if (isV4lScanningEnabled()) {
670 mVideoWd = inotify_add_watch(mINotifyFd, VIDEO_DEVICE_PATH, IN_DELETE | IN_CREATE);
671 LOG_ALWAYS_FATAL_IF(mVideoWd < 0, "Could not register INotify for %s: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700672 VIDEO_DEVICE_PATH, strerror(errno));
Philip Quinn39b81682019-01-09 22:20:39 -0800673 } else {
674 mVideoWd = -1;
675 ALOGI("Video device scanning disabled");
676 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800677
Siarhei Vishniakou2d0e9482019-09-24 12:52:47 +0100678 struct epoll_event eventItem = {};
679 eventItem.events = EPOLLIN | EPOLLWAKEUP;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700680 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800681 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800682 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
683
684 int wakeFds[2];
685 result = pipe(wakeFds);
686 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
687
688 mWakeReadPipeFd = wakeFds[0];
689 mWakeWritePipeFd = wakeFds[1];
690
691 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
692 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700693 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800694
695 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
696 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700697 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800698
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700699 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800700 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
701 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700702 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800703}
704
705EventHub::~EventHub(void) {
706 closeAllDevicesLocked();
707
Michael Wrightd02c5b62014-02-10 15:10:22 -0800708 ::close(mEpollFd);
709 ::close(mINotifyFd);
710 ::close(mWakeReadPipeFd);
711 ::close(mWakeWritePipeFd);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800712}
713
714InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000715 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800716 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700717 return device != nullptr ? device->identifier : InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800718}
719
Chris Ye1b0c7342020-07-28 21:57:03 -0700720Flags<InputDeviceClass> EventHub::getDeviceClasses(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000721 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800722 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700723 return device != nullptr ? device->classes : Flags<InputDeviceClass>(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800724}
725
726int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000727 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800728 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700729 return device != nullptr ? device->controllerNumber : 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800730}
731
732void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
Chris Ye87143712020-11-10 05:05:58 +0000733 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800734 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700735 if (device != nullptr && device->configuration) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800736 *outConfiguration = *device->configuration;
737 } else {
738 outConfiguration->clear();
739 }
740}
741
742status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700743 RawAbsoluteAxisInfo* outAxisInfo) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800744 outAxisInfo->clear();
745
746 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000747 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800748
749 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700750 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800751 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700752 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
753 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
754 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800755 return -errno;
756 }
757
758 if (info.minimum != info.maximum) {
759 outAxisInfo->valid = true;
760 outAxisInfo->minValue = info.minimum;
761 outAxisInfo->maxValue = info.maximum;
762 outAxisInfo->flat = info.flat;
763 outAxisInfo->fuzz = info.fuzz;
764 outAxisInfo->resolution = info.resolution;
765 }
766 return OK;
767 }
768 }
769 return -1;
770}
771
772bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
773 if (axis >= 0 && axis <= REL_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000774 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800775 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700776 return device != nullptr ? device->relBitmask.test(axis) : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800777 }
778 return false;
779}
780
781bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
Chris Ye87143712020-11-10 05:05:58 +0000782 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800783
Chris Ye989bb932020-07-04 16:18:59 -0700784 Device* device = getDeviceLocked(deviceId);
785 return property >= 0 && property <= INPUT_PROP_MAX && device != nullptr
786 ? device->propBitmask.test(property)
787 : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788}
789
Chris Yef59a2f42020-10-16 12:55:26 -0700790bool EventHub::hasMscEvent(int32_t deviceId, int mscEvent) const {
791 std::scoped_lock _l(mLock);
792
793 Device* device = getDeviceLocked(deviceId);
794 return mscEvent >= 0 && mscEvent <= MSC_MAX && device != nullptr
795 ? device->mscBitmask.test(mscEvent)
796 : false;
797}
798
Michael Wrightd02c5b62014-02-10 15:10:22 -0800799int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
800 if (scanCode >= 0 && scanCode <= KEY_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000801 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800802
803 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700804 if (device != nullptr && device->hasValidFd() && device->keyBitmask.test(scanCode)) {
805 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
806 return device->keyState.test(scanCode) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800807 }
808 }
809 }
810 return AKEY_STATE_UNKNOWN;
811}
812
813int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
Chris Ye87143712020-11-10 05:05:58 +0000814 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800815
816 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700817 if (device != nullptr && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800818 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800819 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode, &scanCodes);
820 if (scanCodes.size() != 0) {
Chris Ye66fbac32020-07-06 20:36:43 -0700821 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800822 for (size_t i = 0; i < scanCodes.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800823 int32_t sc = scanCodes[i];
Chris Ye66fbac32020-07-06 20:36:43 -0700824 if (sc >= 0 && sc <= KEY_MAX && device->keyState.test(sc)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800825 return AKEY_STATE_DOWN;
826 }
827 }
828 return AKEY_STATE_UP;
829 }
830 }
831 }
832 return AKEY_STATE_UNKNOWN;
833}
834
835int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
836 if (sw >= 0 && sw <= SW_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000837 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800838
839 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700840 if (device != nullptr && device->hasValidFd() && device->swBitmask.test(sw)) {
841 if (device->readDeviceBitMask(EVIOCGSW(0), device->swState) >= 0) {
842 return device->swState.test(sw) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800843 }
844 }
845 }
846 return AKEY_STATE_UNKNOWN;
847}
848
849status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
850 *outValue = 0;
851
852 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000853 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800854
855 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700856 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800857 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700858 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
859 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
860 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800861 return -errno;
862 }
863
864 *outValue = info.value;
865 return OK;
866 }
867 }
868 return -1;
869}
870
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700871bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes, const int32_t* keyCodes,
872 uint8_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +0000873 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874
875 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700876 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800877 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800878 for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) {
879 scanCodes.clear();
880
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700881 status_t err = device->keyMap.keyLayoutMap->findScanCodesForKey(keyCodes[codeIndex],
882 &scanCodes);
883 if (!err) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800884 // check the possible scan codes identified by the layout map against the
885 // map of codes actually emitted by the driver
886 for (size_t sc = 0; sc < scanCodes.size(); sc++) {
Chris Ye66fbac32020-07-06 20:36:43 -0700887 if (device->keyBitmask.test(scanCodes[sc])) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800888 outFlags[codeIndex] = 1;
889 break;
890 }
891 }
892 }
893 }
894 return true;
895 }
896 return false;
897}
898
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700899status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
900 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +0000901 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800902 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700903 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904
Chris Ye66fbac32020-07-06 20:36:43 -0700905 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800906 // Check the key character map first.
Chris Ye3a1e4462020-08-12 10:13:15 -0700907 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
908 if (kcm) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800909 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
910 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700911 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800912 }
913 }
914
915 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700916 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800917 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700918 status = NO_ERROR;
919 }
920 }
921
922 if (status == NO_ERROR) {
Chris Ye3a1e4462020-08-12 10:13:15 -0700923 if (kcm) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700924 kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState);
925 } else {
926 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800927 }
928 }
929 }
930
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700931 if (status != NO_ERROR) {
932 *outKeycode = 0;
933 *outFlags = 0;
934 *outMetaState = metaState;
935 }
936
937 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800938}
939
940status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
Chris Ye87143712020-11-10 05:05:58 +0000941 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800942 Device* device = getDeviceLocked(deviceId);
943
Chris Ye66fbac32020-07-06 20:36:43 -0700944 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800945 status_t err = device->keyMap.keyLayoutMap->mapAxis(scanCode, outAxisInfo);
946 if (err == NO_ERROR) {
947 return NO_ERROR;
948 }
949 }
950
951 return NAME_NOT_FOUND;
952}
953
Chris Yef59a2f42020-10-16 12:55:26 -0700954base::Result<std::pair<InputDeviceSensorType, int32_t>> EventHub::mapSensor(int32_t deviceId,
955 int32_t absCode) {
956 std::scoped_lock _l(mLock);
957 Device* device = getDeviceLocked(deviceId);
958
959 if (device != nullptr && device->keyMap.haveKeyLayout()) {
960 return device->keyMap.keyLayoutMap->mapSensor(absCode);
961 }
962 return Errorf("Device not found or device has no key layout.");
963}
964
Chris Ye3fdbfef2021-01-06 18:45:18 -0800965const std::vector<int32_t> EventHub::getRawLightIds(int32_t deviceId) {
966 std::scoped_lock _l(mLock);
967 Device* device = getDeviceLocked(deviceId);
968 std::vector<int32_t> lightIds;
969
970 if (device != nullptr) {
971 for (const auto [id, info] : device->lightInfos) {
972 lightIds.push_back(id);
973 }
974 }
975 return lightIds;
976}
977
978std::optional<RawLightInfo> EventHub::getRawLightInfo(int32_t deviceId, int32_t lightId) {
979 std::scoped_lock _l(mLock);
980 Device* device = getDeviceLocked(deviceId);
981
982 if (device != nullptr) {
983 auto it = device->lightInfos.find(lightId);
984 if (it != device->lightInfos.end()) {
985 return it->second;
986 }
987 }
988 return std::nullopt;
989}
990
991std::optional<int32_t> EventHub::getLightBrightness(int32_t deviceId, int32_t lightId) {
992 std::scoped_lock _l(mLock);
993
994 Device* device = getDeviceLocked(deviceId);
995 if (device == nullptr) {
996 return std::nullopt;
997 }
998
999 auto it = device->lightInfos.find(lightId);
1000 if (it == device->lightInfos.end()) {
1001 return std::nullopt;
1002 }
1003 std::string buffer;
1004 if (!base::ReadFileToString(it->second.path / LIGHT_NODES.at(InputLightClass::BRIGHTNESS),
1005 &buffer)) {
1006 return std::nullopt;
1007 }
1008 return std::stoi(buffer);
1009}
1010
1011std::optional<std::unordered_map<LightColor, int32_t>> EventHub::getLightIntensities(
1012 int32_t deviceId, int32_t lightId) {
1013 std::scoped_lock _l(mLock);
1014
1015 Device* device = getDeviceLocked(deviceId);
1016 if (device == nullptr) {
1017 return std::nullopt;
1018 }
1019
1020 auto lightIt = device->lightInfos.find(lightId);
1021 if (lightIt == device->lightInfos.end()) {
1022 return std::nullopt;
1023 }
1024
1025 auto ret =
1026 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1027
1028 if (!ret.has_value()) {
1029 return std::nullopt;
1030 }
1031 std::array<LightColor, COLOR_NUM> colors = ret.value();
1032
1033 std::string intensityStr;
1034 if (!base::ReadFileToString(lightIt->second.path /
1035 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY),
1036 &intensityStr)) {
1037 return std::nullopt;
1038 }
1039
1040 // Intensity node outputs 3 color values
1041 std::regex intensityPattern("([0-9]+)\\s([0-9]+)\\s([0-9]+)[\\n]");
1042 std::smatch results;
1043
1044 if (!std::regex_match(intensityStr, results, intensityPattern)) {
1045 return std::nullopt;
1046 }
1047 std::unordered_map<LightColor, int32_t> intensities;
1048 for (size_t i = 1; i < results.size(); i++) {
1049 int value = std::stoi(results[i].str());
1050 intensities.emplace(colors[i - 1], value);
1051 }
1052 return intensities;
1053}
1054
1055void EventHub::setLightBrightness(int32_t deviceId, int32_t lightId, int32_t brightness) {
1056 std::scoped_lock _l(mLock);
1057
1058 Device* device = getDeviceLocked(deviceId);
1059 if (device == nullptr) {
1060 ALOGE("Device Id %d does not exist", deviceId);
1061 return;
1062 }
1063 auto lightIt = device->lightInfos.find(lightId);
1064 if (lightIt == device->lightInfos.end()) {
1065 ALOGE("Light Id %d does not exist.", lightId);
1066 return;
1067 }
1068
1069 if (!base::WriteStringToFile(std::to_string(brightness),
1070 lightIt->second.path /
1071 LIGHT_NODES.at(InputLightClass::BRIGHTNESS))) {
1072 ALOGE("Can not write to file, error: %s", strerror(errno));
1073 }
1074}
1075
1076void EventHub::setLightIntensities(int32_t deviceId, int32_t lightId,
1077 std::unordered_map<LightColor, int32_t> intensities) {
1078 std::scoped_lock _l(mLock);
1079
1080 Device* device = getDeviceLocked(deviceId);
1081 if (device == nullptr) {
1082 ALOGE("Device Id %d does not exist", deviceId);
1083 return;
1084 }
1085 auto lightIt = device->lightInfos.find(lightId);
1086 if (lightIt == device->lightInfos.end()) {
1087 ALOGE("Light Id %d does not exist.", lightId);
1088 return;
1089 }
1090
1091 auto ret =
1092 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1093
1094 if (!ret.has_value()) {
1095 return;
1096 }
1097 std::array<LightColor, COLOR_NUM> colors = ret.value();
1098
1099 std::string rgbStr;
1100 for (size_t i = 0; i < COLOR_NUM; i++) {
1101 auto it = intensities.find(colors[i]);
1102 if (it != intensities.end()) {
1103 rgbStr += std::to_string(it->second);
1104 // Insert space between colors
1105 if (i < COLOR_NUM - 1) {
1106 rgbStr += " ";
1107 }
1108 }
1109 }
1110 // Append new line
1111 rgbStr += "\n";
1112
1113 if (!base::WriteStringToFile(rgbStr,
1114 lightIt->second.path /
1115 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY))) {
1116 ALOGE("Can not write to file, error: %s", strerror(errno));
1117 }
1118}
1119
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001120void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Chris Ye87143712020-11-10 05:05:58 +00001121 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001122
1123 mExcludedDevices = devices;
1124}
1125
1126bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
Chris Ye87143712020-11-10 05:05:58 +00001127 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001128 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001129 if (device != nullptr && scanCode >= 0 && scanCode <= KEY_MAX) {
1130 return device->keyBitmask.test(scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001131 }
1132 return false;
1133}
1134
1135bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
Chris Ye87143712020-11-10 05:05:58 +00001136 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001137 Device* device = getDeviceLocked(deviceId);
1138 int32_t sc;
Chris Ye989bb932020-07-04 16:18:59 -07001139 if (device != nullptr && device->mapLed(led, &sc) == NO_ERROR) {
Chris Ye66fbac32020-07-06 20:36:43 -07001140 return device->ledBitmask.test(sc);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001141 }
1142 return false;
1143}
1144
1145void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
Chris Ye87143712020-11-10 05:05:58 +00001146 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001147 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -07001148 if (device != nullptr && device->hasValidFd()) {
1149 device->setLedStateLocked(led, on);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001150 }
1151}
1152
1153void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001154 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001155 outVirtualKeys.clear();
1156
Chris Ye87143712020-11-10 05:05:58 +00001157 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001158 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001159 if (device != nullptr && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001160 const std::vector<VirtualKeyDefinition> virtualKeys =
1161 device->virtualKeyMap->getVirtualKeys();
1162 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001163 }
1164}
1165
Chris Ye3a1e4462020-08-12 10:13:15 -07001166const std::shared_ptr<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001167 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001168 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001169 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001170 return device->getKeyCharacterMap();
1171 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001172 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001173}
1174
Chris Ye3a1e4462020-08-12 10:13:15 -07001175bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, std::shared_ptr<KeyCharacterMap> map) {
Chris Ye87143712020-11-10 05:05:58 +00001176 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001177 Device* device = getDeviceLocked(deviceId);
Chris Ye3a1e4462020-08-12 10:13:15 -07001178 if (device != nullptr && map != nullptr && device->keyMap.keyCharacterMap != nullptr) {
1179 device->keyMap.keyCharacterMap->combine(*map);
1180 device->keyMap.keyCharacterMapFile = device->keyMap.keyCharacterMap->getLoadFileName();
1181 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001182 }
1183 return false;
1184}
1185
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001186static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
1187 std::string rawDescriptor;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001188 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001189 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001190 if (!identifier.uniqueId.empty()) {
1191 rawDescriptor += "uniqueId:";
1192 rawDescriptor += identifier.uniqueId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001193 } else if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001194 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001195 }
1196
1197 if (identifier.vendor == 0 && identifier.product == 0) {
1198 // If we don't know the vendor and product id, then the device is probably
1199 // built-in so we need to rely on other information to uniquely identify
1200 // the input device. Usually we try to avoid relying on the device name or
1201 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001202 if (!identifier.name.empty()) {
1203 rawDescriptor += "name:";
1204 rawDescriptor += identifier.name;
1205 } else if (!identifier.location.empty()) {
1206 rawDescriptor += "location:";
1207 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001208 }
1209 }
1210 identifier.descriptor = sha1(rawDescriptor);
1211 return rawDescriptor;
1212}
1213
1214void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
1215 // Compute a device descriptor that uniquely identifies the device.
1216 // The descriptor is assumed to be a stable identifier. Its value should not
1217 // change between reboots, reconnections, firmware updates or new releases
1218 // of Android. In practice we sometimes get devices that cannot be uniquely
1219 // identified. In this case we enforce uniqueness between connected devices.
1220 // Ideally, we also want the descriptor to be short and relatively opaque.
1221
1222 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001223 std::string rawDescriptor = generateDescriptor(identifier);
1224 if (identifier.uniqueId.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001225 // If it didn't have a unique id check for conflicts and enforce
1226 // uniqueness if necessary.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001227 while (getDeviceByDescriptorLocked(identifier.descriptor) != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228 identifier.nonce++;
1229 rawDescriptor = generateDescriptor(identifier);
1230 }
1231 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001232 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001233 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001234}
1235
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001236void EventHub::vibrate(int32_t deviceId, const VibrationElement& element) {
Chris Ye87143712020-11-10 05:05:58 +00001237 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001238 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001239 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001240 ff_effect effect;
1241 memset(&effect, 0, sizeof(effect));
1242 effect.type = FF_RUMBLE;
1243 effect.id = device->ffEffectId;
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001244 // evdev FF_RUMBLE effect only supports two channels of vibration.
Chris Ye6393a262020-08-04 19:41:36 -07001245 effect.u.rumble.strong_magnitude = element.getMagnitude(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1246 effect.u.rumble.weak_magnitude = element.getMagnitude(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001247 effect.replay.length = element.duration.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001248 effect.replay.delay = 0;
1249 if (ioctl(device->fd, EVIOCSFF, &effect)) {
1250 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001251 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001252 return;
1253 }
1254 device->ffEffectId = effect.id;
1255
1256 struct input_event ev;
1257 ev.time.tv_sec = 0;
1258 ev.time.tv_usec = 0;
1259 ev.type = EV_FF;
1260 ev.code = device->ffEffectId;
1261 ev.value = 1;
1262 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1263 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001264 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001265 return;
1266 }
1267 device->ffEffectPlaying = true;
1268 }
1269}
1270
1271void EventHub::cancelVibrate(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001272 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001273 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001274 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001275 if (device->ffEffectPlaying) {
1276 device->ffEffectPlaying = false;
1277
1278 struct input_event ev;
1279 ev.time.tv_sec = 0;
1280 ev.time.tv_usec = 0;
1281 ev.type = EV_FF;
1282 ev.code = device->ffEffectId;
1283 ev.value = 0;
1284 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1285 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001286 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001287 return;
1288 }
1289 }
1290 }
1291}
1292
Chris Ye87143712020-11-10 05:05:58 +00001293std::vector<int32_t> EventHub::getVibratorIds(int32_t deviceId) {
1294 std::scoped_lock _l(mLock);
1295 std::vector<int32_t> vibrators;
1296 Device* device = getDeviceLocked(deviceId);
1297 if (device != nullptr && device->hasValidFd() &&
1298 device->classes.test(InputDeviceClass::VIBRATOR)) {
1299 vibrators.push_back(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1300 vibrators.push_back(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
1301 }
1302 return vibrators;
1303}
1304
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001305EventHub::Device* EventHub::getDeviceByDescriptorLocked(const std::string& descriptor) const {
Chris Ye989bb932020-07-04 16:18:59 -07001306 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001307 if (descriptor == device->identifier.descriptor) {
Chris Ye989bb932020-07-04 16:18:59 -07001308 return device.get();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001309 }
1310 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001311 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001312}
1313
1314EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001315 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001316 deviceId = mBuiltInKeyboardId;
1317 }
Chris Ye989bb932020-07-04 16:18:59 -07001318 const auto& it = mDevices.find(deviceId);
1319 return it != mDevices.end() ? it->second.get() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001320}
1321
Chris Ye8594e192020-07-14 10:34:06 -07001322EventHub::Device* EventHub::getDeviceByPathLocked(const std::string& devicePath) const {
Chris Ye989bb932020-07-04 16:18:59 -07001323 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001324 if (device->path == devicePath) {
Chris Ye989bb932020-07-04 16:18:59 -07001325 return device.get();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001326 }
1327 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001328 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001329}
1330
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001331/**
1332 * The file descriptor could be either input device, or a video device (associated with a
1333 * specific input device). Check both cases here, and return the device that this event
1334 * belongs to. Caller can compare the fd's once more to determine event type.
1335 * Looks through all input devices, and only attached video devices. Unattached video
1336 * devices are ignored.
1337 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001338EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
Chris Ye989bb932020-07-04 16:18:59 -07001339 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001340 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001341 // This is an input device event
Chris Ye989bb932020-07-04 16:18:59 -07001342 return device.get();
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001343 }
1344 if (device->videoDevice && device->videoDevice->getFd() == fd) {
1345 // This is a video device event
Chris Ye989bb932020-07-04 16:18:59 -07001346 return device.get();
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001347 }
1348 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001349 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
1350 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001351 return nullptr;
1352}
1353
Kim Low03ea0352020-11-06 12:45:07 -08001354std::optional<int32_t> EventHub::getBatteryCapacity(int32_t deviceId) const {
1355 std::scoped_lock _l(mLock);
1356 Device* device = getDeviceLocked(deviceId);
1357 std::string buffer;
1358
Chris Ye3fdbfef2021-01-06 18:45:18 -08001359 if (device == nullptr || !device->sysfsBatteryPath.has_value()) {
Kim Low03ea0352020-11-06 12:45:07 -08001360 return std::nullopt;
1361 }
1362
1363 // Some devices report battery capacity as an integer through the "capacity" file
Chris Ye3fdbfef2021-01-06 18:45:18 -08001364 if (base::ReadFileToString(device->sysfsBatteryPath.value() / "capacity", &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001365 return std::stoi(base::Trim(buffer));
Kim Low03ea0352020-11-06 12:45:07 -08001366 }
1367
1368 // Other devices report capacity as an enum value POWER_SUPPLY_CAPACITY_LEVEL_XXX
1369 // These values are taken from kernel source code include/linux/power_supply.h
Chris Ye3fdbfef2021-01-06 18:45:18 -08001370 if (base::ReadFileToString(device->sysfsBatteryPath.value() / "capacity_level", &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001371 // Remove any white space such as trailing new line
1372 const auto it = BATTERY_LEVEL.find(base::Trim(buffer));
Kim Low03ea0352020-11-06 12:45:07 -08001373 if (it != BATTERY_LEVEL.end()) {
1374 return it->second;
1375 }
1376 }
1377 return std::nullopt;
1378}
1379
1380std::optional<int32_t> EventHub::getBatteryStatus(int32_t deviceId) const {
1381 std::scoped_lock _l(mLock);
1382 Device* device = getDeviceLocked(deviceId);
1383 std::string buffer;
1384
Chris Ye3fdbfef2021-01-06 18:45:18 -08001385 if (device == nullptr || !device->sysfsBatteryPath.has_value()) {
Kim Low03ea0352020-11-06 12:45:07 -08001386 return std::nullopt;
1387 }
1388
Chris Ye3fdbfef2021-01-06 18:45:18 -08001389 if (!base::ReadFileToString(device->sysfsBatteryPath.value() / "status", &buffer)) {
Kim Low03ea0352020-11-06 12:45:07 -08001390 ALOGE("Failed to read sysfs battery info: %s", strerror(errno));
1391 return std::nullopt;
1392 }
1393
Chris Yed1936772021-02-22 10:30:40 -08001394 // Remove white space like trailing new line
1395 const auto it = BATTERY_STATUS.find(base::Trim(buffer));
Kim Low03ea0352020-11-06 12:45:07 -08001396
1397 if (it != BATTERY_STATUS.end()) {
1398 return it->second;
1399 }
1400
1401 return std::nullopt;
1402}
1403
Michael Wrightd02c5b62014-02-10 15:10:22 -08001404size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
1405 ALOG_ASSERT(bufferSize >= 1);
1406
Chris Ye87143712020-11-10 05:05:58 +00001407 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001408
1409 struct input_event readBuffer[bufferSize];
1410
1411 RawEvent* event = buffer;
1412 size_t capacity = bufferSize;
1413 bool awoken = false;
1414 for (;;) {
1415 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
1416
1417 // Reopen input devices if needed.
1418 if (mNeedToReopenDevices) {
1419 mNeedToReopenDevices = false;
1420
1421 ALOGI("Reopening all input devices due to a configuration change.");
1422
1423 closeAllDevicesLocked();
1424 mNeedToScanDevices = true;
1425 break; // return to the caller before we actually rescan
1426 }
1427
1428 // Report any devices that had last been added/removed.
Chris Ye989bb932020-07-04 16:18:59 -07001429 for (auto it = mClosingDevices.begin(); it != mClosingDevices.end();) {
1430 std::unique_ptr<Device> device = std::move(*it);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001431 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001432 event->when = now;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001433 event->deviceId = (device->id == mBuiltInKeyboardId)
1434 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
1435 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001436 event->type = DEVICE_REMOVED;
1437 event += 1;
Chris Ye989bb932020-07-04 16:18:59 -07001438 it = mClosingDevices.erase(it);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001439 mNeedToSendFinishedDeviceScan = true;
1440 if (--capacity == 0) {
1441 break;
1442 }
1443 }
1444
1445 if (mNeedToScanDevices) {
1446 mNeedToScanDevices = false;
1447 scanDevicesLocked();
1448 mNeedToSendFinishedDeviceScan = true;
1449 }
1450
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001451 while (!mOpeningDevices.empty()) {
1452 std::unique_ptr<Device> device = std::move(*mOpeningDevices.rbegin());
1453 mOpeningDevices.pop_back();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001454 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001455 event->when = now;
1456 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1457 event->type = DEVICE_ADDED;
1458 event += 1;
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001459
1460 // Try to find a matching video device by comparing device names
1461 for (auto it = mUnattachedVideoDevices.begin(); it != mUnattachedVideoDevices.end();
1462 it++) {
1463 std::unique_ptr<TouchVideoDevice>& videoDevice = *it;
1464 if (tryAddVideoDevice(*device, videoDevice)) {
1465 // videoDevice was transferred to 'device'
1466 it = mUnattachedVideoDevices.erase(it);
1467 break;
1468 }
1469 }
1470
1471 auto [dev_it, inserted] = mDevices.insert_or_assign(device->id, std::move(device));
1472 if (!inserted) {
Chris Ye989bb932020-07-04 16:18:59 -07001473 ALOGW("Device id %d exists, replaced.", device->id);
1474 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001475 mNeedToSendFinishedDeviceScan = true;
1476 if (--capacity == 0) {
1477 break;
1478 }
1479 }
1480
1481 if (mNeedToSendFinishedDeviceScan) {
1482 mNeedToSendFinishedDeviceScan = false;
1483 event->when = now;
1484 event->type = FINISHED_DEVICE_SCAN;
1485 event += 1;
1486 if (--capacity == 0) {
1487 break;
1488 }
1489 }
1490
1491 // Grab the next input event.
1492 bool deviceChanged = false;
1493 while (mPendingEventIndex < mPendingEventCount) {
1494 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001495 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001496 if (eventItem.events & EPOLLIN) {
1497 mPendingINotify = true;
1498 } else {
1499 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
1500 }
1501 continue;
1502 }
1503
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001504 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001505 if (eventItem.events & EPOLLIN) {
1506 ALOGV("awoken after wake()");
1507 awoken = true;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001508 char wakeReadBuffer[16];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001509 ssize_t nRead;
1510 do {
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001511 nRead = read(mWakeReadPipeFd, wakeReadBuffer, sizeof(wakeReadBuffer));
1512 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(wakeReadBuffer));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001513 } else {
1514 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001515 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001516 }
1517 continue;
1518 }
1519
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001520 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Chris Ye989bb932020-07-04 16:18:59 -07001521 if (device == nullptr) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001522 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
1523 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001524 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001525 continue;
1526 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001527 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
1528 if (eventItem.events & EPOLLIN) {
1529 size_t numFrames = device->videoDevice->readAndQueueFrames();
1530 if (numFrames == 0) {
1531 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001532 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001533 }
1534 } else if (eventItem.events & EPOLLHUP) {
1535 // TODO(b/121395353) - consider adding EPOLLRDHUP
1536 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001537 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001538 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1539 device->videoDevice = nullptr;
1540 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001541 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1542 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001543 ALOG_ASSERT(!DEBUG);
1544 }
1545 continue;
1546 }
1547 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -08001548 if (eventItem.events & EPOLLIN) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001549 int32_t readSize =
1550 read(device->fd, readBuffer, sizeof(struct input_event) * capacity);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001551 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
1552 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -07001553 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001554 " bufferSize: %zu capacity: %zu errno: %d)\n",
1555 device->fd, readSize, bufferSize, capacity, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001556 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001557 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001558 } else if (readSize < 0) {
1559 if (errno != EAGAIN && errno != EINTR) {
1560 ALOGW("could not get event (errno=%d)", errno);
1561 }
1562 } else if ((readSize % sizeof(struct input_event)) != 0) {
1563 ALOGE("could not get event (wrong size: %d)", readSize);
1564 } else {
1565 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1566
1567 size_t count = size_t(readSize) / sizeof(struct input_event);
1568 for (size_t i = 0; i < count; i++) {
1569 struct input_event& iev = readBuffer[i];
Siarhei Vishniakou592bac22018-11-08 19:42:38 -08001570 event->when = processEventTimestamp(iev);
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001571 event->readTime = systemTime(SYSTEM_TIME_MONOTONIC);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001572 event->deviceId = deviceId;
1573 event->type = iev.type;
1574 event->code = iev.code;
1575 event->value = iev.value;
1576 event += 1;
1577 capacity -= 1;
1578 }
1579 if (capacity == 0) {
1580 // The result buffer is full. Reset the pending event index
1581 // so we will try to read the device again on the next iteration.
1582 mPendingEventIndex -= 1;
1583 break;
1584 }
1585 }
1586 } else if (eventItem.events & EPOLLHUP) {
1587 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001588 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001589 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001590 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001591 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001592 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1593 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001594 }
1595 }
1596
1597 // readNotify() will modify the list of devices so this must be done after
1598 // processing all other events to ensure that we read all remaining events
1599 // before closing the devices.
1600 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
1601 mPendingINotify = false;
1602 readNotifyLocked();
1603 deviceChanged = true;
1604 }
1605
1606 // Report added or removed devices immediately.
1607 if (deviceChanged) {
1608 continue;
1609 }
1610
1611 // Return now if we have collected any events or if we were explicitly awoken.
1612 if (event != buffer || awoken) {
1613 break;
1614 }
1615
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001616 // Poll for events.
1617 // When a device driver has pending (unread) events, it acquires
1618 // a kernel wake lock. Once the last pending event has been read, the device
1619 // driver will release the kernel wake lock, but the epoll will hold the wakelock,
1620 // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
1621 // is called again for the same fd that produced the event.
1622 // Thus the system can only sleep if there are no events pending or
1623 // currently being processed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001624 //
1625 // The timeout is advisory only. If the device is asleep, it will not wake just to
1626 // service the timeout.
1627 mPendingEventIndex = 0;
1628
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001629 mLock.unlock(); // release lock before poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001630
1631 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1632
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001633 mLock.lock(); // reacquire lock after poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001634
1635 if (pollResult == 0) {
1636 // Timed out.
1637 mPendingEventCount = 0;
1638 break;
1639 }
1640
1641 if (pollResult < 0) {
1642 // An error occurred.
1643 mPendingEventCount = 0;
1644
1645 // Sleep after errors to avoid locking up the system.
1646 // Hopefully the error is transient.
1647 if (errno != EINTR) {
1648 ALOGW("poll failed (errno=%d)\n", errno);
1649 usleep(100000);
1650 }
1651 } else {
1652 // Some events occurred.
1653 mPendingEventCount = size_t(pollResult);
1654 }
1655 }
1656
1657 // All done, return the number of events we read.
1658 return event - buffer;
1659}
1660
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001661std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001662 std::scoped_lock _l(mLock);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001663
1664 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001665 if (device == nullptr || !device->videoDevice) {
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001666 return {};
1667 }
1668 return device->videoDevice->consumeFrames();
1669}
1670
Michael Wrightd02c5b62014-02-10 15:10:22 -08001671void EventHub::wake() {
1672 ALOGV("wake() called");
1673
1674 ssize_t nWrite;
1675 do {
1676 nWrite = write(mWakeWritePipeFd, "W", 1);
1677 } while (nWrite == -1 && errno == EINTR);
1678
1679 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001680 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001681 }
1682}
1683
1684void EventHub::scanDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001685 status_t result = scanDirLocked(DEVICE_PATH);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001686 if (result < 0) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001687 ALOGE("scan dir failed for %s", DEVICE_PATH);
1688 }
Philip Quinn39b81682019-01-09 22:20:39 -08001689 if (isV4lScanningEnabled()) {
1690 result = scanVideoDirLocked(VIDEO_DEVICE_PATH);
1691 if (result != OK) {
1692 ALOGE("scan video dir failed for %s", VIDEO_DEVICE_PATH);
1693 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001694 }
Chris Ye989bb932020-07-04 16:18:59 -07001695 if (mDevices.find(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) == mDevices.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001696 createVirtualKeyboardLocked();
1697 }
1698}
1699
1700// ----------------------------------------------------------------------------
1701
Michael Wrightd02c5b62014-02-10 15:10:22 -08001702static const int32_t GAMEPAD_KEYCODES[] = {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001703 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C, //
1704 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z, //
1705 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1, //
1706 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2, //
1707 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR, //
1708 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE, //
Michael Wrightd02c5b62014-02-10 15:10:22 -08001709};
1710
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001711status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001712 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001713 struct epoll_event eventItem = {};
1714 eventItem.events = EPOLLIN | EPOLLWAKEUP;
1715 eventItem.data.fd = fd;
1716 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1717 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001718 return -errno;
1719 }
1720 return OK;
1721}
1722
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001723status_t EventHub::unregisterFdFromEpoll(int fd) {
1724 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
1725 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
1726 return -errno;
1727 }
1728 return OK;
1729}
1730
Chris Ye989bb932020-07-04 16:18:59 -07001731status_t EventHub::registerDeviceForEpollLocked(Device& device) {
1732 status_t result = registerFdForEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001733 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07001734 ALOGE("Could not add input device fd to epoll for device %" PRId32, device.id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001735 return result;
1736 }
Chris Ye989bb932020-07-04 16:18:59 -07001737 if (device.videoDevice) {
1738 registerVideoDeviceForEpollLocked(*device.videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001739 }
1740 return result;
1741}
1742
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001743void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
1744 status_t result = registerFdForEpoll(videoDevice.getFd());
1745 if (result != OK) {
1746 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
1747 }
1748}
1749
Chris Ye989bb932020-07-04 16:18:59 -07001750status_t EventHub::unregisterDeviceFromEpollLocked(Device& device) {
1751 if (device.hasValidFd()) {
1752 status_t result = unregisterFdFromEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001753 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07001754 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device.id);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001755 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001756 }
1757 }
Chris Ye989bb932020-07-04 16:18:59 -07001758 if (device.videoDevice) {
1759 unregisterVideoDeviceFromEpollLocked(*device.videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001760 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001761 return OK;
1762}
1763
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001764void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
1765 if (videoDevice.hasValidFd()) {
1766 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
1767 if (result != OK) {
1768 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001769 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001770 }
1771 }
1772}
1773
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00001774void EventHub::openDeviceLocked(const std::string& devicePath) {
1775 // If an input device happens to register around the time when EventHub's constructor runs, it
1776 // is possible that the same input event node (for example, /dev/input/event3) will be noticed
1777 // in both 'inotify' callback and also in the 'scanDirLocked' pass. To prevent duplicate devices
1778 // from getting registered, ensure that this path is not already covered by an existing device.
1779 for (const auto& [deviceId, device] : mDevices) {
1780 if (device->path == devicePath) {
1781 return; // device was already registered
1782 }
1783 }
1784
Michael Wrightd02c5b62014-02-10 15:10:22 -08001785 char buffer[80];
1786
Chris Ye8594e192020-07-14 10:34:06 -07001787 ALOGV("Opening device: %s", devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001788
Chris Ye8594e192020-07-14 10:34:06 -07001789 int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001790 if (fd < 0) {
Chris Ye8594e192020-07-14 10:34:06 -07001791 ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00001792 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001793 }
1794
1795 InputDeviceIdentifier identifier;
1796
1797 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001798 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Chris Ye8594e192020-07-14 10:34:06 -07001799 ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001800 } else {
1801 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001802 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001803 }
1804
1805 // Check to see if the device is on our excluded list
1806 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001807 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001808 if (identifier.name == item) {
Chris Ye8594e192020-07-14 10:34:06 -07001809 ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001810 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00001811 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001812 }
1813 }
1814
1815 // Get device driver version.
1816 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001817 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Chris Ye8594e192020-07-14 10:34:06 -07001818 ALOGE("could not get driver version for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001819 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00001820 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001821 }
1822
1823 // Get device identifier.
1824 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001825 if (ioctl(fd, EVIOCGID, &inputId)) {
Chris Ye8594e192020-07-14 10:34:06 -07001826 ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001827 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00001828 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001829 }
1830 identifier.bus = inputId.bustype;
1831 identifier.product = inputId.product;
1832 identifier.vendor = inputId.vendor;
1833 identifier.version = inputId.version;
1834
1835 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001836 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
1837 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001838 } else {
1839 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001840 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001841 }
1842
1843 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001844 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
1845 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001846 } else {
1847 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001848 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001849 }
1850
1851 // Fill in the descriptor.
1852 assignDescriptorLocked(identifier);
1853
Michael Wrightd02c5b62014-02-10 15:10:22 -08001854 // Allocate device. (The device object takes ownership of the fd at this point.)
1855 int32_t deviceId = mNextDeviceId++;
Chris Ye989bb932020-07-04 16:18:59 -07001856 std::unique_ptr<Device> device = std::make_unique<Device>(fd, deviceId, devicePath, identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001857
Chris Ye8594e192020-07-14 10:34:06 -07001858 ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001859 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001860 " vendor %04x\n"
1861 " product %04x\n"
1862 " version %04x\n",
1863 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001864 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
1865 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
1866 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
1867 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001868 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
1869 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001870
1871 // Load the configuration file for the device.
Chris Ye989bb932020-07-04 16:18:59 -07001872 device->loadConfigurationLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001873
Chris Ye3fdbfef2021-01-06 18:45:18 -08001874 // Grab the device's sysfs path
1875 device->sysfsRootPath = getSysfsRootPath(devicePath.c_str());
1876 // find related components
1877 bool hasBattery = device->configureBatteryLocked();
1878 bool hasLights = device->configureLightsLocked();
1879
Michael Wrightd02c5b62014-02-10 15:10:22 -08001880 // Figure out the kinds of events the device reports.
Chris Ye66fbac32020-07-06 20:36:43 -07001881 device->readDeviceBitMask(EVIOCGBIT(EV_KEY, 0), device->keyBitmask);
1882 device->readDeviceBitMask(EVIOCGBIT(EV_ABS, 0), device->absBitmask);
1883 device->readDeviceBitMask(EVIOCGBIT(EV_REL, 0), device->relBitmask);
1884 device->readDeviceBitMask(EVIOCGBIT(EV_SW, 0), device->swBitmask);
1885 device->readDeviceBitMask(EVIOCGBIT(EV_LED, 0), device->ledBitmask);
1886 device->readDeviceBitMask(EVIOCGBIT(EV_FF, 0), device->ffBitmask);
Chris Yef59a2f42020-10-16 12:55:26 -07001887 device->readDeviceBitMask(EVIOCGBIT(EV_MSC, 0), device->mscBitmask);
Chris Ye66fbac32020-07-06 20:36:43 -07001888 device->readDeviceBitMask(EVIOCGPROP(0), device->propBitmask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001889
1890 // See if this is a keyboard. Ignore everything in the button range except for
1891 // joystick and gamepad buttons which are handled like keyboards for the most part.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001892 bool haveKeyboardKeys =
Chris Ye66fbac32020-07-06 20:36:43 -07001893 device->keyBitmask.any(0, BTN_MISC) || device->keyBitmask.any(BTN_WHEEL, KEY_MAX + 1);
1894 bool haveGamepadButtons = device->keyBitmask.any(BTN_MISC, BTN_MOUSE) ||
1895 device->keyBitmask.any(BTN_JOYSTICK, BTN_DIGI);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001896 if (haveKeyboardKeys || haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001897 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001898 }
1899
1900 // See if this is a cursor device such as a trackball or mouse.
Chris Ye66fbac32020-07-06 20:36:43 -07001901 if (device->keyBitmask.test(BTN_MOUSE) && device->relBitmask.test(REL_X) &&
1902 device->relBitmask.test(REL_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001903 device->classes |= InputDeviceClass::CURSOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001904 }
1905
Prashant Malani1941ff52015-08-11 18:29:28 -07001906 // See if this is a rotary encoder type device.
1907 String8 deviceType = String8();
1908 if (device->configuration &&
1909 device->configuration->tryGetProperty(String8("device.type"), deviceType)) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001910 if (!deviceType.compare(String8("rotaryEncoder"))) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001911 device->classes |= InputDeviceClass::ROTARY_ENCODER;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001912 }
Prashant Malani1941ff52015-08-11 18:29:28 -07001913 }
1914
Michael Wrightd02c5b62014-02-10 15:10:22 -08001915 // See if this is a touch pad.
1916 // Is this a new modern multi-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07001917 if (device->absBitmask.test(ABS_MT_POSITION_X) && device->absBitmask.test(ABS_MT_POSITION_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001918 // Some joysticks such as the PS3 controller report axes that conflict
1919 // with the ABS_MT range. Try to confirm that the device really is
1920 // a touch screen.
Chris Ye66fbac32020-07-06 20:36:43 -07001921 if (device->keyBitmask.test(BTN_TOUCH) || !haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001922 device->classes |= (InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001923 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001924 // Is this an old style single-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07001925 } else if (device->keyBitmask.test(BTN_TOUCH) && device->absBitmask.test(ABS_X) &&
1926 device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001927 device->classes |= InputDeviceClass::TOUCH;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001928 // Is this a BT stylus?
Chris Ye66fbac32020-07-06 20:36:43 -07001929 } else if ((device->absBitmask.test(ABS_PRESSURE) || device->keyBitmask.test(BTN_TOUCH)) &&
1930 !device->absBitmask.test(ABS_X) && !device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001931 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -07001932 // Keyboard will try to claim some of the buttons but we really want to reserve those so we
1933 // can fuse it with the touch screen data, so just take them back. Note this means an
1934 // external stylus cannot also be a keyboard device.
Chris Ye1b0c7342020-07-28 21:57:03 -07001935 device->classes &= ~InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001936 }
1937
1938 // See if this device is a joystick.
1939 // Assumes that joysticks always have gamepad buttons in order to distinguish them
1940 // from other devices such as accelerometers that also have absolute axes.
1941 if (haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001942 auto assumedClasses = device->classes | InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001943 for (int i = 0; i <= ABS_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07001944 if (device->absBitmask.test(i) &&
Chris Ye1b0c7342020-07-28 21:57:03 -07001945 (getAbsAxisUsage(i, assumedClasses).test(InputDeviceClass::JOYSTICK))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001946 device->classes = assumedClasses;
1947 break;
1948 }
1949 }
1950 }
1951
Chris Yef59a2f42020-10-16 12:55:26 -07001952 // Check whether this device is an accelerometer.
1953 if (device->propBitmask.test(INPUT_PROP_ACCELEROMETER)) {
1954 device->classes |= InputDeviceClass::SENSOR;
1955 }
1956
Michael Wrightd02c5b62014-02-10 15:10:22 -08001957 // Check whether this device has switches.
1958 for (int i = 0; i <= SW_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07001959 if (device->swBitmask.test(i)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001960 device->classes |= InputDeviceClass::SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001961 break;
1962 }
1963 }
1964
1965 // Check whether this device supports the vibrator.
Chris Ye66fbac32020-07-06 20:36:43 -07001966 if (device->ffBitmask.test(FF_RUMBLE)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001967 device->classes |= InputDeviceClass::VIBRATOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001968 }
1969
1970 // Configure virtual keys.
Chris Ye1b0c7342020-07-28 21:57:03 -07001971 if ((device->classes.test(InputDeviceClass::TOUCH))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001972 // Load the virtual keys for the touch screen, if any.
1973 // We do this now so that we can make sure to load the keymap if necessary.
Chris Ye989bb932020-07-04 16:18:59 -07001974 bool success = device->loadVirtualKeyMapLocked();
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001975 if (success) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001976 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001977 }
1978 }
1979
1980 // Load the key map.
Chris Yef59a2f42020-10-16 12:55:26 -07001981 // We need to do this for joysticks too because the key layout may specify axes, and for
1982 // sensor as well because the key layout may specify the axes to sensor data mapping.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001983 status_t keyMapStatus = NAME_NOT_FOUND;
Chris Yef59a2f42020-10-16 12:55:26 -07001984 if (device->classes.any(InputDeviceClass::KEYBOARD | InputDeviceClass::JOYSTICK |
1985 InputDeviceClass::SENSOR)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001986 // Load the keymap for the device.
Chris Ye989bb932020-07-04 16:18:59 -07001987 keyMapStatus = device->loadKeyMapLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001988 }
1989
1990 // Configure the keyboard, gamepad or virtual keyboard.
Chris Ye1b0c7342020-07-28 21:57:03 -07001991 if (device->classes.test(InputDeviceClass::KEYBOARD)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001992 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001993 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05001994 isEligibleBuiltInKeyboard(device->identifier, device->configuration.get(),
1995 &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001996 mBuiltInKeyboardId = device->id;
1997 }
1998
1999 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
Chris Ye989bb932020-07-04 16:18:59 -07002000 if (device->hasKeycodeLocked(AKEYCODE_Q)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002001 device->classes |= InputDeviceClass::ALPHAKEY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002002 }
2003
2004 // See if this device has a DPAD.
Chris Ye989bb932020-07-04 16:18:59 -07002005 if (device->hasKeycodeLocked(AKEYCODE_DPAD_UP) &&
2006 device->hasKeycodeLocked(AKEYCODE_DPAD_DOWN) &&
2007 device->hasKeycodeLocked(AKEYCODE_DPAD_LEFT) &&
2008 device->hasKeycodeLocked(AKEYCODE_DPAD_RIGHT) &&
2009 device->hasKeycodeLocked(AKEYCODE_DPAD_CENTER)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002010 device->classes |= InputDeviceClass::DPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002011 }
2012
2013 // See if this device has a gamepad.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002014 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES) / sizeof(GAMEPAD_KEYCODES[0]); i++) {
Chris Ye989bb932020-07-04 16:18:59 -07002015 if (device->hasKeycodeLocked(GAMEPAD_KEYCODES[i])) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002016 device->classes |= InputDeviceClass::GAMEPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002017 break;
2018 }
2019 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002020 }
2021
2022 // If the device isn't recognized as something we handle, don't monitor it.
Chris Ye1b0c7342020-07-28 21:57:03 -07002023 if (device->classes == Flags<InputDeviceClass>(0)) {
Chris Ye8594e192020-07-14 10:34:06 -07002024 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002025 device->identifier.name.c_str());
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002026 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002027 }
2028
Chris Ye3fdbfef2021-01-06 18:45:18 -08002029 // Classify InputDeviceClass::BATTERY.
2030 if (hasBattery) {
2031 device->classes |= InputDeviceClass::BATTERY;
2032 }
Kim Low03ea0352020-11-06 12:45:07 -08002033
Chris Ye3fdbfef2021-01-06 18:45:18 -08002034 // Classify InputDeviceClass::LIGHT.
2035 if (hasLights) {
2036 device->classes |= InputDeviceClass::LIGHT;
Kim Low03ea0352020-11-06 12:45:07 -08002037 }
2038
Tim Kilbourn063ff532015-04-08 10:26:18 -07002039 // Determine whether the device has a mic.
Chris Ye989bb932020-07-04 16:18:59 -07002040 if (device->deviceHasMicLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002041 device->classes |= InputDeviceClass::MIC;
Tim Kilbourn063ff532015-04-08 10:26:18 -07002042 }
2043
Michael Wrightd02c5b62014-02-10 15:10:22 -08002044 // Determine whether the device is external or internal.
Chris Ye989bb932020-07-04 16:18:59 -07002045 if (device->isExternalDeviceLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002046 device->classes |= InputDeviceClass::EXTERNAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002047 }
2048
Chris Ye1b0c7342020-07-28 21:57:03 -07002049 if (device->classes.any(InputDeviceClass::JOYSTICK | InputDeviceClass::DPAD) &&
2050 device->classes.test(InputDeviceClass::GAMEPAD)) {
Chris Ye989bb932020-07-04 16:18:59 -07002051 device->controllerNumber = getNextControllerNumberLocked(device->identifier.name);
2052 device->setLedForControllerLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002053 }
2054
Chris Ye989bb932020-07-04 16:18:59 -07002055 if (registerDeviceForEpollLocked(*device) != OK) {
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002056 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002057 }
2058
Chris Ye989bb932020-07-04 16:18:59 -07002059 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002060
Chris Ye1b0c7342020-07-28 21:57:03 -07002061 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=%s, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002062 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Chris Ye1b0c7342020-07-28 21:57:03 -07002063 deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(),
2064 device->classes.string().c_str(), device->configurationFile.c_str(),
2065 device->keyMap.keyLayoutFile.c_str(), device->keyMap.keyCharacterMapFile.c_str(),
2066 toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002067
Chris Ye989bb932020-07-04 16:18:59 -07002068 addDeviceLocked(std::move(device));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002069}
2070
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002071void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
2072 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
2073 if (!videoDevice) {
2074 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
2075 return;
2076 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002077 // Transfer ownership of this video device to a matching input device
Chris Ye989bb932020-07-04 16:18:59 -07002078 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002079 if (tryAddVideoDevice(*device, videoDevice)) {
2080 return; // 'device' now owns 'videoDevice'
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002081 }
2082 }
2083
2084 // Couldn't find a matching input device, so just add it to a temporary holding queue.
2085 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002086 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002087 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002088 mUnattachedVideoDevices.push_back(std::move(videoDevice));
2089}
2090
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002091bool EventHub::tryAddVideoDevice(EventHub::Device& device,
2092 std::unique_ptr<TouchVideoDevice>& videoDevice) {
2093 if (videoDevice->getName() != device.identifier.name) {
2094 return false;
2095 }
2096 device.videoDevice = std::move(videoDevice);
2097 if (device.enabled) {
2098 registerVideoDeviceForEpollLocked(*device.videoDevice);
2099 }
2100 return true;
2101}
2102
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002103bool EventHub::isDeviceEnabled(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002104 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002105 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002106 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002107 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2108 return false;
2109 }
2110 return device->enabled;
2111}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002112
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002113status_t EventHub::enableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002114 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002115 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002116 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002117 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2118 return BAD_VALUE;
2119 }
2120 if (device->enabled) {
2121 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
2122 return OK;
2123 }
2124 status_t result = device->enable();
2125 if (result != OK) {
2126 ALOGE("Failed to enable device %" PRId32, deviceId);
2127 return result;
2128 }
2129
Chris Ye989bb932020-07-04 16:18:59 -07002130 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002131
Chris Ye989bb932020-07-04 16:18:59 -07002132 return registerDeviceForEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002133}
2134
2135status_t EventHub::disableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002136 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002137 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002138 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002139 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2140 return BAD_VALUE;
2141 }
2142 if (!device->enabled) {
2143 ALOGW("Duplicate call to %s, input device already disabled", __func__);
2144 return OK;
2145 }
Chris Ye989bb932020-07-04 16:18:59 -07002146 unregisterDeviceFromEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002147 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002148}
2149
2150void EventHub::createVirtualKeyboardLocked() {
2151 InputDeviceIdentifier identifier;
2152 identifier.name = "Virtual";
2153 identifier.uniqueId = "<virtual>";
2154 assignDescriptorLocked(identifier);
2155
Chris Ye989bb932020-07-04 16:18:59 -07002156 std::unique_ptr<Device> device =
2157 std::make_unique<Device>(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
2158 identifier);
Chris Ye1b0c7342020-07-28 21:57:03 -07002159 device->classes = InputDeviceClass::KEYBOARD | InputDeviceClass::ALPHAKEY |
2160 InputDeviceClass::DPAD | InputDeviceClass::VIRTUAL;
Chris Ye989bb932020-07-04 16:18:59 -07002161 device->loadKeyMapLocked();
2162 addDeviceLocked(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002163}
2164
Chris Ye989bb932020-07-04 16:18:59 -07002165void EventHub::addDeviceLocked(std::unique_ptr<Device> device) {
2166 mOpeningDevices.push_back(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002167}
2168
Chris Ye989bb932020-07-04 16:18:59 -07002169int32_t EventHub::getNextControllerNumberLocked(const std::string& name) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002170 if (mControllerNumbers.isFull()) {
2171 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Chris Ye989bb932020-07-04 16:18:59 -07002172 name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002173 return 0;
2174 }
2175 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
2176 // one
2177 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
2178}
2179
Chris Ye989bb932020-07-04 16:18:59 -07002180void EventHub::releaseControllerNumberLocked(int32_t num) {
2181 if (num > 0) {
2182 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002183 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002184}
2185
Chris Ye8594e192020-07-14 10:34:06 -07002186void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002187 Device* device = getDeviceByPathLocked(devicePath);
Chris Ye989bb932020-07-04 16:18:59 -07002188 if (device != nullptr) {
2189 closeDeviceLocked(*device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002190 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002191 }
Chris Ye8594e192020-07-14 10:34:06 -07002192 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002193}
2194
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002195/**
2196 * Find the video device by filename, and close it.
2197 * The video device is closed by path during an inotify event, where we don't have the
2198 * additional context about the video device fd, or the associated input device.
2199 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002200void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002201 // A video device may be owned by an existing input device, or it may be stored in
2202 // the mUnattachedVideoDevices queue. Check both locations.
Chris Ye989bb932020-07-04 16:18:59 -07002203 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002204 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002205 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002206 device->videoDevice = nullptr;
2207 return;
2208 }
2209 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002210 mUnattachedVideoDevices
2211 .erase(std::remove_if(mUnattachedVideoDevices.begin(), mUnattachedVideoDevices.end(),
2212 [&devicePath](
2213 const std::unique_ptr<TouchVideoDevice>& videoDevice) {
2214 return videoDevice->getPath() == devicePath;
2215 }),
2216 mUnattachedVideoDevices.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002217}
2218
2219void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002220 mUnattachedVideoDevices.clear();
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002221 while (!mDevices.empty()) {
2222 closeDeviceLocked(*(mDevices.begin()->second));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002223 }
2224}
2225
Chris Ye989bb932020-07-04 16:18:59 -07002226void EventHub::closeDeviceLocked(Device& device) {
2227 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=%s", device.path.c_str(),
2228 device.identifier.name.c_str(), device.id, device.fd, device.classes.string().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002229
Chris Ye989bb932020-07-04 16:18:59 -07002230 if (device.id == mBuiltInKeyboardId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002231 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Chris Ye989bb932020-07-04 16:18:59 -07002232 device.path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002233 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
2234 }
2235
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002236 unregisterDeviceFromEpollLocked(device);
Chris Ye989bb932020-07-04 16:18:59 -07002237 if (device.videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002238 // This must be done after the video device is removed from epoll
Chris Ye989bb932020-07-04 16:18:59 -07002239 mUnattachedVideoDevices.push_back(std::move(device.videoDevice));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002240 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002241
Chris Ye989bb932020-07-04 16:18:59 -07002242 releaseControllerNumberLocked(device.controllerNumber);
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002243 device.controllerNumber = 0;
Chris Ye989bb932020-07-04 16:18:59 -07002244 device.close();
Chris Ye989bb932020-07-04 16:18:59 -07002245 mClosingDevices.push_back(std::move(mDevices[device.id]));
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002246
Chris Ye989bb932020-07-04 16:18:59 -07002247 mDevices.erase(device.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002248}
2249
2250status_t EventHub::readNotifyLocked() {
2251 int res;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002252 char event_buf[512];
2253 int event_size;
2254 int event_pos = 0;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002255 struct inotify_event* event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002256
2257 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
2258 res = read(mINotifyFd, event_buf, sizeof(event_buf));
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002259 if (res < (int)sizeof(*event)) {
2260 if (errno == EINTR) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002261 ALOGW("could not get event, %s\n", strerror(errno));
2262 return -1;
2263 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002264
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002265 while (res >= (int)sizeof(*event)) {
2266 event = (struct inotify_event*)(event_buf + event_pos);
2267 if (event->len) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08002268 if (event->wd == mInputWd) {
Chris Ye8594e192020-07-14 10:34:06 -07002269 std::string filename = std::string(DEVICE_PATH) + "/" + event->name;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002270 if (event->mask & IN_CREATE) {
Chris Ye8594e192020-07-14 10:34:06 -07002271 openDeviceLocked(filename);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08002272 } else {
2273 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
Chris Ye8594e192020-07-14 10:34:06 -07002274 closeDeviceByPathLocked(filename);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08002275 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002276 } else if (event->wd == mVideoWd) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08002277 if (isV4lTouchNode(event->name)) {
Chris Ye8594e192020-07-14 10:34:06 -07002278 std::string filename = std::string(VIDEO_DEVICE_PATH) + "/" + event->name;
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002279 if (event->mask & IN_CREATE) {
2280 openVideoDeviceLocked(filename);
2281 } else {
2282 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
2283 closeVideoDeviceByPathLocked(filename);
2284 }
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08002285 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002286 } else {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08002287 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event->wd);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002288 }
2289 }
2290 event_size = sizeof(*event) + event->len;
2291 res -= event_size;
2292 event_pos += event_size;
2293 }
2294 return 0;
2295}
2296
Chris Ye8594e192020-07-14 10:34:06 -07002297status_t EventHub::scanDirLocked(const std::string& dirname) {
2298 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2299 openDeviceLocked(entry.path());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002300 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002301 return 0;
2302}
2303
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002304/**
2305 * Look for all dirname/v4l-touch* devices, and open them.
2306 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002307status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Chris Ye8594e192020-07-14 10:34:06 -07002308 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2309 if (isV4lTouchNode(entry.path())) {
2310 ALOGI("Found touch video device %s", entry.path().c_str());
2311 openVideoDeviceLocked(entry.path());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002312 }
2313 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002314 return OK;
2315}
2316
Michael Wrightd02c5b62014-02-10 15:10:22 -08002317void EventHub::requestReopenDevices() {
2318 ALOGV("requestReopenDevices() called");
2319
Chris Ye87143712020-11-10 05:05:58 +00002320 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002321 mNeedToReopenDevices = true;
2322}
2323
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002324void EventHub::dump(std::string& dump) {
2325 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002326
2327 { // acquire lock
Chris Ye87143712020-11-10 05:05:58 +00002328 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002329
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002330 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002331
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002332 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002333
Chris Ye989bb932020-07-04 16:18:59 -07002334 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002335 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002336 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002337 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002338 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002339 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002340 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002341 }
Chris Ye1b0c7342020-07-28 21:57:03 -07002342 dump += StringPrintf(INDENT3 "Classes: %s\n", device->classes.string().c_str());
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002343 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002344 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002345 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
2346 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002347 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002348 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002349 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002350 "product=0x%04x, version=0x%04x\n",
2351 device->identifier.bus, device->identifier.vendor,
2352 device->identifier.product, device->identifier.version);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002353 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002354 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002355 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002356 device->keyMap.keyCharacterMapFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002357 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002358 device->configurationFile.c_str());
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002359 dump += INDENT3 "VideoDevice: ";
2360 if (device->videoDevice) {
2361 dump += device->videoDevice->dump() + "\n";
2362 } else {
2363 dump += "<none>\n";
2364 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002365 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002366
2367 dump += INDENT "Unattached video devices:\n";
2368 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
2369 dump += INDENT2 + videoDevice->dump() + "\n";
2370 }
2371 if (mUnattachedVideoDevices.empty()) {
2372 dump += INDENT2 "<none>\n";
2373 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002374 } // release lock
2375}
2376
2377void EventHub::monitor() {
2378 // Acquire and release the lock to ensure that the event hub has not deadlocked.
Chris Ye1c2e0892020-11-30 21:41:44 -08002379 std::unique_lock<std::mutex> lock(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002380}
2381
Michael Wrightd02c5b62014-02-10 15:10:22 -08002382}; // namespace android