blob: a0d3b6a75708a6cae3797a413cf3e062fdd4098f [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2005 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070017#include <assert.h>
18#include <dirent.h>
19#include <errno.h>
20#include <fcntl.h>
21#include <inttypes.h>
22#include <memory.h>
23#include <stdint.h>
24#include <stdio.h>
25#include <stdlib.h>
26#include <string.h>
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +010027#include <sys/capability.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070028#include <sys/epoll.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070029#include <sys/inotify.h>
30#include <sys/ioctl.h>
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070031#include <sys/limits.h>
Kim Low03ea0352020-11-06 12:45:07 -080032#include <sys/stat.h>
33#include <sys/sysmacros.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070034#include <unistd.h>
35
Michael Wrightd02c5b62014-02-10 15:10:22 -080036#define LOG_TAG "EventHub"
37
38// #define LOG_NDEBUG 0
Kim Low03ea0352020-11-06 12:45:07 -080039#include <android-base/file.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080040#include <android-base/stringprintf.h>
Philip Quinn39b81682019-01-09 22:20:39 -080041#include <cutils/properties.h>
Chris Ye8594e192020-07-14 10:34:06 -070042#include <input/KeyCharacterMap.h>
43#include <input/KeyLayoutMap.h>
44#include <input/VirtualKeyMap.h>
Dan Albert677d87e2014-06-16 17:31:28 -070045#include <openssl/sha.h>
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070046#include <utils/Errors.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080047#include <utils/Log.h>
48#include <utils/Timers.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080049
Chris Ye8594e192020-07-14 10:34:06 -070050#include <filesystem>
Chris Ye3fdbfef2021-01-06 18:45:18 -080051#include <regex>
Chris Ye8594e192020-07-14 10:34:06 -070052
53#include "EventHub.h"
Michael Wrightd02c5b62014-02-10 15:10:22 -080054
Michael Wrightd02c5b62014-02-10 15:10:22 -080055#define INDENT " "
56#define INDENT2 " "
57#define INDENT3 " "
58
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080059using android::base::StringPrintf;
Chris Ye1b0c7342020-07-28 21:57:03 -070060using namespace android::flag_operators;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080061
Michael Wrightd02c5b62014-02-10 15:10:22 -080062namespace android {
63
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070064static const char* DEVICE_PATH = "/dev/input";
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080065// v4l2 devices go directly into /dev
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070066static const char* VIDEO_DEVICE_PATH = "/dev";
Michael Wrightd02c5b62014-02-10 15:10:22 -080067
Chris Ye87143712020-11-10 05:05:58 +000068static constexpr int32_t FF_STRONG_MAGNITUDE_CHANNEL_IDX = 0;
69static constexpr int32_t FF_WEAK_MAGNITUDE_CHANNEL_IDX = 1;
Chris Ye6393a262020-08-04 19:41:36 -070070
Kim Low03ea0352020-11-06 12:45:07 -080071// must be kept in sync with definitions in kernel /drivers/power/supply/power_supply_sysfs.c
72static const std::unordered_map<std::string, int32_t> BATTERY_STATUS =
73 {{"Unknown", BATTERY_STATUS_UNKNOWN},
74 {"Charging", BATTERY_STATUS_CHARGING},
75 {"Discharging", BATTERY_STATUS_DISCHARGING},
76 {"Not charging", BATTERY_STATUS_NOT_CHARGING},
77 {"Full", BATTERY_STATUS_FULL}};
78
79// Mapping taken from
80// https://gitlab.freedesktop.org/upower/upower/-/blob/master/src/linux/up-device-supply.c#L484
81static const std::unordered_map<std::string, int32_t> BATTERY_LEVEL = {{"Critical", 5},
82 {"Low", 10},
83 {"Normal", 55},
84 {"High", 70},
85 {"Full", 100},
86 {"Unknown", 50}};
87
Chris Ye3fdbfef2021-01-06 18:45:18 -080088// Mapping for input led class node names lookup.
89// https://www.kernel.org/doc/html/latest/leds/leds-class.html
90static const std::unordered_map<std::string, InputLightClass> LIGHT_CLASSES =
91 {{"red", InputLightClass::RED},
92 {"green", InputLightClass::GREEN},
93 {"blue", InputLightClass::BLUE},
94 {"global", InputLightClass::GLOBAL},
95 {"brightness", InputLightClass::BRIGHTNESS},
96 {"multi_index", InputLightClass::MULTI_INDEX},
97 {"multi_intensity", InputLightClass::MULTI_INTENSITY},
98 {"max_brightness", InputLightClass::MAX_BRIGHTNESS}};
99
100// Mapping for input multicolor led class node names.
101// https://www.kernel.org/doc/html/latest/leds/leds-class-multicolor.html
102static const std::unordered_map<InputLightClass, std::string> LIGHT_NODES =
103 {{InputLightClass::BRIGHTNESS, "brightness"},
104 {InputLightClass::MULTI_INDEX, "multi_index"},
105 {InputLightClass::MULTI_INTENSITY, "multi_intensity"}};
106
107// Mapping for light color name and the light color
108const std::unordered_map<std::string, LightColor> LIGHT_COLORS = {{"red", LightColor::RED},
109 {"green", LightColor::GREEN},
110 {"blue", LightColor::BLUE}};
111
Michael Wrightd02c5b62014-02-10 15:10:22 -0800112static inline const char* toString(bool value) {
113 return value ? "true" : "false";
114}
115
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100116static std::string sha1(const std::string& in) {
Dan Albert677d87e2014-06-16 17:31:28 -0700117 SHA_CTX ctx;
118 SHA1_Init(&ctx);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100119 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
Dan Albert677d87e2014-06-16 17:31:28 -0700120 u_char digest[SHA_DIGEST_LENGTH];
121 SHA1_Final(digest, &ctx);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800122
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100123 std::string out;
Dan Albert677d87e2014-06-16 17:31:28 -0700124 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100125 out += StringPrintf("%02x", digest[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800126 }
127 return out;
128}
129
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800130/**
131 * Return true if name matches "v4l-touch*"
132 */
Chris Ye8594e192020-07-14 10:34:06 -0700133static bool isV4lTouchNode(std::string name) {
134 return name.find("v4l-touch") != std::string::npos;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800135}
136
Philip Quinn39b81682019-01-09 22:20:39 -0800137/**
138 * Returns true if V4L devices should be scanned.
139 *
140 * The system property ro.input.video_enabled can be used to control whether
141 * EventHub scans and opens V4L devices. As V4L does not support multiple
142 * clients, EventHub effectively blocks access to these devices when it opens
Siarhei Vishniakou29f88492019-04-05 14:11:43 -0700143 * them.
144 *
145 * Setting this to "false" would prevent any video devices from being discovered and
146 * associated with input devices.
147 *
148 * This property can be used as follows:
149 * 1. To turn off features that are dependent on video device presence.
150 * 2. During testing and development, to allow other clients to read video devices
151 * directly from /dev.
Philip Quinn39b81682019-01-09 22:20:39 -0800152 */
153static bool isV4lScanningEnabled() {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700154 return property_get_bool("ro.input.video_enabled", true /* default_value */);
Philip Quinn39b81682019-01-09 22:20:39 -0800155}
156
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800157static nsecs_t processEventTimestamp(const struct input_event& event) {
158 // Use the time specified in the event instead of the current time
159 // so that downstream code can get more accurate estimates of
160 // event dispatch latency from the time the event is enqueued onto
161 // the evdev client buffer.
162 //
163 // The event's timestamp fortuitously uses the same monotonic clock
164 // time base as the rest of Android. The kernel event device driver
165 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
166 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
167 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
168 // system call that also queries ktime_get_ts().
169
170 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.time.tv_sec) +
171 microseconds_to_nanoseconds(event.time.tv_usec);
172 return inputEventTime;
173}
174
Kim Low03ea0352020-11-06 12:45:07 -0800175/**
176 * Returns the sysfs root path of the input device
177 *
178 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800179static std::optional<std::filesystem::path> getSysfsRootPath(const char* devicePath) {
Kim Low03ea0352020-11-06 12:45:07 -0800180 std::error_code errorCode;
181
182 // Stat the device path to get the major and minor number of the character file
183 struct stat statbuf;
184 if (stat(devicePath, &statbuf) == -1) {
185 ALOGE("Could not stat device %s due to error: %s.", devicePath, std::strerror(errno));
Chris Ye3fdbfef2021-01-06 18:45:18 -0800186 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800187 }
188
189 unsigned int major_num = major(statbuf.st_rdev);
190 unsigned int minor_num = minor(statbuf.st_rdev);
191
192 // Realpath "/sys/dev/char/{major}:{minor}" to get the sysfs path to the input event
193 auto sysfsPath = std::filesystem::path("/sys/dev/char/");
194 sysfsPath /= std::to_string(major_num) + ":" + std::to_string(minor_num);
195 sysfsPath = std::filesystem::canonical(sysfsPath, errorCode);
196
197 // Make sure nothing went wrong in call to canonical()
198 if (errorCode) {
199 ALOGW("Could not run filesystem::canonical() due to error %d : %s.", errorCode.value(),
200 errorCode.message().c_str());
Chris Ye3fdbfef2021-01-06 18:45:18 -0800201 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800202 }
203
204 // Continue to go up a directory until we reach a directory named "input"
205 while (sysfsPath != "/" && sysfsPath.filename() != "input") {
206 sysfsPath = sysfsPath.parent_path();
207 }
208
209 // Then go up one more and you will be at the sysfs root of the device
210 sysfsPath = sysfsPath.parent_path();
211
212 // Make sure we didn't reach root path and that directory actually exists
213 if (sysfsPath == "/" || !std::filesystem::exists(sysfsPath, errorCode)) {
214 if (errorCode) {
215 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
216 errorCode.message().c_str());
217 }
218
219 // Not found
Chris Ye3fdbfef2021-01-06 18:45:18 -0800220 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800221 }
222
223 return sysfsPath;
224}
225
226/**
Chris Ye3fdbfef2021-01-06 18:45:18 -0800227 * Returns the list of files under a specified path.
Kim Low03ea0352020-11-06 12:45:07 -0800228 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800229static std::vector<std::filesystem::path> allFilesInPath(const std::filesystem::path& path) {
230 std::vector<std::filesystem::path> nodes;
231 std::error_code errorCode;
232 auto iter = std::filesystem::directory_iterator(path, errorCode);
233 while (!errorCode && iter != std::filesystem::directory_iterator()) {
234 nodes.push_back(iter->path());
235 iter++;
236 }
237 return nodes;
238}
239
240/**
241 * Returns the list of files under a specified directory in a sysfs path.
242 * Example:
243 * findSysfsNodes(sysfsRootPath, SysfsClass::LEDS) will return all led nodes under "leds" directory
244 * in the sysfs path.
245 */
246static std::vector<std::filesystem::path> findSysfsNodes(const std::filesystem::path& sysfsRoot,
247 SysfsClass clazz) {
248 std::string nodeStr = NamedEnum::string(clazz);
249 std::for_each(nodeStr.begin(), nodeStr.end(),
250 [](char& c) { c = std::tolower(static_cast<unsigned char>(c)); });
251 std::vector<std::filesystem::path> nodes;
252 for (auto path = sysfsRoot; path != "/" && nodes.empty(); path = path.parent_path()) {
253 nodes = allFilesInPath(path / nodeStr);
254 }
255 return nodes;
256}
257
258static std::optional<std::array<LightColor, COLOR_NUM>> getColorIndexArray(
259 std::filesystem::path path) {
260 std::string indexStr;
261 if (!base::ReadFileToString(path, &indexStr)) {
262 return std::nullopt;
263 }
264
265 // Parse the multi color LED index file, refer to kernel docs
266 // leds/leds-class-multicolor.html
267 std::regex indexPattern("(red|green|blue)\\s(red|green|blue)\\s(red|green|blue)[\\n]");
268 std::smatch results;
269 std::array<LightColor, COLOR_NUM> colors;
270 if (!std::regex_match(indexStr, results, indexPattern)) {
271 return std::nullopt;
272 }
273
274 for (size_t i = 1; i < results.size(); i++) {
275 const auto it = LIGHT_COLORS.find(results[i].str());
276 if (it != LIGHT_COLORS.end()) {
277 // intensities.emplace(it->second, 0);
278 colors[i - 1] = it->second;
Kim Low03ea0352020-11-06 12:45:07 -0800279 }
280 }
Chris Ye3fdbfef2021-01-06 18:45:18 -0800281 return colors;
Kim Low03ea0352020-11-06 12:45:07 -0800282}
283
Michael Wrightd02c5b62014-02-10 15:10:22 -0800284// --- Global Functions ---
285
Chris Ye1b0c7342020-07-28 21:57:03 -0700286Flags<InputDeviceClass> getAbsAxisUsage(int32_t axis, Flags<InputDeviceClass> deviceClasses) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800287 // Touch devices get dibs on touch-related axes.
Chris Ye1b0c7342020-07-28 21:57:03 -0700288 if (deviceClasses.test(InputDeviceClass::TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800289 switch (axis) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700290 case ABS_X:
291 case ABS_Y:
292 case ABS_PRESSURE:
293 case ABS_TOOL_WIDTH:
294 case ABS_DISTANCE:
295 case ABS_TILT_X:
296 case ABS_TILT_Y:
297 case ABS_MT_SLOT:
298 case ABS_MT_TOUCH_MAJOR:
299 case ABS_MT_TOUCH_MINOR:
300 case ABS_MT_WIDTH_MAJOR:
301 case ABS_MT_WIDTH_MINOR:
302 case ABS_MT_ORIENTATION:
303 case ABS_MT_POSITION_X:
304 case ABS_MT_POSITION_Y:
305 case ABS_MT_TOOL_TYPE:
306 case ABS_MT_BLOB_ID:
307 case ABS_MT_TRACKING_ID:
308 case ABS_MT_PRESSURE:
309 case ABS_MT_DISTANCE:
Chris Ye1b0c7342020-07-28 21:57:03 -0700310 return InputDeviceClass::TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800311 }
312 }
313
Chris Yef59a2f42020-10-16 12:55:26 -0700314 if (deviceClasses.test(InputDeviceClass::SENSOR)) {
315 switch (axis) {
316 case ABS_X:
317 case ABS_Y:
318 case ABS_Z:
319 case ABS_RX:
320 case ABS_RY:
321 case ABS_RZ:
322 return InputDeviceClass::SENSOR;
323 }
324 }
325
Michael Wright842500e2015-03-13 17:32:02 -0700326 // External stylus gets the pressure axis
Chris Ye1b0c7342020-07-28 21:57:03 -0700327 if (deviceClasses.test(InputDeviceClass::EXTERNAL_STYLUS)) {
Michael Wright842500e2015-03-13 17:32:02 -0700328 if (axis == ABS_PRESSURE) {
Chris Ye1b0c7342020-07-28 21:57:03 -0700329 return InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -0700330 }
331 }
332
Michael Wrightd02c5b62014-02-10 15:10:22 -0800333 // Joystick devices get the rest.
Chris Ye1b0c7342020-07-28 21:57:03 -0700334 return deviceClasses & InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800335}
336
337// --- EventHub::Device ---
338
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100339EventHub::Device::Device(int fd, int32_t id, const std::string& path,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700340 const InputDeviceIdentifier& identifier)
Chris Ye989bb932020-07-04 16:18:59 -0700341 : fd(fd),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700342 id(id),
343 path(path),
344 identifier(identifier),
345 classes(0),
346 configuration(nullptr),
347 virtualKeyMap(nullptr),
348 ffEffectPlaying(false),
349 ffEffectId(-1),
Chris Ye3fdbfef2021-01-06 18:45:18 -0800350 nextLightId(0),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700351 controllerNumber(0),
352 enabled(true),
Chris Ye66fbac32020-07-06 20:36:43 -0700353 isVirtual(fd < 0) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800354
355EventHub::Device::~Device() {
356 close();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800357}
358
359void EventHub::Device::close() {
360 if (fd >= 0) {
361 ::close(fd);
362 fd = -1;
363 }
364}
365
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700366status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100367 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700368 if (fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100369 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700370 return -errno;
371 }
372 enabled = true;
373 return OK;
374}
375
376status_t EventHub::Device::disable() {
377 close();
378 enabled = false;
379 return OK;
380}
381
Chris Ye989bb932020-07-04 16:18:59 -0700382bool EventHub::Device::hasValidFd() const {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700383 return !isVirtual && enabled;
384}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800385
Chris Ye3a1e4462020-08-12 10:13:15 -0700386const std::shared_ptr<KeyCharacterMap> EventHub::Device::getKeyCharacterMap() const {
Chris Ye989bb932020-07-04 16:18:59 -0700387 return keyMap.keyCharacterMap;
388}
389
390template <std::size_t N>
391status_t EventHub::Device::readDeviceBitMask(unsigned long ioctlCode, BitArray<N>& bitArray) {
392 if (!hasValidFd()) {
393 return BAD_VALUE;
394 }
395 if ((_IOC_SIZE(ioctlCode) == 0)) {
396 ioctlCode |= _IOC(0, 0, 0, bitArray.bytes());
397 }
398
399 typename BitArray<N>::Buffer buffer;
400 status_t ret = ioctl(fd, ioctlCode, buffer.data());
401 bitArray.loadFromBuffer(buffer);
402 return ret;
403}
404
405void EventHub::Device::configureFd() {
406 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
407 if (classes.test(InputDeviceClass::KEYBOARD)) {
408 // Disable kernel key repeat since we handle it ourselves
409 unsigned int repeatRate[] = {0, 0};
410 if (ioctl(fd, EVIOCSREP, repeatRate)) {
411 ALOGW("Unable to disable kernel key repeat for %s: %s", path.c_str(), strerror(errno));
412 }
413 }
414
415 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
416 // associated with input events. This is important because the input system
417 // uses the timestamps extensively and assumes they were recorded using the monotonic
418 // clock.
419 int clockId = CLOCK_MONOTONIC;
Chris Yef59a2f42020-10-16 12:55:26 -0700420 if (classes.test(InputDeviceClass::SENSOR)) {
421 // Each new sensor event should use the same time base as
422 // SystemClock.elapsedRealtimeNanos().
423 clockId = CLOCK_BOOTTIME;
424 }
Chris Ye989bb932020-07-04 16:18:59 -0700425 bool usingClockIoctl = !ioctl(fd, EVIOCSCLOCKID, &clockId);
426 ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
427}
428
429bool EventHub::Device::hasKeycodeLocked(int keycode) const {
430 if (!keyMap.haveKeyLayout()) {
431 return false;
432 }
433
434 std::vector<int32_t> scanCodes;
435 keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes);
436 const size_t N = scanCodes.size();
437 for (size_t i = 0; i < N && i <= KEY_MAX; i++) {
438 int32_t sc = scanCodes[i];
439 if (sc >= 0 && sc <= KEY_MAX && keyBitmask.test(sc)) {
440 return true;
441 }
442 }
443
444 return false;
445}
446
447void EventHub::Device::loadConfigurationLocked() {
448 configurationFile =
449 getInputDeviceConfigurationFilePathByDeviceIdentifier(identifier,
450 InputDeviceConfigurationFileType::
451 CONFIGURATION);
452 if (configurationFile.empty()) {
453 ALOGD("No input device configuration file found for device '%s'.", identifier.name.c_str());
454 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500455 android::base::Result<std::unique_ptr<PropertyMap>> propertyMap =
456 PropertyMap::load(configurationFile.c_str());
457 if (!propertyMap.ok()) {
Chris Ye989bb932020-07-04 16:18:59 -0700458 ALOGE("Error loading input device configuration file for device '%s'. "
459 "Using default configuration.",
460 identifier.name.c_str());
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500461 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500462 configuration = std::move(*propertyMap);
Chris Ye989bb932020-07-04 16:18:59 -0700463 }
464 }
465}
466
467bool EventHub::Device::loadVirtualKeyMapLocked() {
468 // The virtual key map is supplied by the kernel as a system board property file.
469 std::string propPath = "/sys/board_properties/virtualkeys.";
470 propPath += identifier.getCanonicalName();
471 if (access(propPath.c_str(), R_OK)) {
472 return false;
473 }
474 virtualKeyMap = VirtualKeyMap::load(propPath);
475 return virtualKeyMap != nullptr;
476}
477
478status_t EventHub::Device::loadKeyMapLocked() {
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500479 return keyMap.load(identifier, configuration.get());
Chris Ye989bb932020-07-04 16:18:59 -0700480}
481
482bool EventHub::Device::isExternalDeviceLocked() {
483 if (configuration) {
484 bool value;
485 if (configuration->tryGetProperty(String8("device.internal"), value)) {
486 return !value;
487 }
488 }
489 return identifier.bus == BUS_USB || identifier.bus == BUS_BLUETOOTH;
490}
491
492bool EventHub::Device::deviceHasMicLocked() {
493 if (configuration) {
494 bool value;
495 if (configuration->tryGetProperty(String8("audio.mic"), value)) {
496 return value;
497 }
498 }
499 return false;
500}
501
502void EventHub::Device::setLedStateLocked(int32_t led, bool on) {
503 int32_t sc;
504 if (hasValidFd() && mapLed(led, &sc) != NAME_NOT_FOUND) {
505 struct input_event ev;
506 ev.time.tv_sec = 0;
507 ev.time.tv_usec = 0;
508 ev.type = EV_LED;
509 ev.code = sc;
510 ev.value = on ? 1 : 0;
511
512 ssize_t nWrite;
513 do {
514 nWrite = write(fd, &ev, sizeof(struct input_event));
515 } while (nWrite == -1 && errno == EINTR);
516 }
517}
518
519void EventHub::Device::setLedForControllerLocked() {
520 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
521 setLedStateLocked(ALED_CONTROLLER_1 + i, controllerNumber == i + 1);
522 }
523}
524
525status_t EventHub::Device::mapLed(int32_t led, int32_t* outScanCode) const {
526 if (!keyMap.haveKeyLayout()) {
527 return NAME_NOT_FOUND;
528 }
529
530 int32_t scanCode;
531 if (keyMap.keyLayoutMap->findScanCodeForLed(led, &scanCode) != NAME_NOT_FOUND) {
532 if (scanCode >= 0 && scanCode <= LED_MAX && ledBitmask.test(scanCode)) {
533 *outScanCode = scanCode;
534 return NO_ERROR;
535 }
536 }
537 return NAME_NOT_FOUND;
538}
539
Chris Ye3fdbfef2021-01-06 18:45:18 -0800540// Check the sysfs path for any input device batteries, returns true if battery found.
541bool EventHub::Device::configureBatteryLocked() {
542 if (!sysfsRootPath.has_value()) {
543 return false;
544 }
545 // Check if device has any batteries.
546 std::vector<std::filesystem::path> batteryPaths =
547 findSysfsNodes(sysfsRootPath.value(), SysfsClass::POWER_SUPPLY);
548 // We only support single battery for an input device, if multiple batteries exist only the
549 // first one is supported.
550 if (batteryPaths.empty()) {
551 // Set path to be empty
552 sysfsBatteryPath = std::nullopt;
553 return false;
554 }
555 // If a battery exists
556 sysfsBatteryPath = batteryPaths[0];
557 return true;
558}
559
560// Check the sysfs path for any input device lights, returns true if lights found.
561bool EventHub::Device::configureLightsLocked() {
562 if (!sysfsRootPath.has_value()) {
563 return false;
564 }
565 // Check if device has any lights.
566 const auto& paths = findSysfsNodes(sysfsRootPath.value(), SysfsClass::LEDS);
567 for (const auto& nodePath : paths) {
568 RawLightInfo info;
569 info.id = ++nextLightId;
570 info.path = nodePath;
571 info.name = nodePath.filename();
572 info.maxBrightness = std::nullopt;
573 size_t nameStart = info.name.rfind(":");
574 if (nameStart != std::string::npos) {
575 // Trim the name to color name
576 info.name = info.name.substr(nameStart + 1);
577 // Set InputLightClass flag for colors
578 const auto it = LIGHT_CLASSES.find(info.name);
579 if (it != LIGHT_CLASSES.end()) {
580 info.flags |= it->second;
581 }
582 }
583 // Scan the path for all the files
584 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
585 const auto& files = allFilesInPath(nodePath);
586 for (const auto& file : files) {
587 const auto it = LIGHT_CLASSES.find(file.filename().string());
588 if (it != LIGHT_CLASSES.end()) {
589 info.flags |= it->second;
590 // If the node has maximum brightness, read it
591 if (it->second == InputLightClass::MAX_BRIGHTNESS) {
592 std::string str;
593 if (base::ReadFileToString(file, &str)) {
594 info.maxBrightness = std::stoi(str);
595 }
596 }
597 }
598 }
599 lightInfos.insert_or_assign(info.id, info);
600 }
601 return !lightInfos.empty();
602}
603
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100604/**
605 * Get the capabilities for the current process.
606 * Crashes the system if unable to create / check / destroy the capabilities object.
607 */
608class Capabilities final {
609public:
610 explicit Capabilities() {
611 mCaps = cap_get_proc();
612 LOG_ALWAYS_FATAL_IF(mCaps == nullptr, "Could not get capabilities of the current process");
613 }
614
615 /**
616 * Check whether the current process has a specific capability
617 * in the set of effective capabilities.
618 * Return CAP_SET if the process has the requested capability
619 * Return CAP_CLEAR otherwise.
620 */
621 cap_flag_value_t checkEffectiveCapability(cap_value_t capability) {
622 cap_flag_value_t value;
623 const int result = cap_get_flag(mCaps, capability, CAP_EFFECTIVE, &value);
624 LOG_ALWAYS_FATAL_IF(result == -1, "Could not obtain the requested capability");
625 return value;
626 }
627
628 ~Capabilities() {
629 const int result = cap_free(mCaps);
630 LOG_ALWAYS_FATAL_IF(result == -1, "Could not release the capabilities structure");
631 }
632
633private:
634 cap_t mCaps;
635};
636
637static void ensureProcessCanBlockSuspend() {
638 Capabilities capabilities;
639 const bool canBlockSuspend =
640 capabilities.checkEffectiveCapability(CAP_BLOCK_SUSPEND) == CAP_SET;
641 LOG_ALWAYS_FATAL_IF(!canBlockSuspend,
642 "Input must be able to block suspend to properly process events");
643}
644
Michael Wrightd02c5b62014-02-10 15:10:22 -0800645// --- EventHub ---
646
Michael Wrightd02c5b62014-02-10 15:10:22 -0800647const int EventHub::EPOLL_MAX_EVENTS;
648
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700649EventHub::EventHub(void)
650 : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
651 mNextDeviceId(1),
652 mControllerNumbers(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800653 mNeedToSendFinishedDeviceScan(false),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700654 mNeedToReopenDevices(false),
655 mNeedToScanDevices(true),
656 mPendingEventCount(0),
657 mPendingEventIndex(0),
658 mPendingINotify(false) {
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100659 ensureProcessCanBlockSuspend();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800660
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800661 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800662 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800663
664 mINotifyFd = inotify_init();
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800665 mInputWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700666 LOG_ALWAYS_FATAL_IF(mInputWd < 0, "Could not register INotify for %s: %s", DEVICE_PATH,
667 strerror(errno));
Philip Quinn39b81682019-01-09 22:20:39 -0800668 if (isV4lScanningEnabled()) {
669 mVideoWd = inotify_add_watch(mINotifyFd, VIDEO_DEVICE_PATH, IN_DELETE | IN_CREATE);
670 LOG_ALWAYS_FATAL_IF(mVideoWd < 0, "Could not register INotify for %s: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700671 VIDEO_DEVICE_PATH, strerror(errno));
Philip Quinn39b81682019-01-09 22:20:39 -0800672 } else {
673 mVideoWd = -1;
674 ALOGI("Video device scanning disabled");
675 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800676
Siarhei Vishniakou2d0e9482019-09-24 12:52:47 +0100677 struct epoll_event eventItem = {};
678 eventItem.events = EPOLLIN | EPOLLWAKEUP;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700679 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800680 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800681 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
682
683 int wakeFds[2];
684 result = pipe(wakeFds);
685 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
686
687 mWakeReadPipeFd = wakeFds[0];
688 mWakeWritePipeFd = wakeFds[1];
689
690 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
691 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700692 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800693
694 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
695 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700696 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800697
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700698 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800699 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
700 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700701 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800702}
703
704EventHub::~EventHub(void) {
705 closeAllDevicesLocked();
706
Michael Wrightd02c5b62014-02-10 15:10:22 -0800707 ::close(mEpollFd);
708 ::close(mINotifyFd);
709 ::close(mWakeReadPipeFd);
710 ::close(mWakeWritePipeFd);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800711}
712
713InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000714 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800715 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700716 return device != nullptr ? device->identifier : InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800717}
718
Chris Ye1b0c7342020-07-28 21:57:03 -0700719Flags<InputDeviceClass> EventHub::getDeviceClasses(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000720 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800721 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700722 return device != nullptr ? device->classes : Flags<InputDeviceClass>(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800723}
724
725int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000726 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800727 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700728 return device != nullptr ? device->controllerNumber : 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800729}
730
731void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
Chris Ye87143712020-11-10 05:05:58 +0000732 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800733 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700734 if (device != nullptr && device->configuration) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800735 *outConfiguration = *device->configuration;
736 } else {
737 outConfiguration->clear();
738 }
739}
740
741status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700742 RawAbsoluteAxisInfo* outAxisInfo) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800743 outAxisInfo->clear();
744
745 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000746 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800747
748 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700749 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800750 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700751 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
752 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
753 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800754 return -errno;
755 }
756
757 if (info.minimum != info.maximum) {
758 outAxisInfo->valid = true;
759 outAxisInfo->minValue = info.minimum;
760 outAxisInfo->maxValue = info.maximum;
761 outAxisInfo->flat = info.flat;
762 outAxisInfo->fuzz = info.fuzz;
763 outAxisInfo->resolution = info.resolution;
764 }
765 return OK;
766 }
767 }
768 return -1;
769}
770
771bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
772 if (axis >= 0 && axis <= REL_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000773 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800774 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700775 return device != nullptr ? device->relBitmask.test(axis) : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800776 }
777 return false;
778}
779
780bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
Chris Ye87143712020-11-10 05:05:58 +0000781 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800782
Chris Ye989bb932020-07-04 16:18:59 -0700783 Device* device = getDeviceLocked(deviceId);
784 return property >= 0 && property <= INPUT_PROP_MAX && device != nullptr
785 ? device->propBitmask.test(property)
786 : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800787}
788
Chris Yef59a2f42020-10-16 12:55:26 -0700789bool EventHub::hasMscEvent(int32_t deviceId, int mscEvent) const {
790 std::scoped_lock _l(mLock);
791
792 Device* device = getDeviceLocked(deviceId);
793 return mscEvent >= 0 && mscEvent <= MSC_MAX && device != nullptr
794 ? device->mscBitmask.test(mscEvent)
795 : false;
796}
797
Michael Wrightd02c5b62014-02-10 15:10:22 -0800798int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
799 if (scanCode >= 0 && scanCode <= KEY_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000800 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800801
802 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700803 if (device != nullptr && device->hasValidFd() && device->keyBitmask.test(scanCode)) {
804 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
805 return device->keyState.test(scanCode) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800806 }
807 }
808 }
809 return AKEY_STATE_UNKNOWN;
810}
811
812int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
Chris Ye87143712020-11-10 05:05:58 +0000813 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800814
815 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700816 if (device != nullptr && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800817 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800818 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode, &scanCodes);
819 if (scanCodes.size() != 0) {
Chris Ye66fbac32020-07-06 20:36:43 -0700820 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800821 for (size_t i = 0; i < scanCodes.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800822 int32_t sc = scanCodes[i];
Chris Ye66fbac32020-07-06 20:36:43 -0700823 if (sc >= 0 && sc <= KEY_MAX && device->keyState.test(sc)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800824 return AKEY_STATE_DOWN;
825 }
826 }
827 return AKEY_STATE_UP;
828 }
829 }
830 }
831 return AKEY_STATE_UNKNOWN;
832}
833
834int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
835 if (sw >= 0 && sw <= SW_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000836 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800837
838 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700839 if (device != nullptr && device->hasValidFd() && device->swBitmask.test(sw)) {
840 if (device->readDeviceBitMask(EVIOCGSW(0), device->swState) >= 0) {
841 return device->swState.test(sw) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800842 }
843 }
844 }
845 return AKEY_STATE_UNKNOWN;
846}
847
848status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
849 *outValue = 0;
850
851 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000852 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800853
854 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700855 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800856 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700857 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
858 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
859 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800860 return -errno;
861 }
862
863 *outValue = info.value;
864 return OK;
865 }
866 }
867 return -1;
868}
869
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700870bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes, const int32_t* keyCodes,
871 uint8_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +0000872 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800873
874 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700875 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800876 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800877 for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) {
878 scanCodes.clear();
879
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700880 status_t err = device->keyMap.keyLayoutMap->findScanCodesForKey(keyCodes[codeIndex],
881 &scanCodes);
882 if (!err) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800883 // check the possible scan codes identified by the layout map against the
884 // map of codes actually emitted by the driver
885 for (size_t sc = 0; sc < scanCodes.size(); sc++) {
Chris Ye66fbac32020-07-06 20:36:43 -0700886 if (device->keyBitmask.test(scanCodes[sc])) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800887 outFlags[codeIndex] = 1;
888 break;
889 }
890 }
891 }
892 }
893 return true;
894 }
895 return false;
896}
897
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700898status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
899 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +0000900 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800901 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700902 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800903
Chris Ye66fbac32020-07-06 20:36:43 -0700904 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800905 // Check the key character map first.
Chris Ye3a1e4462020-08-12 10:13:15 -0700906 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
907 if (kcm) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800908 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
909 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700910 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800911 }
912 }
913
914 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700915 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800916 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700917 status = NO_ERROR;
918 }
919 }
920
921 if (status == NO_ERROR) {
Chris Ye3a1e4462020-08-12 10:13:15 -0700922 if (kcm) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700923 kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState);
924 } else {
925 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800926 }
927 }
928 }
929
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700930 if (status != NO_ERROR) {
931 *outKeycode = 0;
932 *outFlags = 0;
933 *outMetaState = metaState;
934 }
935
936 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800937}
938
939status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
Chris Ye87143712020-11-10 05:05:58 +0000940 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800941 Device* device = getDeviceLocked(deviceId);
942
Chris Ye66fbac32020-07-06 20:36:43 -0700943 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800944 status_t err = device->keyMap.keyLayoutMap->mapAxis(scanCode, outAxisInfo);
945 if (err == NO_ERROR) {
946 return NO_ERROR;
947 }
948 }
949
950 return NAME_NOT_FOUND;
951}
952
Chris Yef59a2f42020-10-16 12:55:26 -0700953base::Result<std::pair<InputDeviceSensorType, int32_t>> EventHub::mapSensor(int32_t deviceId,
954 int32_t absCode) {
955 std::scoped_lock _l(mLock);
956 Device* device = getDeviceLocked(deviceId);
957
958 if (device != nullptr && device->keyMap.haveKeyLayout()) {
959 return device->keyMap.keyLayoutMap->mapSensor(absCode);
960 }
961 return Errorf("Device not found or device has no key layout.");
962}
963
Chris Ye3fdbfef2021-01-06 18:45:18 -0800964const std::vector<int32_t> EventHub::getRawLightIds(int32_t deviceId) {
965 std::scoped_lock _l(mLock);
966 Device* device = getDeviceLocked(deviceId);
967 std::vector<int32_t> lightIds;
968
969 if (device != nullptr) {
970 for (const auto [id, info] : device->lightInfos) {
971 lightIds.push_back(id);
972 }
973 }
974 return lightIds;
975}
976
977std::optional<RawLightInfo> EventHub::getRawLightInfo(int32_t deviceId, int32_t lightId) {
978 std::scoped_lock _l(mLock);
979 Device* device = getDeviceLocked(deviceId);
980
981 if (device != nullptr) {
982 auto it = device->lightInfos.find(lightId);
983 if (it != device->lightInfos.end()) {
984 return it->second;
985 }
986 }
987 return std::nullopt;
988}
989
990std::optional<int32_t> EventHub::getLightBrightness(int32_t deviceId, int32_t lightId) {
991 std::scoped_lock _l(mLock);
992
993 Device* device = getDeviceLocked(deviceId);
994 if (device == nullptr) {
995 return std::nullopt;
996 }
997
998 auto it = device->lightInfos.find(lightId);
999 if (it == device->lightInfos.end()) {
1000 return std::nullopt;
1001 }
1002 std::string buffer;
1003 if (!base::ReadFileToString(it->second.path / LIGHT_NODES.at(InputLightClass::BRIGHTNESS),
1004 &buffer)) {
1005 return std::nullopt;
1006 }
1007 return std::stoi(buffer);
1008}
1009
1010std::optional<std::unordered_map<LightColor, int32_t>> EventHub::getLightIntensities(
1011 int32_t deviceId, int32_t lightId) {
1012 std::scoped_lock _l(mLock);
1013
1014 Device* device = getDeviceLocked(deviceId);
1015 if (device == nullptr) {
1016 return std::nullopt;
1017 }
1018
1019 auto lightIt = device->lightInfos.find(lightId);
1020 if (lightIt == device->lightInfos.end()) {
1021 return std::nullopt;
1022 }
1023
1024 auto ret =
1025 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1026
1027 if (!ret.has_value()) {
1028 return std::nullopt;
1029 }
1030 std::array<LightColor, COLOR_NUM> colors = ret.value();
1031
1032 std::string intensityStr;
1033 if (!base::ReadFileToString(lightIt->second.path /
1034 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY),
1035 &intensityStr)) {
1036 return std::nullopt;
1037 }
1038
1039 // Intensity node outputs 3 color values
1040 std::regex intensityPattern("([0-9]+)\\s([0-9]+)\\s([0-9]+)[\\n]");
1041 std::smatch results;
1042
1043 if (!std::regex_match(intensityStr, results, intensityPattern)) {
1044 return std::nullopt;
1045 }
1046 std::unordered_map<LightColor, int32_t> intensities;
1047 for (size_t i = 1; i < results.size(); i++) {
1048 int value = std::stoi(results[i].str());
1049 intensities.emplace(colors[i - 1], value);
1050 }
1051 return intensities;
1052}
1053
1054void EventHub::setLightBrightness(int32_t deviceId, int32_t lightId, int32_t brightness) {
1055 std::scoped_lock _l(mLock);
1056
1057 Device* device = getDeviceLocked(deviceId);
1058 if (device == nullptr) {
1059 ALOGE("Device Id %d does not exist", deviceId);
1060 return;
1061 }
1062 auto lightIt = device->lightInfos.find(lightId);
1063 if (lightIt == device->lightInfos.end()) {
1064 ALOGE("Light Id %d does not exist.", lightId);
1065 return;
1066 }
1067
1068 if (!base::WriteStringToFile(std::to_string(brightness),
1069 lightIt->second.path /
1070 LIGHT_NODES.at(InputLightClass::BRIGHTNESS))) {
1071 ALOGE("Can not write to file, error: %s", strerror(errno));
1072 }
1073}
1074
1075void EventHub::setLightIntensities(int32_t deviceId, int32_t lightId,
1076 std::unordered_map<LightColor, int32_t> intensities) {
1077 std::scoped_lock _l(mLock);
1078
1079 Device* device = getDeviceLocked(deviceId);
1080 if (device == nullptr) {
1081 ALOGE("Device Id %d does not exist", deviceId);
1082 return;
1083 }
1084 auto lightIt = device->lightInfos.find(lightId);
1085 if (lightIt == device->lightInfos.end()) {
1086 ALOGE("Light Id %d does not exist.", lightId);
1087 return;
1088 }
1089
1090 auto ret =
1091 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1092
1093 if (!ret.has_value()) {
1094 return;
1095 }
1096 std::array<LightColor, COLOR_NUM> colors = ret.value();
1097
1098 std::string rgbStr;
1099 for (size_t i = 0; i < COLOR_NUM; i++) {
1100 auto it = intensities.find(colors[i]);
1101 if (it != intensities.end()) {
1102 rgbStr += std::to_string(it->second);
1103 // Insert space between colors
1104 if (i < COLOR_NUM - 1) {
1105 rgbStr += " ";
1106 }
1107 }
1108 }
1109 // Append new line
1110 rgbStr += "\n";
1111
1112 if (!base::WriteStringToFile(rgbStr,
1113 lightIt->second.path /
1114 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY))) {
1115 ALOGE("Can not write to file, error: %s", strerror(errno));
1116 }
1117}
1118
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001119void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Chris Ye87143712020-11-10 05:05:58 +00001120 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001121
1122 mExcludedDevices = devices;
1123}
1124
1125bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
Chris Ye87143712020-11-10 05:05:58 +00001126 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001127 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001128 if (device != nullptr && scanCode >= 0 && scanCode <= KEY_MAX) {
1129 return device->keyBitmask.test(scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001130 }
1131 return false;
1132}
1133
1134bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
Chris Ye87143712020-11-10 05:05:58 +00001135 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001136 Device* device = getDeviceLocked(deviceId);
1137 int32_t sc;
Chris Ye989bb932020-07-04 16:18:59 -07001138 if (device != nullptr && device->mapLed(led, &sc) == NO_ERROR) {
Chris Ye66fbac32020-07-06 20:36:43 -07001139 return device->ledBitmask.test(sc);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001140 }
1141 return false;
1142}
1143
1144void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
Chris Ye87143712020-11-10 05:05:58 +00001145 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001146 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -07001147 if (device != nullptr && device->hasValidFd()) {
1148 device->setLedStateLocked(led, on);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001149 }
1150}
1151
1152void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001153 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001154 outVirtualKeys.clear();
1155
Chris Ye87143712020-11-10 05:05:58 +00001156 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001157 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001158 if (device != nullptr && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001159 const std::vector<VirtualKeyDefinition> virtualKeys =
1160 device->virtualKeyMap->getVirtualKeys();
1161 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001162 }
1163}
1164
Chris Ye3a1e4462020-08-12 10:13:15 -07001165const std::shared_ptr<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001166 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001167 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001168 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001169 return device->getKeyCharacterMap();
1170 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001171 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001172}
1173
Chris Ye3a1e4462020-08-12 10:13:15 -07001174bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, std::shared_ptr<KeyCharacterMap> map) {
Chris Ye87143712020-11-10 05:05:58 +00001175 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001176 Device* device = getDeviceLocked(deviceId);
Chris Ye3a1e4462020-08-12 10:13:15 -07001177 if (device != nullptr && map != nullptr && device->keyMap.keyCharacterMap != nullptr) {
1178 device->keyMap.keyCharacterMap->combine(*map);
1179 device->keyMap.keyCharacterMapFile = device->keyMap.keyCharacterMap->getLoadFileName();
1180 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001181 }
1182 return false;
1183}
1184
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001185static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
1186 std::string rawDescriptor;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001187 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001188 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001189 if (!identifier.uniqueId.empty()) {
1190 rawDescriptor += "uniqueId:";
1191 rawDescriptor += identifier.uniqueId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001192 } else if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001193 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194 }
1195
1196 if (identifier.vendor == 0 && identifier.product == 0) {
1197 // If we don't know the vendor and product id, then the device is probably
1198 // built-in so we need to rely on other information to uniquely identify
1199 // the input device. Usually we try to avoid relying on the device name or
1200 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001201 if (!identifier.name.empty()) {
1202 rawDescriptor += "name:";
1203 rawDescriptor += identifier.name;
1204 } else if (!identifier.location.empty()) {
1205 rawDescriptor += "location:";
1206 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001207 }
1208 }
1209 identifier.descriptor = sha1(rawDescriptor);
1210 return rawDescriptor;
1211}
1212
1213void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
1214 // Compute a device descriptor that uniquely identifies the device.
1215 // The descriptor is assumed to be a stable identifier. Its value should not
1216 // change between reboots, reconnections, firmware updates or new releases
1217 // of Android. In practice we sometimes get devices that cannot be uniquely
1218 // identified. In this case we enforce uniqueness between connected devices.
1219 // Ideally, we also want the descriptor to be short and relatively opaque.
1220
1221 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001222 std::string rawDescriptor = generateDescriptor(identifier);
1223 if (identifier.uniqueId.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001224 // If it didn't have a unique id check for conflicts and enforce
1225 // uniqueness if necessary.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001226 while (getDeviceByDescriptorLocked(identifier.descriptor) != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001227 identifier.nonce++;
1228 rawDescriptor = generateDescriptor(identifier);
1229 }
1230 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001231 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001232 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001233}
1234
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001235void EventHub::vibrate(int32_t deviceId, const VibrationElement& element) {
Chris Ye87143712020-11-10 05:05:58 +00001236 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001238 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001239 ff_effect effect;
1240 memset(&effect, 0, sizeof(effect));
1241 effect.type = FF_RUMBLE;
1242 effect.id = device->ffEffectId;
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001243 // evdev FF_RUMBLE effect only supports two channels of vibration.
Chris Ye6393a262020-08-04 19:41:36 -07001244 effect.u.rumble.strong_magnitude = element.getMagnitude(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1245 effect.u.rumble.weak_magnitude = element.getMagnitude(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001246 effect.replay.length = element.duration.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001247 effect.replay.delay = 0;
1248 if (ioctl(device->fd, EVIOCSFF, &effect)) {
1249 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001250 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001251 return;
1252 }
1253 device->ffEffectId = effect.id;
1254
1255 struct input_event ev;
1256 ev.time.tv_sec = 0;
1257 ev.time.tv_usec = 0;
1258 ev.type = EV_FF;
1259 ev.code = device->ffEffectId;
1260 ev.value = 1;
1261 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1262 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001263 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001264 return;
1265 }
1266 device->ffEffectPlaying = true;
1267 }
1268}
1269
1270void EventHub::cancelVibrate(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001271 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001272 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001273 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001274 if (device->ffEffectPlaying) {
1275 device->ffEffectPlaying = false;
1276
1277 struct input_event ev;
1278 ev.time.tv_sec = 0;
1279 ev.time.tv_usec = 0;
1280 ev.type = EV_FF;
1281 ev.code = device->ffEffectId;
1282 ev.value = 0;
1283 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1284 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001285 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001286 return;
1287 }
1288 }
1289 }
1290}
1291
Chris Ye87143712020-11-10 05:05:58 +00001292std::vector<int32_t> EventHub::getVibratorIds(int32_t deviceId) {
1293 std::scoped_lock _l(mLock);
1294 std::vector<int32_t> vibrators;
1295 Device* device = getDeviceLocked(deviceId);
1296 if (device != nullptr && device->hasValidFd() &&
1297 device->classes.test(InputDeviceClass::VIBRATOR)) {
1298 vibrators.push_back(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1299 vibrators.push_back(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
1300 }
1301 return vibrators;
1302}
1303
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001304EventHub::Device* EventHub::getDeviceByDescriptorLocked(const std::string& descriptor) const {
Chris Ye989bb932020-07-04 16:18:59 -07001305 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001306 if (descriptor == device->identifier.descriptor) {
Chris Ye989bb932020-07-04 16:18:59 -07001307 return device.get();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001308 }
1309 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001310 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001311}
1312
1313EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001314 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001315 deviceId = mBuiltInKeyboardId;
1316 }
Chris Ye989bb932020-07-04 16:18:59 -07001317 const auto& it = mDevices.find(deviceId);
1318 return it != mDevices.end() ? it->second.get() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001319}
1320
Chris Ye8594e192020-07-14 10:34:06 -07001321EventHub::Device* EventHub::getDeviceByPathLocked(const std::string& devicePath) const {
Chris Ye989bb932020-07-04 16:18:59 -07001322 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001323 if (device->path == devicePath) {
Chris Ye989bb932020-07-04 16:18:59 -07001324 return device.get();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001325 }
1326 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001327 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001328}
1329
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001330/**
1331 * The file descriptor could be either input device, or a video device (associated with a
1332 * specific input device). Check both cases here, and return the device that this event
1333 * belongs to. Caller can compare the fd's once more to determine event type.
1334 * Looks through all input devices, and only attached video devices. Unattached video
1335 * devices are ignored.
1336 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001337EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
Chris Ye989bb932020-07-04 16:18:59 -07001338 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001339 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001340 // This is an input device event
Chris Ye989bb932020-07-04 16:18:59 -07001341 return device.get();
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001342 }
1343 if (device->videoDevice && device->videoDevice->getFd() == fd) {
1344 // This is a video device event
Chris Ye989bb932020-07-04 16:18:59 -07001345 return device.get();
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001346 }
1347 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001348 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
1349 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001350 return nullptr;
1351}
1352
Kim Low03ea0352020-11-06 12:45:07 -08001353std::optional<int32_t> EventHub::getBatteryCapacity(int32_t deviceId) const {
1354 std::scoped_lock _l(mLock);
1355 Device* device = getDeviceLocked(deviceId);
1356 std::string buffer;
1357
Chris Ye3fdbfef2021-01-06 18:45:18 -08001358 if (device == nullptr || !device->sysfsBatteryPath.has_value()) {
Kim Low03ea0352020-11-06 12:45:07 -08001359 return std::nullopt;
1360 }
1361
1362 // Some devices report battery capacity as an integer through the "capacity" file
Chris Ye3fdbfef2021-01-06 18:45:18 -08001363 if (base::ReadFileToString(device->sysfsBatteryPath.value() / "capacity", &buffer)) {
Kim Low03ea0352020-11-06 12:45:07 -08001364 return std::stoi(buffer);
1365 }
1366
1367 // Other devices report capacity as an enum value POWER_SUPPLY_CAPACITY_LEVEL_XXX
1368 // These values are taken from kernel source code include/linux/power_supply.h
Chris Ye3fdbfef2021-01-06 18:45:18 -08001369 if (base::ReadFileToString(device->sysfsBatteryPath.value() / "capacity_level", &buffer)) {
Kim Low03ea0352020-11-06 12:45:07 -08001370 const auto it = BATTERY_LEVEL.find(buffer);
1371 if (it != BATTERY_LEVEL.end()) {
1372 return it->second;
1373 }
1374 }
1375 return std::nullopt;
1376}
1377
1378std::optional<int32_t> EventHub::getBatteryStatus(int32_t deviceId) const {
1379 std::scoped_lock _l(mLock);
1380 Device* device = getDeviceLocked(deviceId);
1381 std::string buffer;
1382
Chris Ye3fdbfef2021-01-06 18:45:18 -08001383 if (device == nullptr || !device->sysfsBatteryPath.has_value()) {
Kim Low03ea0352020-11-06 12:45:07 -08001384 return std::nullopt;
1385 }
1386
Chris Ye3fdbfef2021-01-06 18:45:18 -08001387 if (!base::ReadFileToString(device->sysfsBatteryPath.value() / "status", &buffer)) {
Kim Low03ea0352020-11-06 12:45:07 -08001388 ALOGE("Failed to read sysfs battery info: %s", strerror(errno));
1389 return std::nullopt;
1390 }
1391
1392 // Remove trailing new line
1393 buffer.erase(std::remove(buffer.begin(), buffer.end(), '\n'), buffer.end());
1394 const auto it = BATTERY_STATUS.find(buffer);
1395
1396 if (it != BATTERY_STATUS.end()) {
1397 return it->second;
1398 }
1399
1400 return std::nullopt;
1401}
1402
Michael Wrightd02c5b62014-02-10 15:10:22 -08001403size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
1404 ALOG_ASSERT(bufferSize >= 1);
1405
Chris Ye87143712020-11-10 05:05:58 +00001406 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001407
1408 struct input_event readBuffer[bufferSize];
1409
1410 RawEvent* event = buffer;
1411 size_t capacity = bufferSize;
1412 bool awoken = false;
1413 for (;;) {
1414 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
1415
1416 // Reopen input devices if needed.
1417 if (mNeedToReopenDevices) {
1418 mNeedToReopenDevices = false;
1419
1420 ALOGI("Reopening all input devices due to a configuration change.");
1421
1422 closeAllDevicesLocked();
1423 mNeedToScanDevices = true;
1424 break; // return to the caller before we actually rescan
1425 }
1426
1427 // Report any devices that had last been added/removed.
Chris Ye989bb932020-07-04 16:18:59 -07001428 for (auto it = mClosingDevices.begin(); it != mClosingDevices.end();) {
1429 std::unique_ptr<Device> device = std::move(*it);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001430 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001431 event->when = now;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001432 event->deviceId = (device->id == mBuiltInKeyboardId)
1433 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
1434 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001435 event->type = DEVICE_REMOVED;
1436 event += 1;
Chris Ye989bb932020-07-04 16:18:59 -07001437 it = mClosingDevices.erase(it);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001438 mNeedToSendFinishedDeviceScan = true;
1439 if (--capacity == 0) {
1440 break;
1441 }
1442 }
1443
1444 if (mNeedToScanDevices) {
1445 mNeedToScanDevices = false;
1446 scanDevicesLocked();
1447 mNeedToSendFinishedDeviceScan = true;
1448 }
1449
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001450 while (!mOpeningDevices.empty()) {
1451 std::unique_ptr<Device> device = std::move(*mOpeningDevices.rbegin());
1452 mOpeningDevices.pop_back();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001453 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001454 event->when = now;
1455 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1456 event->type = DEVICE_ADDED;
1457 event += 1;
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001458
1459 // Try to find a matching video device by comparing device names
1460 for (auto it = mUnattachedVideoDevices.begin(); it != mUnattachedVideoDevices.end();
1461 it++) {
1462 std::unique_ptr<TouchVideoDevice>& videoDevice = *it;
1463 if (tryAddVideoDevice(*device, videoDevice)) {
1464 // videoDevice was transferred to 'device'
1465 it = mUnattachedVideoDevices.erase(it);
1466 break;
1467 }
1468 }
1469
1470 auto [dev_it, inserted] = mDevices.insert_or_assign(device->id, std::move(device));
1471 if (!inserted) {
Chris Ye989bb932020-07-04 16:18:59 -07001472 ALOGW("Device id %d exists, replaced.", device->id);
1473 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001474 mNeedToSendFinishedDeviceScan = true;
1475 if (--capacity == 0) {
1476 break;
1477 }
1478 }
1479
1480 if (mNeedToSendFinishedDeviceScan) {
1481 mNeedToSendFinishedDeviceScan = false;
1482 event->when = now;
1483 event->type = FINISHED_DEVICE_SCAN;
1484 event += 1;
1485 if (--capacity == 0) {
1486 break;
1487 }
1488 }
1489
1490 // Grab the next input event.
1491 bool deviceChanged = false;
1492 while (mPendingEventIndex < mPendingEventCount) {
1493 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001494 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001495 if (eventItem.events & EPOLLIN) {
1496 mPendingINotify = true;
1497 } else {
1498 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
1499 }
1500 continue;
1501 }
1502
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001503 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001504 if (eventItem.events & EPOLLIN) {
1505 ALOGV("awoken after wake()");
1506 awoken = true;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001507 char wakeReadBuffer[16];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001508 ssize_t nRead;
1509 do {
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001510 nRead = read(mWakeReadPipeFd, wakeReadBuffer, sizeof(wakeReadBuffer));
1511 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(wakeReadBuffer));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001512 } else {
1513 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001514 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001515 }
1516 continue;
1517 }
1518
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001519 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Chris Ye989bb932020-07-04 16:18:59 -07001520 if (device == nullptr) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001521 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
1522 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001523 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001524 continue;
1525 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001526 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
1527 if (eventItem.events & EPOLLIN) {
1528 size_t numFrames = device->videoDevice->readAndQueueFrames();
1529 if (numFrames == 0) {
1530 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001531 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001532 }
1533 } else if (eventItem.events & EPOLLHUP) {
1534 // TODO(b/121395353) - consider adding EPOLLRDHUP
1535 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001536 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001537 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1538 device->videoDevice = nullptr;
1539 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001540 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1541 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001542 ALOG_ASSERT(!DEBUG);
1543 }
1544 continue;
1545 }
1546 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -08001547 if (eventItem.events & EPOLLIN) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001548 int32_t readSize =
1549 read(device->fd, readBuffer, sizeof(struct input_event) * capacity);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001550 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
1551 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -07001552 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001553 " bufferSize: %zu capacity: %zu errno: %d)\n",
1554 device->fd, readSize, bufferSize, capacity, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001555 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001556 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001557 } else if (readSize < 0) {
1558 if (errno != EAGAIN && errno != EINTR) {
1559 ALOGW("could not get event (errno=%d)", errno);
1560 }
1561 } else if ((readSize % sizeof(struct input_event)) != 0) {
1562 ALOGE("could not get event (wrong size: %d)", readSize);
1563 } else {
1564 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1565
1566 size_t count = size_t(readSize) / sizeof(struct input_event);
1567 for (size_t i = 0; i < count; i++) {
1568 struct input_event& iev = readBuffer[i];
Siarhei Vishniakou592bac22018-11-08 19:42:38 -08001569 event->when = processEventTimestamp(iev);
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001570 event->readTime = systemTime(SYSTEM_TIME_MONOTONIC);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001571 event->deviceId = deviceId;
1572 event->type = iev.type;
1573 event->code = iev.code;
1574 event->value = iev.value;
1575 event += 1;
1576 capacity -= 1;
1577 }
1578 if (capacity == 0) {
1579 // The result buffer is full. Reset the pending event index
1580 // so we will try to read the device again on the next iteration.
1581 mPendingEventIndex -= 1;
1582 break;
1583 }
1584 }
1585 } else if (eventItem.events & EPOLLHUP) {
1586 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001587 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001588 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001589 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001590 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001591 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1592 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001593 }
1594 }
1595
1596 // readNotify() will modify the list of devices so this must be done after
1597 // processing all other events to ensure that we read all remaining events
1598 // before closing the devices.
1599 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
1600 mPendingINotify = false;
1601 readNotifyLocked();
1602 deviceChanged = true;
1603 }
1604
1605 // Report added or removed devices immediately.
1606 if (deviceChanged) {
1607 continue;
1608 }
1609
1610 // Return now if we have collected any events or if we were explicitly awoken.
1611 if (event != buffer || awoken) {
1612 break;
1613 }
1614
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001615 // Poll for events.
1616 // When a device driver has pending (unread) events, it acquires
1617 // a kernel wake lock. Once the last pending event has been read, the device
1618 // driver will release the kernel wake lock, but the epoll will hold the wakelock,
1619 // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
1620 // is called again for the same fd that produced the event.
1621 // Thus the system can only sleep if there are no events pending or
1622 // currently being processed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001623 //
1624 // The timeout is advisory only. If the device is asleep, it will not wake just to
1625 // service the timeout.
1626 mPendingEventIndex = 0;
1627
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001628 mLock.unlock(); // release lock before poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001629
1630 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1631
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001632 mLock.lock(); // reacquire lock after poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001633
1634 if (pollResult == 0) {
1635 // Timed out.
1636 mPendingEventCount = 0;
1637 break;
1638 }
1639
1640 if (pollResult < 0) {
1641 // An error occurred.
1642 mPendingEventCount = 0;
1643
1644 // Sleep after errors to avoid locking up the system.
1645 // Hopefully the error is transient.
1646 if (errno != EINTR) {
1647 ALOGW("poll failed (errno=%d)\n", errno);
1648 usleep(100000);
1649 }
1650 } else {
1651 // Some events occurred.
1652 mPendingEventCount = size_t(pollResult);
1653 }
1654 }
1655
1656 // All done, return the number of events we read.
1657 return event - buffer;
1658}
1659
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001660std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001661 std::scoped_lock _l(mLock);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001662
1663 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001664 if (device == nullptr || !device->videoDevice) {
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001665 return {};
1666 }
1667 return device->videoDevice->consumeFrames();
1668}
1669
Michael Wrightd02c5b62014-02-10 15:10:22 -08001670void EventHub::wake() {
1671 ALOGV("wake() called");
1672
1673 ssize_t nWrite;
1674 do {
1675 nWrite = write(mWakeWritePipeFd, "W", 1);
1676 } while (nWrite == -1 && errno == EINTR);
1677
1678 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001679 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001680 }
1681}
1682
1683void EventHub::scanDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001684 status_t result = scanDirLocked(DEVICE_PATH);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001685 if (result < 0) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001686 ALOGE("scan dir failed for %s", DEVICE_PATH);
1687 }
Philip Quinn39b81682019-01-09 22:20:39 -08001688 if (isV4lScanningEnabled()) {
1689 result = scanVideoDirLocked(VIDEO_DEVICE_PATH);
1690 if (result != OK) {
1691 ALOGE("scan video dir failed for %s", VIDEO_DEVICE_PATH);
1692 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001693 }
Chris Ye989bb932020-07-04 16:18:59 -07001694 if (mDevices.find(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) == mDevices.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001695 createVirtualKeyboardLocked();
1696 }
1697}
1698
1699// ----------------------------------------------------------------------------
1700
Michael Wrightd02c5b62014-02-10 15:10:22 -08001701static const int32_t GAMEPAD_KEYCODES[] = {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001702 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C, //
1703 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z, //
1704 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1, //
1705 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2, //
1706 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR, //
1707 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE, //
Michael Wrightd02c5b62014-02-10 15:10:22 -08001708};
1709
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001710status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001711 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001712 struct epoll_event eventItem = {};
1713 eventItem.events = EPOLLIN | EPOLLWAKEUP;
1714 eventItem.data.fd = fd;
1715 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1716 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001717 return -errno;
1718 }
1719 return OK;
1720}
1721
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001722status_t EventHub::unregisterFdFromEpoll(int fd) {
1723 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
1724 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
1725 return -errno;
1726 }
1727 return OK;
1728}
1729
Chris Ye989bb932020-07-04 16:18:59 -07001730status_t EventHub::registerDeviceForEpollLocked(Device& device) {
1731 status_t result = registerFdForEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001732 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07001733 ALOGE("Could not add input device fd to epoll for device %" PRId32, device.id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001734 return result;
1735 }
Chris Ye989bb932020-07-04 16:18:59 -07001736 if (device.videoDevice) {
1737 registerVideoDeviceForEpollLocked(*device.videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001738 }
1739 return result;
1740}
1741
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001742void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
1743 status_t result = registerFdForEpoll(videoDevice.getFd());
1744 if (result != OK) {
1745 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
1746 }
1747}
1748
Chris Ye989bb932020-07-04 16:18:59 -07001749status_t EventHub::unregisterDeviceFromEpollLocked(Device& device) {
1750 if (device.hasValidFd()) {
1751 status_t result = unregisterFdFromEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001752 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07001753 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device.id);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001754 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001755 }
1756 }
Chris Ye989bb932020-07-04 16:18:59 -07001757 if (device.videoDevice) {
1758 unregisterVideoDeviceFromEpollLocked(*device.videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001759 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001760 return OK;
1761}
1762
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001763void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
1764 if (videoDevice.hasValidFd()) {
1765 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
1766 if (result != OK) {
1767 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001768 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001769 }
1770 }
1771}
1772
Chris Ye8594e192020-07-14 10:34:06 -07001773status_t EventHub::openDeviceLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001774 char buffer[80];
1775
Chris Ye8594e192020-07-14 10:34:06 -07001776 ALOGV("Opening device: %s", devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001777
Chris Ye8594e192020-07-14 10:34:06 -07001778 int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001779 if (fd < 0) {
Chris Ye8594e192020-07-14 10:34:06 -07001780 ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001781 return -1;
1782 }
1783
1784 InputDeviceIdentifier identifier;
1785
1786 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001787 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Chris Ye8594e192020-07-14 10:34:06 -07001788 ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001789 } else {
1790 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001791 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001792 }
1793
1794 // Check to see if the device is on our excluded list
1795 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001796 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001797 if (identifier.name == item) {
Chris Ye8594e192020-07-14 10:34:06 -07001798 ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799 close(fd);
1800 return -1;
1801 }
1802 }
1803
1804 // Get device driver version.
1805 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001806 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Chris Ye8594e192020-07-14 10:34:06 -07001807 ALOGE("could not get driver version for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001808 close(fd);
1809 return -1;
1810 }
1811
1812 // Get device identifier.
1813 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001814 if (ioctl(fd, EVIOCGID, &inputId)) {
Chris Ye8594e192020-07-14 10:34:06 -07001815 ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001816 close(fd);
1817 return -1;
1818 }
1819 identifier.bus = inputId.bustype;
1820 identifier.product = inputId.product;
1821 identifier.vendor = inputId.vendor;
1822 identifier.version = inputId.version;
1823
1824 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001825 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
1826 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001827 } else {
1828 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001829 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001830 }
1831
1832 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001833 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
1834 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001835 } else {
1836 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001837 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001838 }
1839
1840 // Fill in the descriptor.
1841 assignDescriptorLocked(identifier);
1842
Michael Wrightd02c5b62014-02-10 15:10:22 -08001843 // Allocate device. (The device object takes ownership of the fd at this point.)
1844 int32_t deviceId = mNextDeviceId++;
Chris Ye989bb932020-07-04 16:18:59 -07001845 std::unique_ptr<Device> device = std::make_unique<Device>(fd, deviceId, devicePath, identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001846
Chris Ye8594e192020-07-14 10:34:06 -07001847 ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001848 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001849 " vendor %04x\n"
1850 " product %04x\n"
1851 " version %04x\n",
1852 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001853 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
1854 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
1855 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
1856 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001857 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
1858 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001859
1860 // Load the configuration file for the device.
Chris Ye989bb932020-07-04 16:18:59 -07001861 device->loadConfigurationLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001862
Chris Ye3fdbfef2021-01-06 18:45:18 -08001863 // Grab the device's sysfs path
1864 device->sysfsRootPath = getSysfsRootPath(devicePath.c_str());
1865 // find related components
1866 bool hasBattery = device->configureBatteryLocked();
1867 bool hasLights = device->configureLightsLocked();
1868
Michael Wrightd02c5b62014-02-10 15:10:22 -08001869 // Figure out the kinds of events the device reports.
Chris Ye66fbac32020-07-06 20:36:43 -07001870 device->readDeviceBitMask(EVIOCGBIT(EV_KEY, 0), device->keyBitmask);
1871 device->readDeviceBitMask(EVIOCGBIT(EV_ABS, 0), device->absBitmask);
1872 device->readDeviceBitMask(EVIOCGBIT(EV_REL, 0), device->relBitmask);
1873 device->readDeviceBitMask(EVIOCGBIT(EV_SW, 0), device->swBitmask);
1874 device->readDeviceBitMask(EVIOCGBIT(EV_LED, 0), device->ledBitmask);
1875 device->readDeviceBitMask(EVIOCGBIT(EV_FF, 0), device->ffBitmask);
Chris Yef59a2f42020-10-16 12:55:26 -07001876 device->readDeviceBitMask(EVIOCGBIT(EV_MSC, 0), device->mscBitmask);
Chris Ye66fbac32020-07-06 20:36:43 -07001877 device->readDeviceBitMask(EVIOCGPROP(0), device->propBitmask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001878
1879 // See if this is a keyboard. Ignore everything in the button range except for
1880 // joystick and gamepad buttons which are handled like keyboards for the most part.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001881 bool haveKeyboardKeys =
Chris Ye66fbac32020-07-06 20:36:43 -07001882 device->keyBitmask.any(0, BTN_MISC) || device->keyBitmask.any(BTN_WHEEL, KEY_MAX + 1);
1883 bool haveGamepadButtons = device->keyBitmask.any(BTN_MISC, BTN_MOUSE) ||
1884 device->keyBitmask.any(BTN_JOYSTICK, BTN_DIGI);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001885 if (haveKeyboardKeys || haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001886 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001887 }
1888
1889 // See if this is a cursor device such as a trackball or mouse.
Chris Ye66fbac32020-07-06 20:36:43 -07001890 if (device->keyBitmask.test(BTN_MOUSE) && device->relBitmask.test(REL_X) &&
1891 device->relBitmask.test(REL_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001892 device->classes |= InputDeviceClass::CURSOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001893 }
1894
Prashant Malani1941ff52015-08-11 18:29:28 -07001895 // See if this is a rotary encoder type device.
1896 String8 deviceType = String8();
1897 if (device->configuration &&
1898 device->configuration->tryGetProperty(String8("device.type"), deviceType)) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001899 if (!deviceType.compare(String8("rotaryEncoder"))) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001900 device->classes |= InputDeviceClass::ROTARY_ENCODER;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001901 }
Prashant Malani1941ff52015-08-11 18:29:28 -07001902 }
1903
Michael Wrightd02c5b62014-02-10 15:10:22 -08001904 // See if this is a touch pad.
1905 // Is this a new modern multi-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07001906 if (device->absBitmask.test(ABS_MT_POSITION_X) && device->absBitmask.test(ABS_MT_POSITION_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001907 // Some joysticks such as the PS3 controller report axes that conflict
1908 // with the ABS_MT range. Try to confirm that the device really is
1909 // a touch screen.
Chris Ye66fbac32020-07-06 20:36:43 -07001910 if (device->keyBitmask.test(BTN_TOUCH) || !haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001911 device->classes |= (InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001912 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001913 // Is this an old style single-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07001914 } else if (device->keyBitmask.test(BTN_TOUCH) && device->absBitmask.test(ABS_X) &&
1915 device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001916 device->classes |= InputDeviceClass::TOUCH;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001917 // Is this a BT stylus?
Chris Ye66fbac32020-07-06 20:36:43 -07001918 } else if ((device->absBitmask.test(ABS_PRESSURE) || device->keyBitmask.test(BTN_TOUCH)) &&
1919 !device->absBitmask.test(ABS_X) && !device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001920 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -07001921 // Keyboard will try to claim some of the buttons but we really want to reserve those so we
1922 // can fuse it with the touch screen data, so just take them back. Note this means an
1923 // external stylus cannot also be a keyboard device.
Chris Ye1b0c7342020-07-28 21:57:03 -07001924 device->classes &= ~InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001925 }
1926
1927 // See if this device is a joystick.
1928 // Assumes that joysticks always have gamepad buttons in order to distinguish them
1929 // from other devices such as accelerometers that also have absolute axes.
1930 if (haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001931 auto assumedClasses = device->classes | InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001932 for (int i = 0; i <= ABS_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07001933 if (device->absBitmask.test(i) &&
Chris Ye1b0c7342020-07-28 21:57:03 -07001934 (getAbsAxisUsage(i, assumedClasses).test(InputDeviceClass::JOYSTICK))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001935 device->classes = assumedClasses;
1936 break;
1937 }
1938 }
1939 }
1940
Chris Yef59a2f42020-10-16 12:55:26 -07001941 // Check whether this device is an accelerometer.
1942 if (device->propBitmask.test(INPUT_PROP_ACCELEROMETER)) {
1943 device->classes |= InputDeviceClass::SENSOR;
1944 }
1945
Michael Wrightd02c5b62014-02-10 15:10:22 -08001946 // Check whether this device has switches.
1947 for (int i = 0; i <= SW_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07001948 if (device->swBitmask.test(i)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001949 device->classes |= InputDeviceClass::SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001950 break;
1951 }
1952 }
1953
1954 // Check whether this device supports the vibrator.
Chris Ye66fbac32020-07-06 20:36:43 -07001955 if (device->ffBitmask.test(FF_RUMBLE)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001956 device->classes |= InputDeviceClass::VIBRATOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001957 }
1958
1959 // Configure virtual keys.
Chris Ye1b0c7342020-07-28 21:57:03 -07001960 if ((device->classes.test(InputDeviceClass::TOUCH))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001961 // Load the virtual keys for the touch screen, if any.
1962 // We do this now so that we can make sure to load the keymap if necessary.
Chris Ye989bb932020-07-04 16:18:59 -07001963 bool success = device->loadVirtualKeyMapLocked();
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001964 if (success) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001965 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001966 }
1967 }
1968
1969 // Load the key map.
Chris Yef59a2f42020-10-16 12:55:26 -07001970 // We need to do this for joysticks too because the key layout may specify axes, and for
1971 // sensor as well because the key layout may specify the axes to sensor data mapping.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001972 status_t keyMapStatus = NAME_NOT_FOUND;
Chris Yef59a2f42020-10-16 12:55:26 -07001973 if (device->classes.any(InputDeviceClass::KEYBOARD | InputDeviceClass::JOYSTICK |
1974 InputDeviceClass::SENSOR)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001975 // Load the keymap for the device.
Chris Ye989bb932020-07-04 16:18:59 -07001976 keyMapStatus = device->loadKeyMapLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001977 }
1978
1979 // Configure the keyboard, gamepad or virtual keyboard.
Chris Ye1b0c7342020-07-28 21:57:03 -07001980 if (device->classes.test(InputDeviceClass::KEYBOARD)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001981 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001982 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05001983 isEligibleBuiltInKeyboard(device->identifier, device->configuration.get(),
1984 &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001985 mBuiltInKeyboardId = device->id;
1986 }
1987
1988 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
Chris Ye989bb932020-07-04 16:18:59 -07001989 if (device->hasKeycodeLocked(AKEYCODE_Q)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001990 device->classes |= InputDeviceClass::ALPHAKEY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001991 }
1992
1993 // See if this device has a DPAD.
Chris Ye989bb932020-07-04 16:18:59 -07001994 if (device->hasKeycodeLocked(AKEYCODE_DPAD_UP) &&
1995 device->hasKeycodeLocked(AKEYCODE_DPAD_DOWN) &&
1996 device->hasKeycodeLocked(AKEYCODE_DPAD_LEFT) &&
1997 device->hasKeycodeLocked(AKEYCODE_DPAD_RIGHT) &&
1998 device->hasKeycodeLocked(AKEYCODE_DPAD_CENTER)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001999 device->classes |= InputDeviceClass::DPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002000 }
2001
2002 // See if this device has a gamepad.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002003 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES) / sizeof(GAMEPAD_KEYCODES[0]); i++) {
Chris Ye989bb932020-07-04 16:18:59 -07002004 if (device->hasKeycodeLocked(GAMEPAD_KEYCODES[i])) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002005 device->classes |= InputDeviceClass::GAMEPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002006 break;
2007 }
2008 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002009 }
2010
2011 // If the device isn't recognized as something we handle, don't monitor it.
Chris Ye1b0c7342020-07-28 21:57:03 -07002012 if (device->classes == Flags<InputDeviceClass>(0)) {
Chris Ye8594e192020-07-14 10:34:06 -07002013 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002014 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002015 return -1;
2016 }
2017
Chris Ye3fdbfef2021-01-06 18:45:18 -08002018 // Classify InputDeviceClass::BATTERY.
2019 if (hasBattery) {
2020 device->classes |= InputDeviceClass::BATTERY;
2021 }
Kim Low03ea0352020-11-06 12:45:07 -08002022
Chris Ye3fdbfef2021-01-06 18:45:18 -08002023 // Classify InputDeviceClass::LIGHT.
2024 if (hasLights) {
2025 device->classes |= InputDeviceClass::LIGHT;
Kim Low03ea0352020-11-06 12:45:07 -08002026 }
2027
Tim Kilbourn063ff532015-04-08 10:26:18 -07002028 // Determine whether the device has a mic.
Chris Ye989bb932020-07-04 16:18:59 -07002029 if (device->deviceHasMicLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002030 device->classes |= InputDeviceClass::MIC;
Tim Kilbourn063ff532015-04-08 10:26:18 -07002031 }
2032
Michael Wrightd02c5b62014-02-10 15:10:22 -08002033 // Determine whether the device is external or internal.
Chris Ye989bb932020-07-04 16:18:59 -07002034 if (device->isExternalDeviceLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002035 device->classes |= InputDeviceClass::EXTERNAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002036 }
2037
Chris Ye1b0c7342020-07-28 21:57:03 -07002038 if (device->classes.any(InputDeviceClass::JOYSTICK | InputDeviceClass::DPAD) &&
2039 device->classes.test(InputDeviceClass::GAMEPAD)) {
Chris Ye989bb932020-07-04 16:18:59 -07002040 device->controllerNumber = getNextControllerNumberLocked(device->identifier.name);
2041 device->setLedForControllerLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002042 }
2043
Chris Ye989bb932020-07-04 16:18:59 -07002044 if (registerDeviceForEpollLocked(*device) != OK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002045 return -1;
2046 }
2047
Chris Ye989bb932020-07-04 16:18:59 -07002048 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002049
Chris Ye1b0c7342020-07-28 21:57:03 -07002050 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=%s, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002051 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Chris Ye1b0c7342020-07-28 21:57:03 -07002052 deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(),
2053 device->classes.string().c_str(), device->configurationFile.c_str(),
2054 device->keyMap.keyLayoutFile.c_str(), device->keyMap.keyCharacterMapFile.c_str(),
2055 toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002056
Chris Ye989bb932020-07-04 16:18:59 -07002057 addDeviceLocked(std::move(device));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002058 return OK;
2059}
2060
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002061void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
2062 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
2063 if (!videoDevice) {
2064 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
2065 return;
2066 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002067 // Transfer ownership of this video device to a matching input device
Chris Ye989bb932020-07-04 16:18:59 -07002068 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002069 if (tryAddVideoDevice(*device, videoDevice)) {
2070 return; // 'device' now owns 'videoDevice'
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002071 }
2072 }
2073
2074 // Couldn't find a matching input device, so just add it to a temporary holding queue.
2075 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002076 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002077 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002078 mUnattachedVideoDevices.push_back(std::move(videoDevice));
2079}
2080
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002081bool EventHub::tryAddVideoDevice(EventHub::Device& device,
2082 std::unique_ptr<TouchVideoDevice>& videoDevice) {
2083 if (videoDevice->getName() != device.identifier.name) {
2084 return false;
2085 }
2086 device.videoDevice = std::move(videoDevice);
2087 if (device.enabled) {
2088 registerVideoDeviceForEpollLocked(*device.videoDevice);
2089 }
2090 return true;
2091}
2092
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002093bool EventHub::isDeviceEnabled(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002094 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002095 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002096 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002097 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2098 return false;
2099 }
2100 return device->enabled;
2101}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002102
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002103status_t EventHub::enableDevice(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 BAD_VALUE;
2109 }
2110 if (device->enabled) {
2111 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
2112 return OK;
2113 }
2114 status_t result = device->enable();
2115 if (result != OK) {
2116 ALOGE("Failed to enable device %" PRId32, deviceId);
2117 return result;
2118 }
2119
Chris Ye989bb932020-07-04 16:18:59 -07002120 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002121
Chris Ye989bb932020-07-04 16:18:59 -07002122 return registerDeviceForEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002123}
2124
2125status_t EventHub::disableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002126 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002127 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002128 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002129 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2130 return BAD_VALUE;
2131 }
2132 if (!device->enabled) {
2133 ALOGW("Duplicate call to %s, input device already disabled", __func__);
2134 return OK;
2135 }
Chris Ye989bb932020-07-04 16:18:59 -07002136 unregisterDeviceFromEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002137 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002138}
2139
2140void EventHub::createVirtualKeyboardLocked() {
2141 InputDeviceIdentifier identifier;
2142 identifier.name = "Virtual";
2143 identifier.uniqueId = "<virtual>";
2144 assignDescriptorLocked(identifier);
2145
Chris Ye989bb932020-07-04 16:18:59 -07002146 std::unique_ptr<Device> device =
2147 std::make_unique<Device>(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
2148 identifier);
Chris Ye1b0c7342020-07-28 21:57:03 -07002149 device->classes = InputDeviceClass::KEYBOARD | InputDeviceClass::ALPHAKEY |
2150 InputDeviceClass::DPAD | InputDeviceClass::VIRTUAL;
Chris Ye989bb932020-07-04 16:18:59 -07002151 device->loadKeyMapLocked();
2152 addDeviceLocked(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002153}
2154
Chris Ye989bb932020-07-04 16:18:59 -07002155void EventHub::addDeviceLocked(std::unique_ptr<Device> device) {
2156 mOpeningDevices.push_back(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002157}
2158
Chris Ye989bb932020-07-04 16:18:59 -07002159int32_t EventHub::getNextControllerNumberLocked(const std::string& name) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002160 if (mControllerNumbers.isFull()) {
2161 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Chris Ye989bb932020-07-04 16:18:59 -07002162 name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002163 return 0;
2164 }
2165 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
2166 // one
2167 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
2168}
2169
Chris Ye989bb932020-07-04 16:18:59 -07002170void EventHub::releaseControllerNumberLocked(int32_t num) {
2171 if (num > 0) {
2172 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002173 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002174}
2175
Chris Ye8594e192020-07-14 10:34:06 -07002176void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002177 Device* device = getDeviceByPathLocked(devicePath);
Chris Ye989bb932020-07-04 16:18:59 -07002178 if (device != nullptr) {
2179 closeDeviceLocked(*device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002180 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002181 }
Chris Ye8594e192020-07-14 10:34:06 -07002182 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002183}
2184
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002185/**
2186 * Find the video device by filename, and close it.
2187 * The video device is closed by path during an inotify event, where we don't have the
2188 * additional context about the video device fd, or the associated input device.
2189 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002190void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002191 // A video device may be owned by an existing input device, or it may be stored in
2192 // the mUnattachedVideoDevices queue. Check both locations.
Chris Ye989bb932020-07-04 16:18:59 -07002193 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002194 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002195 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002196 device->videoDevice = nullptr;
2197 return;
2198 }
2199 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002200 mUnattachedVideoDevices
2201 .erase(std::remove_if(mUnattachedVideoDevices.begin(), mUnattachedVideoDevices.end(),
2202 [&devicePath](
2203 const std::unique_ptr<TouchVideoDevice>& videoDevice) {
2204 return videoDevice->getPath() == devicePath;
2205 }),
2206 mUnattachedVideoDevices.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002207}
2208
2209void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002210 mUnattachedVideoDevices.clear();
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002211 while (!mDevices.empty()) {
2212 closeDeviceLocked(*(mDevices.begin()->second));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002213 }
2214}
2215
Chris Ye989bb932020-07-04 16:18:59 -07002216void EventHub::closeDeviceLocked(Device& device) {
2217 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=%s", device.path.c_str(),
2218 device.identifier.name.c_str(), device.id, device.fd, device.classes.string().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002219
Chris Ye989bb932020-07-04 16:18:59 -07002220 if (device.id == mBuiltInKeyboardId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002221 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Chris Ye989bb932020-07-04 16:18:59 -07002222 device.path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002223 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
2224 }
2225
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002226 unregisterDeviceFromEpollLocked(device);
Chris Ye989bb932020-07-04 16:18:59 -07002227 if (device.videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002228 // This must be done after the video device is removed from epoll
Chris Ye989bb932020-07-04 16:18:59 -07002229 mUnattachedVideoDevices.push_back(std::move(device.videoDevice));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002230 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002231
Chris Ye989bb932020-07-04 16:18:59 -07002232 releaseControllerNumberLocked(device.controllerNumber);
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002233 device.controllerNumber = 0;
Chris Ye989bb932020-07-04 16:18:59 -07002234 device.close();
Chris Ye989bb932020-07-04 16:18:59 -07002235 mClosingDevices.push_back(std::move(mDevices[device.id]));
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002236
Chris Ye989bb932020-07-04 16:18:59 -07002237 mDevices.erase(device.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002238}
2239
2240status_t EventHub::readNotifyLocked() {
2241 int res;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242 char event_buf[512];
2243 int event_size;
2244 int event_pos = 0;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002245 struct inotify_event* event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002246
2247 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
2248 res = read(mINotifyFd, event_buf, sizeof(event_buf));
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002249 if (res < (int)sizeof(*event)) {
2250 if (errno == EINTR) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002251 ALOGW("could not get event, %s\n", strerror(errno));
2252 return -1;
2253 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002254
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002255 while (res >= (int)sizeof(*event)) {
2256 event = (struct inotify_event*)(event_buf + event_pos);
2257 if (event->len) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08002258 if (event->wd == mInputWd) {
Chris Ye8594e192020-07-14 10:34:06 -07002259 std::string filename = std::string(DEVICE_PATH) + "/" + event->name;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002260 if (event->mask & IN_CREATE) {
Chris Ye8594e192020-07-14 10:34:06 -07002261 openDeviceLocked(filename);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08002262 } else {
2263 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
Chris Ye8594e192020-07-14 10:34:06 -07002264 closeDeviceByPathLocked(filename);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08002265 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002266 } else if (event->wd == mVideoWd) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08002267 if (isV4lTouchNode(event->name)) {
Chris Ye8594e192020-07-14 10:34:06 -07002268 std::string filename = std::string(VIDEO_DEVICE_PATH) + "/" + event->name;
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002269 if (event->mask & IN_CREATE) {
2270 openVideoDeviceLocked(filename);
2271 } else {
2272 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
2273 closeVideoDeviceByPathLocked(filename);
2274 }
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08002275 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002276 } else {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08002277 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event->wd);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002278 }
2279 }
2280 event_size = sizeof(*event) + event->len;
2281 res -= event_size;
2282 event_pos += event_size;
2283 }
2284 return 0;
2285}
2286
Chris Ye8594e192020-07-14 10:34:06 -07002287status_t EventHub::scanDirLocked(const std::string& dirname) {
2288 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2289 openDeviceLocked(entry.path());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002290 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002291 return 0;
2292}
2293
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002294/**
2295 * Look for all dirname/v4l-touch* devices, and open them.
2296 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002297status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Chris Ye8594e192020-07-14 10:34:06 -07002298 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2299 if (isV4lTouchNode(entry.path())) {
2300 ALOGI("Found touch video device %s", entry.path().c_str());
2301 openVideoDeviceLocked(entry.path());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002302 }
2303 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002304 return OK;
2305}
2306
Michael Wrightd02c5b62014-02-10 15:10:22 -08002307void EventHub::requestReopenDevices() {
2308 ALOGV("requestReopenDevices() called");
2309
Chris Ye87143712020-11-10 05:05:58 +00002310 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002311 mNeedToReopenDevices = true;
2312}
2313
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002314void EventHub::dump(std::string& dump) {
2315 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002316
2317 { // acquire lock
Chris Ye87143712020-11-10 05:05:58 +00002318 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002319
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002320 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002321
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002322 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002323
Chris Ye989bb932020-07-04 16:18:59 -07002324 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002325 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002326 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002327 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002328 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002329 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002330 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002331 }
Chris Ye1b0c7342020-07-28 21:57:03 -07002332 dump += StringPrintf(INDENT3 "Classes: %s\n", device->classes.string().c_str());
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002333 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002334 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002335 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
2336 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002337 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002338 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002339 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002340 "product=0x%04x, version=0x%04x\n",
2341 device->identifier.bus, device->identifier.vendor,
2342 device->identifier.product, device->identifier.version);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002343 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002344 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002345 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002346 device->keyMap.keyCharacterMapFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002347 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002348 device->configurationFile.c_str());
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002349 dump += INDENT3 "VideoDevice: ";
2350 if (device->videoDevice) {
2351 dump += device->videoDevice->dump() + "\n";
2352 } else {
2353 dump += "<none>\n";
2354 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002355 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002356
2357 dump += INDENT "Unattached video devices:\n";
2358 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
2359 dump += INDENT2 + videoDevice->dump() + "\n";
2360 }
2361 if (mUnattachedVideoDevices.empty()) {
2362 dump += INDENT2 "<none>\n";
2363 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002364 } // release lock
2365}
2366
2367void EventHub::monitor() {
2368 // Acquire and release the lock to ensure that the event hub has not deadlocked.
Chris Ye1c2e0892020-11-30 21:41:44 -08002369 std::unique_lock<std::mutex> lock(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002370}
2371
Michael Wrightd02c5b62014-02-10 15:10:22 -08002372}; // namespace android