blob: e939d1cb91276a9d69f0655235df6e6b81f6bda0 [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);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001570 event->deviceId = deviceId;
1571 event->type = iev.type;
1572 event->code = iev.code;
1573 event->value = iev.value;
1574 event += 1;
1575 capacity -= 1;
1576 }
1577 if (capacity == 0) {
1578 // The result buffer is full. Reset the pending event index
1579 // so we will try to read the device again on the next iteration.
1580 mPendingEventIndex -= 1;
1581 break;
1582 }
1583 }
1584 } else if (eventItem.events & EPOLLHUP) {
1585 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001586 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001587 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001588 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001589 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001590 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1591 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001592 }
1593 }
1594
1595 // readNotify() will modify the list of devices so this must be done after
1596 // processing all other events to ensure that we read all remaining events
1597 // before closing the devices.
1598 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
1599 mPendingINotify = false;
1600 readNotifyLocked();
1601 deviceChanged = true;
1602 }
1603
1604 // Report added or removed devices immediately.
1605 if (deviceChanged) {
1606 continue;
1607 }
1608
1609 // Return now if we have collected any events or if we were explicitly awoken.
1610 if (event != buffer || awoken) {
1611 break;
1612 }
1613
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001614 // Poll for events.
1615 // When a device driver has pending (unread) events, it acquires
1616 // a kernel wake lock. Once the last pending event has been read, the device
1617 // driver will release the kernel wake lock, but the epoll will hold the wakelock,
1618 // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
1619 // is called again for the same fd that produced the event.
1620 // Thus the system can only sleep if there are no events pending or
1621 // currently being processed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001622 //
1623 // The timeout is advisory only. If the device is asleep, it will not wake just to
1624 // service the timeout.
1625 mPendingEventIndex = 0;
1626
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001627 mLock.unlock(); // release lock before poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001628
1629 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1630
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001631 mLock.lock(); // reacquire lock after poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001632
1633 if (pollResult == 0) {
1634 // Timed out.
1635 mPendingEventCount = 0;
1636 break;
1637 }
1638
1639 if (pollResult < 0) {
1640 // An error occurred.
1641 mPendingEventCount = 0;
1642
1643 // Sleep after errors to avoid locking up the system.
1644 // Hopefully the error is transient.
1645 if (errno != EINTR) {
1646 ALOGW("poll failed (errno=%d)\n", errno);
1647 usleep(100000);
1648 }
1649 } else {
1650 // Some events occurred.
1651 mPendingEventCount = size_t(pollResult);
1652 }
1653 }
1654
1655 // All done, return the number of events we read.
1656 return event - buffer;
1657}
1658
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001659std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001660 std::scoped_lock _l(mLock);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001661
1662 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001663 if (device == nullptr || !device->videoDevice) {
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001664 return {};
1665 }
1666 return device->videoDevice->consumeFrames();
1667}
1668
Michael Wrightd02c5b62014-02-10 15:10:22 -08001669void EventHub::wake() {
1670 ALOGV("wake() called");
1671
1672 ssize_t nWrite;
1673 do {
1674 nWrite = write(mWakeWritePipeFd, "W", 1);
1675 } while (nWrite == -1 && errno == EINTR);
1676
1677 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001678 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001679 }
1680}
1681
1682void EventHub::scanDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001683 status_t result = scanDirLocked(DEVICE_PATH);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001684 if (result < 0) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001685 ALOGE("scan dir failed for %s", DEVICE_PATH);
1686 }
Philip Quinn39b81682019-01-09 22:20:39 -08001687 if (isV4lScanningEnabled()) {
1688 result = scanVideoDirLocked(VIDEO_DEVICE_PATH);
1689 if (result != OK) {
1690 ALOGE("scan video dir failed for %s", VIDEO_DEVICE_PATH);
1691 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001692 }
Chris Ye989bb932020-07-04 16:18:59 -07001693 if (mDevices.find(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) == mDevices.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001694 createVirtualKeyboardLocked();
1695 }
1696}
1697
1698// ----------------------------------------------------------------------------
1699
Michael Wrightd02c5b62014-02-10 15:10:22 -08001700static const int32_t GAMEPAD_KEYCODES[] = {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001701 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C, //
1702 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z, //
1703 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1, //
1704 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2, //
1705 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR, //
1706 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE, //
Michael Wrightd02c5b62014-02-10 15:10:22 -08001707};
1708
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001709status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001710 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001711 struct epoll_event eventItem = {};
1712 eventItem.events = EPOLLIN | EPOLLWAKEUP;
1713 eventItem.data.fd = fd;
1714 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1715 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001716 return -errno;
1717 }
1718 return OK;
1719}
1720
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001721status_t EventHub::unregisterFdFromEpoll(int fd) {
1722 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
1723 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
1724 return -errno;
1725 }
1726 return OK;
1727}
1728
Chris Ye989bb932020-07-04 16:18:59 -07001729status_t EventHub::registerDeviceForEpollLocked(Device& device) {
1730 status_t result = registerFdForEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001731 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07001732 ALOGE("Could not add input device fd to epoll for device %" PRId32, device.id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001733 return result;
1734 }
Chris Ye989bb932020-07-04 16:18:59 -07001735 if (device.videoDevice) {
1736 registerVideoDeviceForEpollLocked(*device.videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001737 }
1738 return result;
1739}
1740
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001741void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
1742 status_t result = registerFdForEpoll(videoDevice.getFd());
1743 if (result != OK) {
1744 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
1745 }
1746}
1747
Chris Ye989bb932020-07-04 16:18:59 -07001748status_t EventHub::unregisterDeviceFromEpollLocked(Device& device) {
1749 if (device.hasValidFd()) {
1750 status_t result = unregisterFdFromEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001751 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07001752 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device.id);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001753 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001754 }
1755 }
Chris Ye989bb932020-07-04 16:18:59 -07001756 if (device.videoDevice) {
1757 unregisterVideoDeviceFromEpollLocked(*device.videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001758 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001759 return OK;
1760}
1761
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001762void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
1763 if (videoDevice.hasValidFd()) {
1764 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
1765 if (result != OK) {
1766 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001767 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001768 }
1769 }
1770}
1771
Chris Ye8594e192020-07-14 10:34:06 -07001772status_t EventHub::openDeviceLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001773 char buffer[80];
1774
Chris Ye8594e192020-07-14 10:34:06 -07001775 ALOGV("Opening device: %s", devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001776
Chris Ye8594e192020-07-14 10:34:06 -07001777 int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001778 if (fd < 0) {
Chris Ye8594e192020-07-14 10:34:06 -07001779 ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001780 return -1;
1781 }
1782
1783 InputDeviceIdentifier identifier;
1784
1785 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001786 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Chris Ye8594e192020-07-14 10:34:06 -07001787 ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001788 } else {
1789 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001790 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001791 }
1792
1793 // Check to see if the device is on our excluded list
1794 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001795 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001796 if (identifier.name == item) {
Chris Ye8594e192020-07-14 10:34:06 -07001797 ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001798 close(fd);
1799 return -1;
1800 }
1801 }
1802
1803 // Get device driver version.
1804 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001805 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Chris Ye8594e192020-07-14 10:34:06 -07001806 ALOGE("could not get driver version for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001807 close(fd);
1808 return -1;
1809 }
1810
1811 // Get device identifier.
1812 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001813 if (ioctl(fd, EVIOCGID, &inputId)) {
Chris Ye8594e192020-07-14 10:34:06 -07001814 ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001815 close(fd);
1816 return -1;
1817 }
1818 identifier.bus = inputId.bustype;
1819 identifier.product = inputId.product;
1820 identifier.vendor = inputId.vendor;
1821 identifier.version = inputId.version;
1822
1823 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001824 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
1825 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001826 } else {
1827 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001828 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001829 }
1830
1831 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001832 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
1833 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001834 } else {
1835 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001836 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001837 }
1838
1839 // Fill in the descriptor.
1840 assignDescriptorLocked(identifier);
1841
Michael Wrightd02c5b62014-02-10 15:10:22 -08001842 // Allocate device. (The device object takes ownership of the fd at this point.)
1843 int32_t deviceId = mNextDeviceId++;
Chris Ye989bb932020-07-04 16:18:59 -07001844 std::unique_ptr<Device> device = std::make_unique<Device>(fd, deviceId, devicePath, identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001845
Chris Ye8594e192020-07-14 10:34:06 -07001846 ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001847 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001848 " vendor %04x\n"
1849 " product %04x\n"
1850 " version %04x\n",
1851 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001852 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
1853 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
1854 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
1855 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001856 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
1857 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001858
1859 // Load the configuration file for the device.
Chris Ye989bb932020-07-04 16:18:59 -07001860 device->loadConfigurationLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001861
Chris Ye3fdbfef2021-01-06 18:45:18 -08001862 // Grab the device's sysfs path
1863 device->sysfsRootPath = getSysfsRootPath(devicePath.c_str());
1864 // find related components
1865 bool hasBattery = device->configureBatteryLocked();
1866 bool hasLights = device->configureLightsLocked();
1867
Michael Wrightd02c5b62014-02-10 15:10:22 -08001868 // Figure out the kinds of events the device reports.
Chris Ye66fbac32020-07-06 20:36:43 -07001869 device->readDeviceBitMask(EVIOCGBIT(EV_KEY, 0), device->keyBitmask);
1870 device->readDeviceBitMask(EVIOCGBIT(EV_ABS, 0), device->absBitmask);
1871 device->readDeviceBitMask(EVIOCGBIT(EV_REL, 0), device->relBitmask);
1872 device->readDeviceBitMask(EVIOCGBIT(EV_SW, 0), device->swBitmask);
1873 device->readDeviceBitMask(EVIOCGBIT(EV_LED, 0), device->ledBitmask);
1874 device->readDeviceBitMask(EVIOCGBIT(EV_FF, 0), device->ffBitmask);
Chris Yef59a2f42020-10-16 12:55:26 -07001875 device->readDeviceBitMask(EVIOCGBIT(EV_MSC, 0), device->mscBitmask);
Chris Ye66fbac32020-07-06 20:36:43 -07001876 device->readDeviceBitMask(EVIOCGPROP(0), device->propBitmask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001877
1878 // See if this is a keyboard. Ignore everything in the button range except for
1879 // joystick and gamepad buttons which are handled like keyboards for the most part.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001880 bool haveKeyboardKeys =
Chris Ye66fbac32020-07-06 20:36:43 -07001881 device->keyBitmask.any(0, BTN_MISC) || device->keyBitmask.any(BTN_WHEEL, KEY_MAX + 1);
1882 bool haveGamepadButtons = device->keyBitmask.any(BTN_MISC, BTN_MOUSE) ||
1883 device->keyBitmask.any(BTN_JOYSTICK, BTN_DIGI);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001884 if (haveKeyboardKeys || haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001885 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001886 }
1887
1888 // See if this is a cursor device such as a trackball or mouse.
Chris Ye66fbac32020-07-06 20:36:43 -07001889 if (device->keyBitmask.test(BTN_MOUSE) && device->relBitmask.test(REL_X) &&
1890 device->relBitmask.test(REL_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001891 device->classes |= InputDeviceClass::CURSOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001892 }
1893
Prashant Malani1941ff52015-08-11 18:29:28 -07001894 // See if this is a rotary encoder type device.
1895 String8 deviceType = String8();
1896 if (device->configuration &&
1897 device->configuration->tryGetProperty(String8("device.type"), deviceType)) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001898 if (!deviceType.compare(String8("rotaryEncoder"))) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001899 device->classes |= InputDeviceClass::ROTARY_ENCODER;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001900 }
Prashant Malani1941ff52015-08-11 18:29:28 -07001901 }
1902
Michael Wrightd02c5b62014-02-10 15:10:22 -08001903 // See if this is a touch pad.
1904 // Is this a new modern multi-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07001905 if (device->absBitmask.test(ABS_MT_POSITION_X) && device->absBitmask.test(ABS_MT_POSITION_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001906 // Some joysticks such as the PS3 controller report axes that conflict
1907 // with the ABS_MT range. Try to confirm that the device really is
1908 // a touch screen.
Chris Ye66fbac32020-07-06 20:36:43 -07001909 if (device->keyBitmask.test(BTN_TOUCH) || !haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001910 device->classes |= (InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001911 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001912 // Is this an old style single-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07001913 } else if (device->keyBitmask.test(BTN_TOUCH) && device->absBitmask.test(ABS_X) &&
1914 device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001915 device->classes |= InputDeviceClass::TOUCH;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001916 // Is this a BT stylus?
Chris Ye66fbac32020-07-06 20:36:43 -07001917 } else if ((device->absBitmask.test(ABS_PRESSURE) || device->keyBitmask.test(BTN_TOUCH)) &&
1918 !device->absBitmask.test(ABS_X) && !device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001919 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -07001920 // Keyboard will try to claim some of the buttons but we really want to reserve those so we
1921 // can fuse it with the touch screen data, so just take them back. Note this means an
1922 // external stylus cannot also be a keyboard device.
Chris Ye1b0c7342020-07-28 21:57:03 -07001923 device->classes &= ~InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001924 }
1925
1926 // See if this device is a joystick.
1927 // Assumes that joysticks always have gamepad buttons in order to distinguish them
1928 // from other devices such as accelerometers that also have absolute axes.
1929 if (haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001930 auto assumedClasses = device->classes | InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001931 for (int i = 0; i <= ABS_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07001932 if (device->absBitmask.test(i) &&
Chris Ye1b0c7342020-07-28 21:57:03 -07001933 (getAbsAxisUsage(i, assumedClasses).test(InputDeviceClass::JOYSTICK))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001934 device->classes = assumedClasses;
1935 break;
1936 }
1937 }
1938 }
1939
Chris Yef59a2f42020-10-16 12:55:26 -07001940 // Check whether this device is an accelerometer.
1941 if (device->propBitmask.test(INPUT_PROP_ACCELEROMETER)) {
1942 device->classes |= InputDeviceClass::SENSOR;
1943 }
1944
Michael Wrightd02c5b62014-02-10 15:10:22 -08001945 // Check whether this device has switches.
1946 for (int i = 0; i <= SW_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07001947 if (device->swBitmask.test(i)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001948 device->classes |= InputDeviceClass::SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001949 break;
1950 }
1951 }
1952
1953 // Check whether this device supports the vibrator.
Chris Ye66fbac32020-07-06 20:36:43 -07001954 if (device->ffBitmask.test(FF_RUMBLE)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001955 device->classes |= InputDeviceClass::VIBRATOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001956 }
1957
1958 // Configure virtual keys.
Chris Ye1b0c7342020-07-28 21:57:03 -07001959 if ((device->classes.test(InputDeviceClass::TOUCH))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001960 // Load the virtual keys for the touch screen, if any.
1961 // We do this now so that we can make sure to load the keymap if necessary.
Chris Ye989bb932020-07-04 16:18:59 -07001962 bool success = device->loadVirtualKeyMapLocked();
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001963 if (success) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001964 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001965 }
1966 }
1967
1968 // Load the key map.
Chris Yef59a2f42020-10-16 12:55:26 -07001969 // We need to do this for joysticks too because the key layout may specify axes, and for
1970 // sensor as well because the key layout may specify the axes to sensor data mapping.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001971 status_t keyMapStatus = NAME_NOT_FOUND;
Chris Yef59a2f42020-10-16 12:55:26 -07001972 if (device->classes.any(InputDeviceClass::KEYBOARD | InputDeviceClass::JOYSTICK |
1973 InputDeviceClass::SENSOR)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001974 // Load the keymap for the device.
Chris Ye989bb932020-07-04 16:18:59 -07001975 keyMapStatus = device->loadKeyMapLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001976 }
1977
1978 // Configure the keyboard, gamepad or virtual keyboard.
Chris Ye1b0c7342020-07-28 21:57:03 -07001979 if (device->classes.test(InputDeviceClass::KEYBOARD)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001980 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001981 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05001982 isEligibleBuiltInKeyboard(device->identifier, device->configuration.get(),
1983 &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001984 mBuiltInKeyboardId = device->id;
1985 }
1986
1987 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
Chris Ye989bb932020-07-04 16:18:59 -07001988 if (device->hasKeycodeLocked(AKEYCODE_Q)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001989 device->classes |= InputDeviceClass::ALPHAKEY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001990 }
1991
1992 // See if this device has a DPAD.
Chris Ye989bb932020-07-04 16:18:59 -07001993 if (device->hasKeycodeLocked(AKEYCODE_DPAD_UP) &&
1994 device->hasKeycodeLocked(AKEYCODE_DPAD_DOWN) &&
1995 device->hasKeycodeLocked(AKEYCODE_DPAD_LEFT) &&
1996 device->hasKeycodeLocked(AKEYCODE_DPAD_RIGHT) &&
1997 device->hasKeycodeLocked(AKEYCODE_DPAD_CENTER)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001998 device->classes |= InputDeviceClass::DPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001999 }
2000
2001 // See if this device has a gamepad.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002002 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES) / sizeof(GAMEPAD_KEYCODES[0]); i++) {
Chris Ye989bb932020-07-04 16:18:59 -07002003 if (device->hasKeycodeLocked(GAMEPAD_KEYCODES[i])) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002004 device->classes |= InputDeviceClass::GAMEPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002005 break;
2006 }
2007 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002008 }
2009
2010 // If the device isn't recognized as something we handle, don't monitor it.
Chris Ye1b0c7342020-07-28 21:57:03 -07002011 if (device->classes == Flags<InputDeviceClass>(0)) {
Chris Ye8594e192020-07-14 10:34:06 -07002012 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002013 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002014 return -1;
2015 }
2016
Chris Ye3fdbfef2021-01-06 18:45:18 -08002017 // Classify InputDeviceClass::BATTERY.
2018 if (hasBattery) {
2019 device->classes |= InputDeviceClass::BATTERY;
2020 }
Kim Low03ea0352020-11-06 12:45:07 -08002021
Chris Ye3fdbfef2021-01-06 18:45:18 -08002022 // Classify InputDeviceClass::LIGHT.
2023 if (hasLights) {
2024 device->classes |= InputDeviceClass::LIGHT;
Kim Low03ea0352020-11-06 12:45:07 -08002025 }
2026
Tim Kilbourn063ff532015-04-08 10:26:18 -07002027 // Determine whether the device has a mic.
Chris Ye989bb932020-07-04 16:18:59 -07002028 if (device->deviceHasMicLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002029 device->classes |= InputDeviceClass::MIC;
Tim Kilbourn063ff532015-04-08 10:26:18 -07002030 }
2031
Michael Wrightd02c5b62014-02-10 15:10:22 -08002032 // Determine whether the device is external or internal.
Chris Ye989bb932020-07-04 16:18:59 -07002033 if (device->isExternalDeviceLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002034 device->classes |= InputDeviceClass::EXTERNAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002035 }
2036
Chris Ye1b0c7342020-07-28 21:57:03 -07002037 if (device->classes.any(InputDeviceClass::JOYSTICK | InputDeviceClass::DPAD) &&
2038 device->classes.test(InputDeviceClass::GAMEPAD)) {
Chris Ye989bb932020-07-04 16:18:59 -07002039 device->controllerNumber = getNextControllerNumberLocked(device->identifier.name);
2040 device->setLedForControllerLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002041 }
2042
Chris Ye989bb932020-07-04 16:18:59 -07002043 if (registerDeviceForEpollLocked(*device) != OK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002044 return -1;
2045 }
2046
Chris Ye989bb932020-07-04 16:18:59 -07002047 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002048
Chris Ye1b0c7342020-07-28 21:57:03 -07002049 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=%s, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002050 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Chris Ye1b0c7342020-07-28 21:57:03 -07002051 deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(),
2052 device->classes.string().c_str(), device->configurationFile.c_str(),
2053 device->keyMap.keyLayoutFile.c_str(), device->keyMap.keyCharacterMapFile.c_str(),
2054 toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002055
Chris Ye989bb932020-07-04 16:18:59 -07002056 addDeviceLocked(std::move(device));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002057 return OK;
2058}
2059
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002060void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
2061 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
2062 if (!videoDevice) {
2063 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
2064 return;
2065 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002066 // Transfer ownership of this video device to a matching input device
Chris Ye989bb932020-07-04 16:18:59 -07002067 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002068 if (tryAddVideoDevice(*device, videoDevice)) {
2069 return; // 'device' now owns 'videoDevice'
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002070 }
2071 }
2072
2073 // Couldn't find a matching input device, so just add it to a temporary holding queue.
2074 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002075 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002076 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002077 mUnattachedVideoDevices.push_back(std::move(videoDevice));
2078}
2079
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002080bool EventHub::tryAddVideoDevice(EventHub::Device& device,
2081 std::unique_ptr<TouchVideoDevice>& videoDevice) {
2082 if (videoDevice->getName() != device.identifier.name) {
2083 return false;
2084 }
2085 device.videoDevice = std::move(videoDevice);
2086 if (device.enabled) {
2087 registerVideoDeviceForEpollLocked(*device.videoDevice);
2088 }
2089 return true;
2090}
2091
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002092bool EventHub::isDeviceEnabled(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002093 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002094 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002095 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002096 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2097 return false;
2098 }
2099 return device->enabled;
2100}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002101
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002102status_t EventHub::enableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002103 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002104 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002105 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002106 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2107 return BAD_VALUE;
2108 }
2109 if (device->enabled) {
2110 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
2111 return OK;
2112 }
2113 status_t result = device->enable();
2114 if (result != OK) {
2115 ALOGE("Failed to enable device %" PRId32, deviceId);
2116 return result;
2117 }
2118
Chris Ye989bb932020-07-04 16:18:59 -07002119 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002120
Chris Ye989bb932020-07-04 16:18:59 -07002121 return registerDeviceForEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002122}
2123
2124status_t EventHub::disableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002125 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002126 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002127 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002128 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2129 return BAD_VALUE;
2130 }
2131 if (!device->enabled) {
2132 ALOGW("Duplicate call to %s, input device already disabled", __func__);
2133 return OK;
2134 }
Chris Ye989bb932020-07-04 16:18:59 -07002135 unregisterDeviceFromEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002136 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002137}
2138
2139void EventHub::createVirtualKeyboardLocked() {
2140 InputDeviceIdentifier identifier;
2141 identifier.name = "Virtual";
2142 identifier.uniqueId = "<virtual>";
2143 assignDescriptorLocked(identifier);
2144
Chris Ye989bb932020-07-04 16:18:59 -07002145 std::unique_ptr<Device> device =
2146 std::make_unique<Device>(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
2147 identifier);
Chris Ye1b0c7342020-07-28 21:57:03 -07002148 device->classes = InputDeviceClass::KEYBOARD | InputDeviceClass::ALPHAKEY |
2149 InputDeviceClass::DPAD | InputDeviceClass::VIRTUAL;
Chris Ye989bb932020-07-04 16:18:59 -07002150 device->loadKeyMapLocked();
2151 addDeviceLocked(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002152}
2153
Chris Ye989bb932020-07-04 16:18:59 -07002154void EventHub::addDeviceLocked(std::unique_ptr<Device> device) {
2155 mOpeningDevices.push_back(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002156}
2157
Chris Ye989bb932020-07-04 16:18:59 -07002158int32_t EventHub::getNextControllerNumberLocked(const std::string& name) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002159 if (mControllerNumbers.isFull()) {
2160 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Chris Ye989bb932020-07-04 16:18:59 -07002161 name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002162 return 0;
2163 }
2164 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
2165 // one
2166 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
2167}
2168
Chris Ye989bb932020-07-04 16:18:59 -07002169void EventHub::releaseControllerNumberLocked(int32_t num) {
2170 if (num > 0) {
2171 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002172 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002173}
2174
Chris Ye8594e192020-07-14 10:34:06 -07002175void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002176 Device* device = getDeviceByPathLocked(devicePath);
Chris Ye989bb932020-07-04 16:18:59 -07002177 if (device != nullptr) {
2178 closeDeviceLocked(*device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002179 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002180 }
Chris Ye8594e192020-07-14 10:34:06 -07002181 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002182}
2183
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002184/**
2185 * Find the video device by filename, and close it.
2186 * The video device is closed by path during an inotify event, where we don't have the
2187 * additional context about the video device fd, or the associated input device.
2188 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002189void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002190 // A video device may be owned by an existing input device, or it may be stored in
2191 // the mUnattachedVideoDevices queue. Check both locations.
Chris Ye989bb932020-07-04 16:18:59 -07002192 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002193 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002194 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002195 device->videoDevice = nullptr;
2196 return;
2197 }
2198 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002199 mUnattachedVideoDevices
2200 .erase(std::remove_if(mUnattachedVideoDevices.begin(), mUnattachedVideoDevices.end(),
2201 [&devicePath](
2202 const std::unique_ptr<TouchVideoDevice>& videoDevice) {
2203 return videoDevice->getPath() == devicePath;
2204 }),
2205 mUnattachedVideoDevices.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002206}
2207
2208void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002209 mUnattachedVideoDevices.clear();
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002210 while (!mDevices.empty()) {
2211 closeDeviceLocked(*(mDevices.begin()->second));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002212 }
2213}
2214
Chris Ye989bb932020-07-04 16:18:59 -07002215void EventHub::closeDeviceLocked(Device& device) {
2216 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=%s", device.path.c_str(),
2217 device.identifier.name.c_str(), device.id, device.fd, device.classes.string().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002218
Chris Ye989bb932020-07-04 16:18:59 -07002219 if (device.id == mBuiltInKeyboardId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002220 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Chris Ye989bb932020-07-04 16:18:59 -07002221 device.path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002222 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
2223 }
2224
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002225 unregisterDeviceFromEpollLocked(device);
Chris Ye989bb932020-07-04 16:18:59 -07002226 if (device.videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002227 // This must be done after the video device is removed from epoll
Chris Ye989bb932020-07-04 16:18:59 -07002228 mUnattachedVideoDevices.push_back(std::move(device.videoDevice));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002229 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002230
Chris Ye989bb932020-07-04 16:18:59 -07002231 releaseControllerNumberLocked(device.controllerNumber);
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002232 device.controllerNumber = 0;
Chris Ye989bb932020-07-04 16:18:59 -07002233 device.close();
Chris Ye989bb932020-07-04 16:18:59 -07002234 mClosingDevices.push_back(std::move(mDevices[device.id]));
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002235
Chris Ye989bb932020-07-04 16:18:59 -07002236 mDevices.erase(device.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002237}
2238
2239status_t EventHub::readNotifyLocked() {
2240 int res;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002241 char event_buf[512];
2242 int event_size;
2243 int event_pos = 0;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002244 struct inotify_event* event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002245
2246 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
2247 res = read(mINotifyFd, event_buf, sizeof(event_buf));
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002248 if (res < (int)sizeof(*event)) {
2249 if (errno == EINTR) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002250 ALOGW("could not get event, %s\n", strerror(errno));
2251 return -1;
2252 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002253
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002254 while (res >= (int)sizeof(*event)) {
2255 event = (struct inotify_event*)(event_buf + event_pos);
2256 if (event->len) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08002257 if (event->wd == mInputWd) {
Chris Ye8594e192020-07-14 10:34:06 -07002258 std::string filename = std::string(DEVICE_PATH) + "/" + event->name;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002259 if (event->mask & IN_CREATE) {
Chris Ye8594e192020-07-14 10:34:06 -07002260 openDeviceLocked(filename);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08002261 } else {
2262 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
Chris Ye8594e192020-07-14 10:34:06 -07002263 closeDeviceByPathLocked(filename);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08002264 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002265 } else if (event->wd == mVideoWd) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08002266 if (isV4lTouchNode(event->name)) {
Chris Ye8594e192020-07-14 10:34:06 -07002267 std::string filename = std::string(VIDEO_DEVICE_PATH) + "/" + event->name;
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002268 if (event->mask & IN_CREATE) {
2269 openVideoDeviceLocked(filename);
2270 } else {
2271 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
2272 closeVideoDeviceByPathLocked(filename);
2273 }
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08002274 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002275 } else {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08002276 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event->wd);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002277 }
2278 }
2279 event_size = sizeof(*event) + event->len;
2280 res -= event_size;
2281 event_pos += event_size;
2282 }
2283 return 0;
2284}
2285
Chris Ye8594e192020-07-14 10:34:06 -07002286status_t EventHub::scanDirLocked(const std::string& dirname) {
2287 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2288 openDeviceLocked(entry.path());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002289 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002290 return 0;
2291}
2292
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002293/**
2294 * Look for all dirname/v4l-touch* devices, and open them.
2295 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002296status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Chris Ye8594e192020-07-14 10:34:06 -07002297 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2298 if (isV4lTouchNode(entry.path())) {
2299 ALOGI("Found touch video device %s", entry.path().c_str());
2300 openVideoDeviceLocked(entry.path());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002301 }
2302 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002303 return OK;
2304}
2305
Michael Wrightd02c5b62014-02-10 15:10:22 -08002306void EventHub::requestReopenDevices() {
2307 ALOGV("requestReopenDevices() called");
2308
Chris Ye87143712020-11-10 05:05:58 +00002309 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002310 mNeedToReopenDevices = true;
2311}
2312
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002313void EventHub::dump(std::string& dump) {
2314 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002315
2316 { // acquire lock
Chris Ye87143712020-11-10 05:05:58 +00002317 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002318
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002319 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002320
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002321 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002322
Chris Ye989bb932020-07-04 16:18:59 -07002323 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002324 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002325 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002326 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002327 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002328 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002329 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002330 }
Chris Ye1b0c7342020-07-28 21:57:03 -07002331 dump += StringPrintf(INDENT3 "Classes: %s\n", device->classes.string().c_str());
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002332 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002333 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002334 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
2335 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002336 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002337 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002338 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002339 "product=0x%04x, version=0x%04x\n",
2340 device->identifier.bus, device->identifier.vendor,
2341 device->identifier.product, device->identifier.version);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002342 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002343 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002344 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002345 device->keyMap.keyCharacterMapFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002346 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002347 device->configurationFile.c_str());
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002348 dump += INDENT3 "VideoDevice: ";
2349 if (device->videoDevice) {
2350 dump += device->videoDevice->dump() + "\n";
2351 } else {
2352 dump += "<none>\n";
2353 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002354 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002355
2356 dump += INDENT "Unattached video devices:\n";
2357 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
2358 dump += INDENT2 + videoDevice->dump() + "\n";
2359 }
2360 if (mUnattachedVideoDevices.empty()) {
2361 dump += INDENT2 "<none>\n";
2362 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002363 } // release lock
2364}
2365
2366void EventHub::monitor() {
2367 // Acquire and release the lock to ensure that the event hub has not deadlocked.
Chris Ye1c2e0892020-11-30 21:41:44 -08002368 std::unique_lock<std::mutex> lock(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002369}
2370
Michael Wrightd02c5b62014-02-10 15:10:22 -08002371}; // namespace android