blob: c8da0ab29f2c48293793c4545dff699a8f6d7143 [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>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070032#include <unistd.h>
33
Michael Wrightd02c5b62014-02-10 15:10:22 -080034#define LOG_TAG "EventHub"
35
36// #define LOG_NDEBUG 0
37
38#include "EventHub.h"
39
40#include <hardware_legacy/power.h>
41
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080042#include <android-base/stringprintf.h>
Philip Quinn39b81682019-01-09 22:20:39 -080043#include <cutils/properties.h>
Dan Albert677d87e2014-06-16 17:31:28 -070044#include <openssl/sha.h>
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070045#include <utils/Errors.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080046#include <utils/Log.h>
47#include <utils/Timers.h>
48#include <utils/threads.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080049
Michael Wrightd02c5b62014-02-10 15:10:22 -080050#include <input/KeyCharacterMap.h>
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070051#include <input/KeyLayoutMap.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080052#include <input/VirtualKeyMap.h>
53
Michael Wrightd02c5b62014-02-10 15:10:22 -080054/* this macro is used to tell if "bit" is set in "array"
55 * it selects a byte from the array, and does a boolean AND
56 * operation with a byte that only has the relevant bit set.
57 * eg. to check for the 12th bit, we do (array[1] & 1<<4)
58 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070059#define test_bit(bit, array) ((array)[(bit) / 8] & (1 << ((bit) % 8)))
Michael Wrightd02c5b62014-02-10 15:10:22 -080060
61/* this macro computes the number of bytes needed to represent a bit array of the specified size */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070062#define sizeof_bit_array(bits) (((bits) + 7) / 8)
Michael Wrightd02c5b62014-02-10 15:10:22 -080063
64#define INDENT " "
65#define INDENT2 " "
66#define INDENT3 " "
67
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080068using android::base::StringPrintf;
69
Michael Wrightd02c5b62014-02-10 15:10:22 -080070namespace android {
71
Siarhei Vishniakou25920312018-12-12 15:24:44 -080072static constexpr bool DEBUG = false;
73
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070074static const char* WAKE_LOCK_ID = "KeyEvents";
75static const char* DEVICE_PATH = "/dev/input";
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080076// v4l2 devices go directly into /dev
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070077static const char* VIDEO_DEVICE_PATH = "/dev";
Michael Wrightd02c5b62014-02-10 15:10:22 -080078
Michael Wrightd02c5b62014-02-10 15:10:22 -080079static inline const char* toString(bool value) {
80 return value ? "true" : "false";
81}
82
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010083static std::string sha1(const std::string& in) {
Dan Albert677d87e2014-06-16 17:31:28 -070084 SHA_CTX ctx;
85 SHA1_Init(&ctx);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010086 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
Dan Albert677d87e2014-06-16 17:31:28 -070087 u_char digest[SHA_DIGEST_LENGTH];
88 SHA1_Final(digest, &ctx);
Michael Wrightd02c5b62014-02-10 15:10:22 -080089
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010090 std::string out;
Dan Albert677d87e2014-06-16 17:31:28 -070091 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010092 out += StringPrintf("%02x", digest[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -080093 }
94 return out;
95}
96
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080097/**
98 * Return true if name matches "v4l-touch*"
99 */
100static bool isV4lTouchNode(const char* name) {
101 return strstr(name, "v4l-touch") == name;
102}
103
Philip Quinn39b81682019-01-09 22:20:39 -0800104/**
105 * Returns true if V4L devices should be scanned.
106 *
107 * The system property ro.input.video_enabled can be used to control whether
108 * EventHub scans and opens V4L devices. As V4L does not support multiple
109 * clients, EventHub effectively blocks access to these devices when it opens
Siarhei Vishniakou29f88492019-04-05 14:11:43 -0700110 * them.
111 *
112 * Setting this to "false" would prevent any video devices from being discovered and
113 * associated with input devices.
114 *
115 * This property can be used as follows:
116 * 1. To turn off features that are dependent on video device presence.
117 * 2. During testing and development, to allow other clients to read video devices
118 * directly from /dev.
Philip Quinn39b81682019-01-09 22:20:39 -0800119 */
120static bool isV4lScanningEnabled() {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700121 return property_get_bool("ro.input.video_enabled", true /* default_value */);
Philip Quinn39b81682019-01-09 22:20:39 -0800122}
123
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800124static nsecs_t processEventTimestamp(const struct input_event& event) {
125 // Use the time specified in the event instead of the current time
126 // so that downstream code can get more accurate estimates of
127 // event dispatch latency from the time the event is enqueued onto
128 // the evdev client buffer.
129 //
130 // The event's timestamp fortuitously uses the same monotonic clock
131 // time base as the rest of Android. The kernel event device driver
132 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
133 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
134 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
135 // system call that also queries ktime_get_ts().
136
137 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.time.tv_sec) +
138 microseconds_to_nanoseconds(event.time.tv_usec);
139 return inputEventTime;
140}
141
Michael Wrightd02c5b62014-02-10 15:10:22 -0800142// --- Global Functions ---
143
144uint32_t getAbsAxisUsage(int32_t axis, uint32_t deviceClasses) {
145 // Touch devices get dibs on touch-related axes.
146 if (deviceClasses & INPUT_DEVICE_CLASS_TOUCH) {
147 switch (axis) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700148 case ABS_X:
149 case ABS_Y:
150 case ABS_PRESSURE:
151 case ABS_TOOL_WIDTH:
152 case ABS_DISTANCE:
153 case ABS_TILT_X:
154 case ABS_TILT_Y:
155 case ABS_MT_SLOT:
156 case ABS_MT_TOUCH_MAJOR:
157 case ABS_MT_TOUCH_MINOR:
158 case ABS_MT_WIDTH_MAJOR:
159 case ABS_MT_WIDTH_MINOR:
160 case ABS_MT_ORIENTATION:
161 case ABS_MT_POSITION_X:
162 case ABS_MT_POSITION_Y:
163 case ABS_MT_TOOL_TYPE:
164 case ABS_MT_BLOB_ID:
165 case ABS_MT_TRACKING_ID:
166 case ABS_MT_PRESSURE:
167 case ABS_MT_DISTANCE:
168 return INPUT_DEVICE_CLASS_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800169 }
170 }
171
Michael Wright842500e2015-03-13 17:32:02 -0700172 // External stylus gets the pressure axis
173 if (deviceClasses & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
174 if (axis == ABS_PRESSURE) {
175 return INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
176 }
177 }
178
Michael Wrightd02c5b62014-02-10 15:10:22 -0800179 // Joystick devices get the rest.
180 return deviceClasses & INPUT_DEVICE_CLASS_JOYSTICK;
181}
182
183// --- EventHub::Device ---
184
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100185EventHub::Device::Device(int fd, int32_t id, const std::string& path,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700186 const InputDeviceIdentifier& identifier)
187 : next(nullptr),
188 fd(fd),
189 id(id),
190 path(path),
191 identifier(identifier),
192 classes(0),
193 configuration(nullptr),
194 virtualKeyMap(nullptr),
195 ffEffectPlaying(false),
196 ffEffectId(-1),
197 controllerNumber(0),
198 enabled(true),
199 isVirtual(fd < 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800200 memset(keyBitmask, 0, sizeof(keyBitmask));
201 memset(absBitmask, 0, sizeof(absBitmask));
202 memset(relBitmask, 0, sizeof(relBitmask));
203 memset(swBitmask, 0, sizeof(swBitmask));
204 memset(ledBitmask, 0, sizeof(ledBitmask));
205 memset(ffBitmask, 0, sizeof(ffBitmask));
206 memset(propBitmask, 0, sizeof(propBitmask));
207}
208
209EventHub::Device::~Device() {
210 close();
211 delete configuration;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800212}
213
214void EventHub::Device::close() {
215 if (fd >= 0) {
216 ::close(fd);
217 fd = -1;
218 }
219}
220
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700221status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100222 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700223 if (fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100224 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700225 return -errno;
226 }
227 enabled = true;
228 return OK;
229}
230
231status_t EventHub::Device::disable() {
232 close();
233 enabled = false;
234 return OK;
235}
236
237bool EventHub::Device::hasValidFd() {
238 return !isVirtual && enabled;
239}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800240
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100241/**
242 * Get the capabilities for the current process.
243 * Crashes the system if unable to create / check / destroy the capabilities object.
244 */
245class Capabilities final {
246public:
247 explicit Capabilities() {
248 mCaps = cap_get_proc();
249 LOG_ALWAYS_FATAL_IF(mCaps == nullptr, "Could not get capabilities of the current process");
250 }
251
252 /**
253 * Check whether the current process has a specific capability
254 * in the set of effective capabilities.
255 * Return CAP_SET if the process has the requested capability
256 * Return CAP_CLEAR otherwise.
257 */
258 cap_flag_value_t checkEffectiveCapability(cap_value_t capability) {
259 cap_flag_value_t value;
260 const int result = cap_get_flag(mCaps, capability, CAP_EFFECTIVE, &value);
261 LOG_ALWAYS_FATAL_IF(result == -1, "Could not obtain the requested capability");
262 return value;
263 }
264
265 ~Capabilities() {
266 const int result = cap_free(mCaps);
267 LOG_ALWAYS_FATAL_IF(result == -1, "Could not release the capabilities structure");
268 }
269
270private:
271 cap_t mCaps;
272};
273
274static void ensureProcessCanBlockSuspend() {
275 Capabilities capabilities;
276 const bool canBlockSuspend =
277 capabilities.checkEffectiveCapability(CAP_BLOCK_SUSPEND) == CAP_SET;
278 LOG_ALWAYS_FATAL_IF(!canBlockSuspend,
279 "Input must be able to block suspend to properly process events");
280}
281
Michael Wrightd02c5b62014-02-10 15:10:22 -0800282// --- EventHub ---
283
Michael Wrightd02c5b62014-02-10 15:10:22 -0800284const int EventHub::EPOLL_MAX_EVENTS;
285
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700286EventHub::EventHub(void)
287 : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
288 mNextDeviceId(1),
289 mControllerNumbers(),
290 mOpeningDevices(nullptr),
291 mClosingDevices(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800292 mNeedToSendFinishedDeviceScan(false),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700293 mNeedToReopenDevices(false),
294 mNeedToScanDevices(true),
295 mPendingEventCount(0),
296 mPendingEventIndex(0),
297 mPendingINotify(false) {
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100298 ensureProcessCanBlockSuspend();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800299 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
300
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800301 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800302 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800303
304 mINotifyFd = inotify_init();
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800305 mInputWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700306 LOG_ALWAYS_FATAL_IF(mInputWd < 0, "Could not register INotify for %s: %s", DEVICE_PATH,
307 strerror(errno));
Philip Quinn39b81682019-01-09 22:20:39 -0800308 if (isV4lScanningEnabled()) {
309 mVideoWd = inotify_add_watch(mINotifyFd, VIDEO_DEVICE_PATH, IN_DELETE | IN_CREATE);
310 LOG_ALWAYS_FATAL_IF(mVideoWd < 0, "Could not register INotify for %s: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700311 VIDEO_DEVICE_PATH, strerror(errno));
Philip Quinn39b81682019-01-09 22:20:39 -0800312 } else {
313 mVideoWd = -1;
314 ALOGI("Video device scanning disabled");
315 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800316
Siarhei Vishniakou2d0e9482019-09-24 12:52:47 +0100317 struct epoll_event eventItem = {};
318 eventItem.events = EPOLLIN | EPOLLWAKEUP;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700319 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800320 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800321 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
322
323 int wakeFds[2];
324 result = pipe(wakeFds);
325 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
326
327 mWakeReadPipeFd = wakeFds[0];
328 mWakeWritePipeFd = wakeFds[1];
329
330 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
331 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700332 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800333
334 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
335 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700336 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800337
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700338 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800339 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
340 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700341 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800342}
343
344EventHub::~EventHub(void) {
345 closeAllDevicesLocked();
346
347 while (mClosingDevices) {
348 Device* device = mClosingDevices;
349 mClosingDevices = device->next;
350 delete device;
351 }
352
353 ::close(mEpollFd);
354 ::close(mINotifyFd);
355 ::close(mWakeReadPipeFd);
356 ::close(mWakeWritePipeFd);
357
358 release_wake_lock(WAKE_LOCK_ID);
359}
360
361InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
362 AutoMutex _l(mLock);
363 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700364 if (device == nullptr) return InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800365 return device->identifier;
366}
367
368uint32_t EventHub::getDeviceClasses(int32_t deviceId) const {
369 AutoMutex _l(mLock);
370 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700371 if (device == nullptr) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800372 return device->classes;
373}
374
375int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
376 AutoMutex _l(mLock);
377 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700378 if (device == nullptr) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800379 return device->controllerNumber;
380}
381
382void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
383 AutoMutex _l(mLock);
384 Device* device = getDeviceLocked(deviceId);
385 if (device && device->configuration) {
386 *outConfiguration = *device->configuration;
387 } else {
388 outConfiguration->clear();
389 }
390}
391
392status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700393 RawAbsoluteAxisInfo* outAxisInfo) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800394 outAxisInfo->clear();
395
396 if (axis >= 0 && axis <= ABS_MAX) {
397 AutoMutex _l(mLock);
398
399 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700400 if (device && device->hasValidFd() && test_bit(axis, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800401 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700402 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
403 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
404 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800405 return -errno;
406 }
407
408 if (info.minimum != info.maximum) {
409 outAxisInfo->valid = true;
410 outAxisInfo->minValue = info.minimum;
411 outAxisInfo->maxValue = info.maximum;
412 outAxisInfo->flat = info.flat;
413 outAxisInfo->fuzz = info.fuzz;
414 outAxisInfo->resolution = info.resolution;
415 }
416 return OK;
417 }
418 }
419 return -1;
420}
421
422bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
423 if (axis >= 0 && axis <= REL_MAX) {
424 AutoMutex _l(mLock);
425
426 Device* device = getDeviceLocked(deviceId);
427 if (device) {
428 return test_bit(axis, device->relBitmask);
429 }
430 }
431 return false;
432}
433
434bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
435 if (property >= 0 && property <= INPUT_PROP_MAX) {
436 AutoMutex _l(mLock);
437
438 Device* device = getDeviceLocked(deviceId);
439 if (device) {
440 return test_bit(property, device->propBitmask);
441 }
442 }
443 return false;
444}
445
446int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
447 if (scanCode >= 0 && scanCode <= KEY_MAX) {
448 AutoMutex _l(mLock);
449
450 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700451 if (device && device->hasValidFd() && test_bit(scanCode, device->keyBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800452 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
453 memset(keyState, 0, sizeof(keyState));
454 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
455 return test_bit(scanCode, keyState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
456 }
457 }
458 }
459 return AKEY_STATE_UNKNOWN;
460}
461
462int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
463 AutoMutex _l(mLock);
464
465 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700466 if (device && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800467 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800468 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode, &scanCodes);
469 if (scanCodes.size() != 0) {
470 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
471 memset(keyState, 0, sizeof(keyState));
472 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
473 for (size_t i = 0; i < scanCodes.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800474 int32_t sc = scanCodes[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -0800475 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, keyState)) {
476 return AKEY_STATE_DOWN;
477 }
478 }
479 return AKEY_STATE_UP;
480 }
481 }
482 }
483 return AKEY_STATE_UNKNOWN;
484}
485
486int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
487 if (sw >= 0 && sw <= SW_MAX) {
488 AutoMutex _l(mLock);
489
490 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700491 if (device && device->hasValidFd() && test_bit(sw, device->swBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800492 uint8_t swState[sizeof_bit_array(SW_MAX + 1)];
493 memset(swState, 0, sizeof(swState));
494 if (ioctl(device->fd, EVIOCGSW(sizeof(swState)), swState) >= 0) {
495 return test_bit(sw, swState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
496 }
497 }
498 }
499 return AKEY_STATE_UNKNOWN;
500}
501
502status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
503 *outValue = 0;
504
505 if (axis >= 0 && axis <= ABS_MAX) {
506 AutoMutex _l(mLock);
507
508 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700509 if (device && device->hasValidFd() && test_bit(axis, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800510 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700511 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
512 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
513 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800514 return -errno;
515 }
516
517 *outValue = info.value;
518 return OK;
519 }
520 }
521 return -1;
522}
523
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700524bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes, const int32_t* keyCodes,
525 uint8_t* outFlags) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800526 AutoMutex _l(mLock);
527
528 Device* device = getDeviceLocked(deviceId);
529 if (device && device->keyMap.haveKeyLayout()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800530 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800531 for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) {
532 scanCodes.clear();
533
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700534 status_t err = device->keyMap.keyLayoutMap->findScanCodesForKey(keyCodes[codeIndex],
535 &scanCodes);
536 if (!err) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800537 // check the possible scan codes identified by the layout map against the
538 // map of codes actually emitted by the driver
539 for (size_t sc = 0; sc < scanCodes.size(); sc++) {
540 if (test_bit(scanCodes[sc], device->keyBitmask)) {
541 outFlags[codeIndex] = 1;
542 break;
543 }
544 }
545 }
546 }
547 return true;
548 }
549 return false;
550}
551
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700552status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
553 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800554 AutoMutex _l(mLock);
555 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700556 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800557
558 if (device) {
559 // Check the key character map first.
560 sp<KeyCharacterMap> kcm = device->getKeyCharacterMap();
Yi Kong9b14ac62018-07-17 13:48:38 -0700561 if (kcm != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800562 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
563 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700564 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800565 }
566 }
567
568 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700569 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800570 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700571 status = NO_ERROR;
572 }
573 }
574
575 if (status == NO_ERROR) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700576 if (kcm != nullptr) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700577 kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState);
578 } else {
579 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800580 }
581 }
582 }
583
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700584 if (status != NO_ERROR) {
585 *outKeycode = 0;
586 *outFlags = 0;
587 *outMetaState = metaState;
588 }
589
590 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800591}
592
593status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
594 AutoMutex _l(mLock);
595 Device* device = getDeviceLocked(deviceId);
596
597 if (device && device->keyMap.haveKeyLayout()) {
598 status_t err = device->keyMap.keyLayoutMap->mapAxis(scanCode, outAxisInfo);
599 if (err == NO_ERROR) {
600 return NO_ERROR;
601 }
602 }
603
604 return NAME_NOT_FOUND;
605}
606
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100607void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800608 AutoMutex _l(mLock);
609
610 mExcludedDevices = devices;
611}
612
613bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
614 AutoMutex _l(mLock);
615 Device* device = getDeviceLocked(deviceId);
616 if (device && scanCode >= 0 && scanCode <= KEY_MAX) {
617 if (test_bit(scanCode, device->keyBitmask)) {
618 return true;
619 }
620 }
621 return false;
622}
623
624bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
625 AutoMutex _l(mLock);
626 Device* device = getDeviceLocked(deviceId);
627 int32_t sc;
628 if (device && mapLed(device, led, &sc) == NO_ERROR) {
629 if (test_bit(sc, device->ledBitmask)) {
630 return true;
631 }
632 }
633 return false;
634}
635
636void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
637 AutoMutex _l(mLock);
638 Device* device = getDeviceLocked(deviceId);
639 setLedStateLocked(device, led, on);
640}
641
642void EventHub::setLedStateLocked(Device* device, int32_t led, bool on) {
643 int32_t sc;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700644 if (device && device->hasValidFd() && mapLed(device, led, &sc) != NAME_NOT_FOUND) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800645 struct input_event ev;
646 ev.time.tv_sec = 0;
647 ev.time.tv_usec = 0;
648 ev.type = EV_LED;
649 ev.code = sc;
650 ev.value = on ? 1 : 0;
651
652 ssize_t nWrite;
653 do {
654 nWrite = write(device->fd, &ev, sizeof(struct input_event));
655 } while (nWrite == -1 && errno == EINTR);
656 }
657}
658
659void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700660 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800661 outVirtualKeys.clear();
662
663 AutoMutex _l(mLock);
664 Device* device = getDeviceLocked(deviceId);
665 if (device && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800666 const std::vector<VirtualKeyDefinition> virtualKeys =
667 device->virtualKeyMap->getVirtualKeys();
668 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800669 }
670}
671
672sp<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
673 AutoMutex _l(mLock);
674 Device* device = getDeviceLocked(deviceId);
675 if (device) {
676 return device->getKeyCharacterMap();
677 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700678 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800679}
680
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700681bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, const sp<KeyCharacterMap>& map) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800682 AutoMutex _l(mLock);
683 Device* device = getDeviceLocked(deviceId);
684 if (device) {
685 if (map != device->overlayKeyMap) {
686 device->overlayKeyMap = map;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700687 device->combinedKeyMap = KeyCharacterMap::combine(device->keyMap.keyCharacterMap, map);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800688 return true;
689 }
690 }
691 return false;
692}
693
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100694static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
695 std::string rawDescriptor;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700696 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800697 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100698 if (!identifier.uniqueId.empty()) {
699 rawDescriptor += "uniqueId:";
700 rawDescriptor += identifier.uniqueId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800701 } else if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100702 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800703 }
704
705 if (identifier.vendor == 0 && identifier.product == 0) {
706 // If we don't know the vendor and product id, then the device is probably
707 // built-in so we need to rely on other information to uniquely identify
708 // the input device. Usually we try to avoid relying on the device name or
709 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100710 if (!identifier.name.empty()) {
711 rawDescriptor += "name:";
712 rawDescriptor += identifier.name;
713 } else if (!identifier.location.empty()) {
714 rawDescriptor += "location:";
715 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800716 }
717 }
718 identifier.descriptor = sha1(rawDescriptor);
719 return rawDescriptor;
720}
721
722void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
723 // Compute a device descriptor that uniquely identifies the device.
724 // The descriptor is assumed to be a stable identifier. Its value should not
725 // change between reboots, reconnections, firmware updates or new releases
726 // of Android. In practice we sometimes get devices that cannot be uniquely
727 // identified. In this case we enforce uniqueness between connected devices.
728 // Ideally, we also want the descriptor to be short and relatively opaque.
729
730 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100731 std::string rawDescriptor = generateDescriptor(identifier);
732 if (identifier.uniqueId.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800733 // If it didn't have a unique id check for conflicts and enforce
734 // uniqueness if necessary.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700735 while (getDeviceByDescriptorLocked(identifier.descriptor) != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800736 identifier.nonce++;
737 rawDescriptor = generateDescriptor(identifier);
738 }
739 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100740 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700741 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800742}
743
744void EventHub::vibrate(int32_t deviceId, nsecs_t duration) {
745 AutoMutex _l(mLock);
746 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700747 if (device && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800748 ff_effect effect;
749 memset(&effect, 0, sizeof(effect));
750 effect.type = FF_RUMBLE;
751 effect.id = device->ffEffectId;
752 effect.u.rumble.strong_magnitude = 0xc000;
753 effect.u.rumble.weak_magnitude = 0xc000;
754 effect.replay.length = (duration + 999999LL) / 1000000LL;
755 effect.replay.delay = 0;
756 if (ioctl(device->fd, EVIOCSFF, &effect)) {
757 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700758 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800759 return;
760 }
761 device->ffEffectId = effect.id;
762
763 struct input_event ev;
764 ev.time.tv_sec = 0;
765 ev.time.tv_usec = 0;
766 ev.type = EV_FF;
767 ev.code = device->ffEffectId;
768 ev.value = 1;
769 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
770 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700771 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800772 return;
773 }
774 device->ffEffectPlaying = true;
775 }
776}
777
778void EventHub::cancelVibrate(int32_t deviceId) {
779 AutoMutex _l(mLock);
780 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700781 if (device && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800782 if (device->ffEffectPlaying) {
783 device->ffEffectPlaying = false;
784
785 struct input_event ev;
786 ev.time.tv_sec = 0;
787 ev.time.tv_usec = 0;
788 ev.type = EV_FF;
789 ev.code = device->ffEffectId;
790 ev.value = 0;
791 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
792 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700793 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800794 return;
795 }
796 }
797 }
798}
799
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100800EventHub::Device* EventHub::getDeviceByDescriptorLocked(const std::string& descriptor) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800801 size_t size = mDevices.size();
802 for (size_t i = 0; i < size; i++) {
803 Device* device = mDevices.valueAt(i);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100804 if (descriptor == device->identifier.descriptor) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800805 return device;
806 }
807 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700808 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800809}
810
811EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -0800812 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800813 deviceId = mBuiltInKeyboardId;
814 }
815 ssize_t index = mDevices.indexOfKey(deviceId);
816 return index >= 0 ? mDevices.valueAt(index) : NULL;
817}
818
819EventHub::Device* EventHub::getDeviceByPathLocked(const char* devicePath) const {
820 for (size_t i = 0; i < mDevices.size(); i++) {
821 Device* device = mDevices.valueAt(i);
822 if (device->path == devicePath) {
823 return device;
824 }
825 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700826 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800827}
828
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700829/**
830 * The file descriptor could be either input device, or a video device (associated with a
831 * specific input device). Check both cases here, and return the device that this event
832 * belongs to. Caller can compare the fd's once more to determine event type.
833 * Looks through all input devices, and only attached video devices. Unattached video
834 * devices are ignored.
835 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700836EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
837 for (size_t i = 0; i < mDevices.size(); i++) {
838 Device* device = mDevices.valueAt(i);
839 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700840 // This is an input device event
841 return device;
842 }
843 if (device->videoDevice && device->videoDevice->getFd() == fd) {
844 // This is a video device event
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700845 return device;
846 }
847 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700848 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
849 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700850 return nullptr;
851}
852
Michael Wrightd02c5b62014-02-10 15:10:22 -0800853size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
854 ALOG_ASSERT(bufferSize >= 1);
855
856 AutoMutex _l(mLock);
857
858 struct input_event readBuffer[bufferSize];
859
860 RawEvent* event = buffer;
861 size_t capacity = bufferSize;
862 bool awoken = false;
863 for (;;) {
864 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
865
866 // Reopen input devices if needed.
867 if (mNeedToReopenDevices) {
868 mNeedToReopenDevices = false;
869
870 ALOGI("Reopening all input devices due to a configuration change.");
871
872 closeAllDevicesLocked();
873 mNeedToScanDevices = true;
874 break; // return to the caller before we actually rescan
875 }
876
877 // Report any devices that had last been added/removed.
878 while (mClosingDevices) {
879 Device* device = mClosingDevices;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700880 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800881 mClosingDevices = device->next;
882 event->when = now;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700883 event->deviceId = (device->id == mBuiltInKeyboardId)
884 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
885 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800886 event->type = DEVICE_REMOVED;
887 event += 1;
888 delete device;
889 mNeedToSendFinishedDeviceScan = true;
890 if (--capacity == 0) {
891 break;
892 }
893 }
894
895 if (mNeedToScanDevices) {
896 mNeedToScanDevices = false;
897 scanDevicesLocked();
898 mNeedToSendFinishedDeviceScan = true;
899 }
900
Yi Kong9b14ac62018-07-17 13:48:38 -0700901 while (mOpeningDevices != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800902 Device* device = mOpeningDevices;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700903 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904 mOpeningDevices = device->next;
905 event->when = now;
906 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
907 event->type = DEVICE_ADDED;
908 event += 1;
909 mNeedToSendFinishedDeviceScan = true;
910 if (--capacity == 0) {
911 break;
912 }
913 }
914
915 if (mNeedToSendFinishedDeviceScan) {
916 mNeedToSendFinishedDeviceScan = false;
917 event->when = now;
918 event->type = FINISHED_DEVICE_SCAN;
919 event += 1;
920 if (--capacity == 0) {
921 break;
922 }
923 }
924
925 // Grab the next input event.
926 bool deviceChanged = false;
927 while (mPendingEventIndex < mPendingEventCount) {
928 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700929 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800930 if (eventItem.events & EPOLLIN) {
931 mPendingINotify = true;
932 } else {
933 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
934 }
935 continue;
936 }
937
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700938 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800939 if (eventItem.events & EPOLLIN) {
940 ALOGV("awoken after wake()");
941 awoken = true;
942 char buffer[16];
943 ssize_t nRead;
944 do {
945 nRead = read(mWakeReadPipeFd, buffer, sizeof(buffer));
946 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(buffer));
947 } else {
948 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700949 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800950 }
951 continue;
952 }
953
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700954 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700955 if (!device) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700956 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
957 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700958 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800959 continue;
960 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700961 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
962 if (eventItem.events & EPOLLIN) {
963 size_t numFrames = device->videoDevice->readAndQueueFrames();
964 if (numFrames == 0) {
965 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700966 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700967 }
968 } else if (eventItem.events & EPOLLHUP) {
969 // TODO(b/121395353) - consider adding EPOLLRDHUP
970 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700971 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700972 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
973 device->videoDevice = nullptr;
974 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700975 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
976 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700977 ALOG_ASSERT(!DEBUG);
978 }
979 continue;
980 }
981 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -0800982 if (eventItem.events & EPOLLIN) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700983 int32_t readSize =
984 read(device->fd, readBuffer, sizeof(struct input_event) * capacity);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800985 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
986 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -0700987 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700988 " bufferSize: %zu capacity: %zu errno: %d)\n",
989 device->fd, readSize, bufferSize, capacity, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800990 deviceChanged = true;
991 closeDeviceLocked(device);
992 } else if (readSize < 0) {
993 if (errno != EAGAIN && errno != EINTR) {
994 ALOGW("could not get event (errno=%d)", errno);
995 }
996 } else if ((readSize % sizeof(struct input_event)) != 0) {
997 ALOGE("could not get event (wrong size: %d)", readSize);
998 } else {
999 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1000
1001 size_t count = size_t(readSize) / sizeof(struct input_event);
1002 for (size_t i = 0; i < count; i++) {
1003 struct input_event& iev = readBuffer[i];
Siarhei Vishniakou592bac22018-11-08 19:42:38 -08001004 event->when = processEventTimestamp(iev);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001005 event->deviceId = deviceId;
1006 event->type = iev.type;
1007 event->code = iev.code;
1008 event->value = iev.value;
1009 event += 1;
1010 capacity -= 1;
1011 }
1012 if (capacity == 0) {
1013 // The result buffer is full. Reset the pending event index
1014 // so we will try to read the device again on the next iteration.
1015 mPendingEventIndex -= 1;
1016 break;
1017 }
1018 }
1019 } else if (eventItem.events & EPOLLHUP) {
1020 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001021 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001022 deviceChanged = true;
1023 closeDeviceLocked(device);
1024 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001025 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1026 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001027 }
1028 }
1029
1030 // readNotify() will modify the list of devices so this must be done after
1031 // processing all other events to ensure that we read all remaining events
1032 // before closing the devices.
1033 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
1034 mPendingINotify = false;
1035 readNotifyLocked();
1036 deviceChanged = true;
1037 }
1038
1039 // Report added or removed devices immediately.
1040 if (deviceChanged) {
1041 continue;
1042 }
1043
1044 // Return now if we have collected any events or if we were explicitly awoken.
1045 if (event != buffer || awoken) {
1046 break;
1047 }
1048
1049 // Poll for events. Mind the wake lock dance!
1050 // We hold a wake lock at all times except during epoll_wait(). This works due to some
1051 // subtle choreography. When a device driver has pending (unread) events, it acquires
1052 // a kernel wake lock. However, once the last pending event has been read, the device
1053 // driver will release the kernel wake lock. To prevent the system from going to sleep
1054 // when this happens, the EventHub holds onto its own user wake lock while the client
1055 // is processing events. Thus the system can only sleep if there are no events
1056 // pending or currently being processed.
1057 //
1058 // The timeout is advisory only. If the device is asleep, it will not wake just to
1059 // service the timeout.
1060 mPendingEventIndex = 0;
1061
1062 mLock.unlock(); // release lock before poll, must be before release_wake_lock
1063 release_wake_lock(WAKE_LOCK_ID);
1064
1065 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1066
1067 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
1068 mLock.lock(); // reacquire lock after poll, must be after acquire_wake_lock
1069
1070 if (pollResult == 0) {
1071 // Timed out.
1072 mPendingEventCount = 0;
1073 break;
1074 }
1075
1076 if (pollResult < 0) {
1077 // An error occurred.
1078 mPendingEventCount = 0;
1079
1080 // Sleep after errors to avoid locking up the system.
1081 // Hopefully the error is transient.
1082 if (errno != EINTR) {
1083 ALOGW("poll failed (errno=%d)\n", errno);
1084 usleep(100000);
1085 }
1086 } else {
1087 // Some events occurred.
1088 mPendingEventCount = size_t(pollResult);
1089 }
1090 }
1091
1092 // All done, return the number of events we read.
1093 return event - buffer;
1094}
1095
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001096std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
1097 AutoMutex _l(mLock);
1098
1099 Device* device = getDeviceLocked(deviceId);
1100 if (!device || !device->videoDevice) {
1101 return {};
1102 }
1103 return device->videoDevice->consumeFrames();
1104}
1105
Michael Wrightd02c5b62014-02-10 15:10:22 -08001106void EventHub::wake() {
1107 ALOGV("wake() called");
1108
1109 ssize_t nWrite;
1110 do {
1111 nWrite = write(mWakeWritePipeFd, "W", 1);
1112 } while (nWrite == -1 && errno == EINTR);
1113
1114 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001115 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001116 }
1117}
1118
1119void EventHub::scanDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001120 status_t result = scanDirLocked(DEVICE_PATH);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001121 if (result < 0) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001122 ALOGE("scan dir failed for %s", DEVICE_PATH);
1123 }
Philip Quinn39b81682019-01-09 22:20:39 -08001124 if (isV4lScanningEnabled()) {
1125 result = scanVideoDirLocked(VIDEO_DEVICE_PATH);
1126 if (result != OK) {
1127 ALOGE("scan video dir failed for %s", VIDEO_DEVICE_PATH);
1128 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001129 }
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001130 if (mDevices.indexOfKey(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) < 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001131 createVirtualKeyboardLocked();
1132 }
1133}
1134
1135// ----------------------------------------------------------------------------
1136
1137static bool containsNonZeroByte(const uint8_t* array, uint32_t startIndex, uint32_t endIndex) {
1138 const uint8_t* end = array + endIndex;
1139 array += startIndex;
1140 while (array != end) {
1141 if (*(array++) != 0) {
1142 return true;
1143 }
1144 }
1145 return false;
1146}
1147
1148static const int32_t GAMEPAD_KEYCODES[] = {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001149 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C, //
1150 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z, //
1151 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1, //
1152 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2, //
1153 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR, //
1154 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE, //
Michael Wrightd02c5b62014-02-10 15:10:22 -08001155};
1156
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001157status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001158 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001159 struct epoll_event eventItem = {};
1160 eventItem.events = EPOLLIN | EPOLLWAKEUP;
1161 eventItem.data.fd = fd;
1162 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1163 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001164 return -errno;
1165 }
1166 return OK;
1167}
1168
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001169status_t EventHub::unregisterFdFromEpoll(int fd) {
1170 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
1171 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
1172 return -errno;
1173 }
1174 return OK;
1175}
1176
1177status_t EventHub::registerDeviceForEpollLocked(Device* device) {
1178 if (device == nullptr) {
1179 if (DEBUG) {
1180 LOG_ALWAYS_FATAL("Cannot call registerDeviceForEpollLocked with null Device");
1181 }
1182 return BAD_VALUE;
1183 }
1184 status_t result = registerFdForEpoll(device->fd);
1185 if (result != OK) {
1186 ALOGE("Could not add input device fd to epoll for device %" PRId32, device->id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001187 return result;
1188 }
1189 if (device->videoDevice) {
1190 registerVideoDeviceForEpollLocked(*device->videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001191 }
1192 return result;
1193}
1194
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001195void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
1196 status_t result = registerFdForEpoll(videoDevice.getFd());
1197 if (result != OK) {
1198 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
1199 }
1200}
1201
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001202status_t EventHub::unregisterDeviceFromEpollLocked(Device* device) {
1203 if (device->hasValidFd()) {
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001204 status_t result = unregisterFdFromEpoll(device->fd);
1205 if (result != OK) {
1206 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device->id);
1207 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001208 }
1209 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001210 if (device->videoDevice) {
1211 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1212 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001213 return OK;
1214}
1215
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001216void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
1217 if (videoDevice.hasValidFd()) {
1218 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
1219 if (result != OK) {
1220 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001221 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001222 }
1223 }
1224}
1225
1226status_t EventHub::openDeviceLocked(const char* devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001227 char buffer[80];
1228
1229 ALOGV("Opening device: %s", devicePath);
1230
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001231 int fd = open(devicePath, O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001232 if (fd < 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001233 ALOGE("could not open %s, %s\n", devicePath, strerror(errno));
1234 return -1;
1235 }
1236
1237 InputDeviceIdentifier identifier;
1238
1239 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001240 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001241 ALOGE("Could not get device name for %s: %s", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001242 } else {
1243 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001244 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001245 }
1246
1247 // Check to see if the device is on our excluded list
1248 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001249 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001250 if (identifier.name == item) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001251 ALOGI("ignoring event id %s driver %s\n", devicePath, item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001252 close(fd);
1253 return -1;
1254 }
1255 }
1256
1257 // Get device driver version.
1258 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001259 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001260 ALOGE("could not get driver version for %s, %s\n", devicePath, strerror(errno));
1261 close(fd);
1262 return -1;
1263 }
1264
1265 // Get device identifier.
1266 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001267 if (ioctl(fd, EVIOCGID, &inputId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001268 ALOGE("could not get device input id for %s, %s\n", devicePath, strerror(errno));
1269 close(fd);
1270 return -1;
1271 }
1272 identifier.bus = inputId.bustype;
1273 identifier.product = inputId.product;
1274 identifier.vendor = inputId.vendor;
1275 identifier.version = inputId.version;
1276
1277 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001278 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
1279 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001280 } else {
1281 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001282 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001283 }
1284
1285 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001286 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
1287 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001288 } else {
1289 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001290 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001291 }
1292
1293 // Fill in the descriptor.
1294 assignDescriptorLocked(identifier);
1295
Michael Wrightd02c5b62014-02-10 15:10:22 -08001296 // Allocate device. (The device object takes ownership of the fd at this point.)
1297 int32_t deviceId = mNextDeviceId++;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001298 Device* device = new Device(fd, deviceId, devicePath, identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001299
1300 ALOGV("add device %d: %s\n", deviceId, devicePath);
1301 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001302 " vendor %04x\n"
1303 " product %04x\n"
1304 " version %04x\n",
1305 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001306 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
1307 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
1308 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
1309 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001310 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
1311 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001312
1313 // Load the configuration file for the device.
1314 loadConfigurationLocked(device);
1315
1316 // Figure out the kinds of events the device reports.
1317 ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(device->keyBitmask)), device->keyBitmask);
1318 ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(device->absBitmask)), device->absBitmask);
1319 ioctl(fd, EVIOCGBIT(EV_REL, sizeof(device->relBitmask)), device->relBitmask);
1320 ioctl(fd, EVIOCGBIT(EV_SW, sizeof(device->swBitmask)), device->swBitmask);
1321 ioctl(fd, EVIOCGBIT(EV_LED, sizeof(device->ledBitmask)), device->ledBitmask);
1322 ioctl(fd, EVIOCGBIT(EV_FF, sizeof(device->ffBitmask)), device->ffBitmask);
1323 ioctl(fd, EVIOCGPROP(sizeof(device->propBitmask)), device->propBitmask);
1324
1325 // See if this is a keyboard. Ignore everything in the button range except for
1326 // joystick and gamepad buttons which are handled like keyboards for the most part.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001327 bool haveKeyboardKeys =
1328 containsNonZeroByte(device->keyBitmask, 0, sizeof_bit_array(BTN_MISC)) ||
1329 containsNonZeroByte(device->keyBitmask, sizeof_bit_array(KEY_OK),
1330 sizeof_bit_array(KEY_MAX + 1));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001331 bool haveGamepadButtons = containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_MISC),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001332 sizeof_bit_array(BTN_MOUSE)) ||
1333 containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_JOYSTICK),
1334 sizeof_bit_array(BTN_DIGI));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001335 if (haveKeyboardKeys || haveGamepadButtons) {
1336 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1337 }
1338
1339 // See if this is a cursor device such as a trackball or mouse.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001340 if (test_bit(BTN_MOUSE, device->keyBitmask) && test_bit(REL_X, device->relBitmask) &&
1341 test_bit(REL_Y, device->relBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001342 device->classes |= INPUT_DEVICE_CLASS_CURSOR;
1343 }
1344
Prashant Malani1941ff52015-08-11 18:29:28 -07001345 // See if this is a rotary encoder type device.
1346 String8 deviceType = String8();
1347 if (device->configuration &&
1348 device->configuration->tryGetProperty(String8("device.type"), deviceType)) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001349 if (!deviceType.compare(String8("rotaryEncoder"))) {
1350 device->classes |= INPUT_DEVICE_CLASS_ROTARY_ENCODER;
1351 }
Prashant Malani1941ff52015-08-11 18:29:28 -07001352 }
1353
Michael Wrightd02c5b62014-02-10 15:10:22 -08001354 // See if this is a touch pad.
1355 // Is this a new modern multi-touch driver?
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001356 if (test_bit(ABS_MT_POSITION_X, device->absBitmask) &&
1357 test_bit(ABS_MT_POSITION_Y, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001358 // Some joysticks such as the PS3 controller report axes that conflict
1359 // with the ABS_MT range. Try to confirm that the device really is
1360 // a touch screen.
1361 if (test_bit(BTN_TOUCH, device->keyBitmask) || !haveGamepadButtons) {
1362 device->classes |= INPUT_DEVICE_CLASS_TOUCH | INPUT_DEVICE_CLASS_TOUCH_MT;
1363 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001364 // Is this an old style single-touch driver?
1365 } else if (test_bit(BTN_TOUCH, device->keyBitmask) && test_bit(ABS_X, device->absBitmask) &&
1366 test_bit(ABS_Y, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001367 device->classes |= INPUT_DEVICE_CLASS_TOUCH;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001368 // Is this a BT stylus?
Michael Wright842500e2015-03-13 17:32:02 -07001369 } else if ((test_bit(ABS_PRESSURE, device->absBitmask) ||
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001370 test_bit(BTN_TOUCH, device->keyBitmask)) &&
1371 !test_bit(ABS_X, device->absBitmask) && !test_bit(ABS_Y, device->absBitmask)) {
Michael Wright842500e2015-03-13 17:32:02 -07001372 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
1373 // Keyboard will try to claim some of the buttons but we really want to reserve those so we
1374 // can fuse it with the touch screen data, so just take them back. Note this means an
1375 // external stylus cannot also be a keyboard device.
1376 device->classes &= ~INPUT_DEVICE_CLASS_KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001377 }
1378
1379 // See if this device is a joystick.
1380 // Assumes that joysticks always have gamepad buttons in order to distinguish them
1381 // from other devices such as accelerometers that also have absolute axes.
1382 if (haveGamepadButtons) {
1383 uint32_t assumedClasses = device->classes | INPUT_DEVICE_CLASS_JOYSTICK;
1384 for (int i = 0; i <= ABS_MAX; i++) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001385 if (test_bit(i, device->absBitmask) &&
1386 (getAbsAxisUsage(i, assumedClasses) & INPUT_DEVICE_CLASS_JOYSTICK)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001387 device->classes = assumedClasses;
1388 break;
1389 }
1390 }
1391 }
1392
1393 // Check whether this device has switches.
1394 for (int i = 0; i <= SW_MAX; i++) {
1395 if (test_bit(i, device->swBitmask)) {
1396 device->classes |= INPUT_DEVICE_CLASS_SWITCH;
1397 break;
1398 }
1399 }
1400
1401 // Check whether this device supports the vibrator.
1402 if (test_bit(FF_RUMBLE, device->ffBitmask)) {
1403 device->classes |= INPUT_DEVICE_CLASS_VIBRATOR;
1404 }
1405
1406 // Configure virtual keys.
1407 if ((device->classes & INPUT_DEVICE_CLASS_TOUCH)) {
1408 // Load the virtual keys for the touch screen, if any.
1409 // We do this now so that we can make sure to load the keymap if necessary.
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001410 bool success = loadVirtualKeyMapLocked(device);
1411 if (success) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001412 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1413 }
1414 }
1415
1416 // Load the key map.
1417 // We need to do this for joysticks too because the key layout may specify axes.
1418 status_t keyMapStatus = NAME_NOT_FOUND;
1419 if (device->classes & (INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_JOYSTICK)) {
1420 // Load the keymap for the device.
1421 keyMapStatus = loadKeyMapLocked(device);
1422 }
1423
1424 // Configure the keyboard, gamepad or virtual keyboard.
1425 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1426 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001427 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
1428 isEligibleBuiltInKeyboard(device->identifier, device->configuration, &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001429 mBuiltInKeyboardId = device->id;
1430 }
1431
1432 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
1433 if (hasKeycodeLocked(device, AKEYCODE_Q)) {
1434 device->classes |= INPUT_DEVICE_CLASS_ALPHAKEY;
1435 }
1436
1437 // See if this device has a DPAD.
1438 if (hasKeycodeLocked(device, AKEYCODE_DPAD_UP) &&
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001439 hasKeycodeLocked(device, AKEYCODE_DPAD_DOWN) &&
1440 hasKeycodeLocked(device, AKEYCODE_DPAD_LEFT) &&
1441 hasKeycodeLocked(device, AKEYCODE_DPAD_RIGHT) &&
1442 hasKeycodeLocked(device, AKEYCODE_DPAD_CENTER)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001443 device->classes |= INPUT_DEVICE_CLASS_DPAD;
1444 }
1445
1446 // See if this device has a gamepad.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001447 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES) / sizeof(GAMEPAD_KEYCODES[0]); i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001448 if (hasKeycodeLocked(device, GAMEPAD_KEYCODES[i])) {
1449 device->classes |= INPUT_DEVICE_CLASS_GAMEPAD;
1450 break;
1451 }
1452 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001453 }
1454
1455 // If the device isn't recognized as something we handle, don't monitor it.
1456 if (device->classes == 0) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001457 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath,
1458 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001459 delete device;
1460 return -1;
1461 }
1462
Tim Kilbourn063ff532015-04-08 10:26:18 -07001463 // Determine whether the device has a mic.
1464 if (deviceHasMicLocked(device)) {
1465 device->classes |= INPUT_DEVICE_CLASS_MIC;
1466 }
1467
Michael Wrightd02c5b62014-02-10 15:10:22 -08001468 // Determine whether the device is external or internal.
1469 if (isExternalDeviceLocked(device)) {
1470 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL;
1471 }
1472
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001473 if (device->classes & (INPUT_DEVICE_CLASS_JOYSTICK | INPUT_DEVICE_CLASS_DPAD) &&
1474 device->classes & INPUT_DEVICE_CLASS_GAMEPAD) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001475 device->controllerNumber = getNextControllerNumberLocked(device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001476 setLedForControllerLocked(device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001477 }
1478
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001479 // Find a matching video device by comparing device names
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001480 // This should be done before registerDeviceForEpollLocked, so that both fds are added to epoll
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001481 for (std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
1482 if (device->identifier.name == videoDevice->getName()) {
1483 device->videoDevice = std::move(videoDevice);
1484 break;
1485 }
1486 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001487 mUnattachedVideoDevices
1488 .erase(std::remove_if(mUnattachedVideoDevices.begin(), mUnattachedVideoDevices.end(),
1489 [](const std::unique_ptr<TouchVideoDevice>& videoDevice) {
1490 return videoDevice == nullptr;
1491 }),
1492 mUnattachedVideoDevices.end());
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001493
1494 if (registerDeviceForEpollLocked(device) != OK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001495 delete device;
1496 return -1;
1497 }
1498
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001499 configureFd(device);
1500
1501 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=0x%x, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001502 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
1503 deviceId, fd, devicePath, device->identifier.name.c_str(), device->classes,
1504 device->configurationFile.c_str(), device->keyMap.keyLayoutFile.c_str(),
1505 device->keyMap.keyCharacterMapFile.c_str(), toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001506
1507 addDeviceLocked(device);
1508 return OK;
1509}
1510
1511void EventHub::configureFd(Device* device) {
1512 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
1513 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1514 // Disable kernel key repeat since we handle it ourselves
1515 unsigned int repeatRate[] = {0, 0};
1516 if (ioctl(device->fd, EVIOCSREP, repeatRate)) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001517 ALOGW("Unable to disable kernel key repeat for %s: %s", device->path.c_str(),
1518 strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001519 }
1520 }
1521
Michael Wrightd02c5b62014-02-10 15:10:22 -08001522 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
1523 // associated with input events. This is important because the input system
1524 // uses the timestamps extensively and assumes they were recorded using the monotonic
1525 // clock.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001526 int clockId = CLOCK_MONOTONIC;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001527 bool usingClockIoctl = !ioctl(device->fd, EVIOCSCLOCKID, &clockId);
Atif Niyaz4180aa42019-05-10 16:27:48 -07001528 ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001529}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001530
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001531void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
1532 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
1533 if (!videoDevice) {
1534 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
1535 return;
1536 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001537 // Transfer ownership of this video device to a matching input device
1538 for (size_t i = 0; i < mDevices.size(); i++) {
1539 Device* device = mDevices.valueAt(i);
1540 if (videoDevice->getName() == device->identifier.name) {
1541 device->videoDevice = std::move(videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001542 if (device->enabled) {
1543 registerVideoDeviceForEpollLocked(*device->videoDevice);
1544 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001545 return;
1546 }
1547 }
1548
1549 // Couldn't find a matching input device, so just add it to a temporary holding queue.
1550 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001551 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001552 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001553 mUnattachedVideoDevices.push_back(std::move(videoDevice));
1554}
1555
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001556bool EventHub::isDeviceEnabled(int32_t deviceId) {
1557 AutoMutex _l(mLock);
1558 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001559 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001560 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1561 return false;
1562 }
1563 return device->enabled;
1564}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001565
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001566status_t EventHub::enableDevice(int32_t deviceId) {
1567 AutoMutex _l(mLock);
1568 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001569 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001570 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1571 return BAD_VALUE;
1572 }
1573 if (device->enabled) {
1574 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
1575 return OK;
1576 }
1577 status_t result = device->enable();
1578 if (result != OK) {
1579 ALOGE("Failed to enable device %" PRId32, deviceId);
1580 return result;
1581 }
1582
1583 configureFd(device);
1584
1585 return registerDeviceForEpollLocked(device);
1586}
1587
1588status_t EventHub::disableDevice(int32_t deviceId) {
1589 AutoMutex _l(mLock);
1590 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001591 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001592 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1593 return BAD_VALUE;
1594 }
1595 if (!device->enabled) {
1596 ALOGW("Duplicate call to %s, input device already disabled", __func__);
1597 return OK;
1598 }
1599 unregisterDeviceFromEpollLocked(device);
1600 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001601}
1602
1603void EventHub::createVirtualKeyboardLocked() {
1604 InputDeviceIdentifier identifier;
1605 identifier.name = "Virtual";
1606 identifier.uniqueId = "<virtual>";
1607 assignDescriptorLocked(identifier);
1608
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001609 Device* device =
1610 new Device(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>", identifier);
1611 device->classes = INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_ALPHAKEY |
1612 INPUT_DEVICE_CLASS_DPAD | INPUT_DEVICE_CLASS_VIRTUAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001613 loadKeyMapLocked(device);
1614 addDeviceLocked(device);
1615}
1616
1617void EventHub::addDeviceLocked(Device* device) {
1618 mDevices.add(device->id, device);
1619 device->next = mOpeningDevices;
1620 mOpeningDevices = device;
1621}
1622
1623void EventHub::loadConfigurationLocked(Device* device) {
1624 device->configurationFile = getInputDeviceConfigurationFilePathByDeviceIdentifier(
1625 device->identifier, INPUT_DEVICE_CONFIGURATION_FILE_TYPE_CONFIGURATION);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001626 if (device->configurationFile.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001627 ALOGD("No input device configuration file found for device '%s'.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001628 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001629 } else {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001630 status_t status = PropertyMap::load(String8(device->configurationFile.c_str()),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001631 &device->configuration);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001632 if (status) {
1633 ALOGE("Error loading input device configuration file for device '%s'. "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001634 "Using default configuration.",
1635 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001636 }
1637 }
1638}
1639
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001640bool EventHub::loadVirtualKeyMapLocked(Device* device) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001641 // The virtual key map is supplied by the kernel as a system board property file.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001642 std::string path;
1643 path += "/sys/board_properties/virtualkeys.";
Siarhei Vishniakoub45635c2019-02-20 19:22:09 -06001644 path += device->identifier.getCanonicalName();
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001645 if (access(path.c_str(), R_OK)) {
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001646 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001647 }
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001648 device->virtualKeyMap = VirtualKeyMap::load(path);
1649 return device->virtualKeyMap != nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001650}
1651
1652status_t EventHub::loadKeyMapLocked(Device* device) {
1653 return device->keyMap.load(device->identifier, device->configuration);
1654}
1655
1656bool EventHub::isExternalDeviceLocked(Device* device) {
1657 if (device->configuration) {
1658 bool value;
1659 if (device->configuration->tryGetProperty(String8("device.internal"), value)) {
1660 return !value;
1661 }
1662 }
1663 return device->identifier.bus == BUS_USB || device->identifier.bus == BUS_BLUETOOTH;
1664}
1665
Tim Kilbourn063ff532015-04-08 10:26:18 -07001666bool EventHub::deviceHasMicLocked(Device* device) {
1667 if (device->configuration) {
1668 bool value;
1669 if (device->configuration->tryGetProperty(String8("audio.mic"), value)) {
1670 return value;
1671 }
1672 }
1673 return false;
1674}
1675
Michael Wrightd02c5b62014-02-10 15:10:22 -08001676int32_t EventHub::getNextControllerNumberLocked(Device* device) {
1677 if (mControllerNumbers.isFull()) {
1678 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001679 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001680 return 0;
1681 }
1682 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
1683 // one
1684 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
1685}
1686
1687void EventHub::releaseControllerNumberLocked(Device* device) {
1688 int32_t num = device->controllerNumber;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001689 device->controllerNumber = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001690 if (num == 0) {
1691 return;
1692 }
1693 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
1694}
1695
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001696void EventHub::setLedForControllerLocked(Device* device) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001697 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
1698 setLedStateLocked(device, ALED_CONTROLLER_1 + i, device->controllerNumber == i + 1);
1699 }
1700}
1701
1702bool EventHub::hasKeycodeLocked(Device* device, int keycode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001703 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001704 return false;
1705 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001706
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001707 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001708 device->keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes);
1709 const size_t N = scanCodes.size();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001710 for (size_t i = 0; i < N && i <= KEY_MAX; i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001711 int32_t sc = scanCodes[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001712 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, device->keyBitmask)) {
1713 return true;
1714 }
1715 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001716
Michael Wrightd02c5b62014-02-10 15:10:22 -08001717 return false;
1718}
1719
1720status_t EventHub::mapLed(Device* device, int32_t led, int32_t* outScanCode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001721 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001722 return NAME_NOT_FOUND;
1723 }
1724
1725 int32_t scanCode;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001726 if (device->keyMap.keyLayoutMap->findScanCodeForLed(led, &scanCode) != NAME_NOT_FOUND) {
1727 if (scanCode >= 0 && scanCode <= LED_MAX && test_bit(scanCode, device->ledBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001728 *outScanCode = scanCode;
1729 return NO_ERROR;
1730 }
1731 }
1732 return NAME_NOT_FOUND;
1733}
1734
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001735void EventHub::closeDeviceByPathLocked(const char* devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001736 Device* device = getDeviceByPathLocked(devicePath);
1737 if (device) {
1738 closeDeviceLocked(device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001739 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001740 }
1741 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001742}
1743
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001744/**
1745 * Find the video device by filename, and close it.
1746 * The video device is closed by path during an inotify event, where we don't have the
1747 * additional context about the video device fd, or the associated input device.
1748 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001749void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001750 // A video device may be owned by an existing input device, or it may be stored in
1751 // the mUnattachedVideoDevices queue. Check both locations.
1752 for (size_t i = 0; i < mDevices.size(); i++) {
1753 Device* device = mDevices.valueAt(i);
1754 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001755 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001756 device->videoDevice = nullptr;
1757 return;
1758 }
1759 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001760 mUnattachedVideoDevices
1761 .erase(std::remove_if(mUnattachedVideoDevices.begin(), mUnattachedVideoDevices.end(),
1762 [&devicePath](
1763 const std::unique_ptr<TouchVideoDevice>& videoDevice) {
1764 return videoDevice->getPath() == devicePath;
1765 }),
1766 mUnattachedVideoDevices.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001767}
1768
1769void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001770 mUnattachedVideoDevices.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001771 while (mDevices.size() > 0) {
1772 closeDeviceLocked(mDevices.valueAt(mDevices.size() - 1));
1773 }
1774}
1775
1776void EventHub::closeDeviceLocked(Device* device) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001777 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=0x%x", device->path.c_str(),
1778 device->identifier.name.c_str(), device->id, device->fd, device->classes);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001779
1780 if (device->id == mBuiltInKeyboardId) {
1781 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001782 device->path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001783 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
1784 }
1785
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001786 unregisterDeviceFromEpollLocked(device);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001787 if (device->videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001788 // This must be done after the video device is removed from epoll
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001789 mUnattachedVideoDevices.push_back(std::move(device->videoDevice));
1790 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001791
1792 releaseControllerNumberLocked(device);
1793
1794 mDevices.removeItem(device->id);
1795 device->close();
1796
1797 // Unlink for opening devices list if it is present.
Yi Kong9b14ac62018-07-17 13:48:38 -07001798 Device* pred = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799 bool found = false;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001800 for (Device* entry = mOpeningDevices; entry != nullptr;) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001801 if (entry == device) {
1802 found = true;
1803 break;
1804 }
1805 pred = entry;
1806 entry = entry->next;
1807 }
1808 if (found) {
1809 // Unlink the device from the opening devices list then delete it.
1810 // We don't need to tell the client that the device was closed because
1811 // it does not even know it was opened in the first place.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001812 ALOGI("Device %s was immediately closed after opening.", device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001813 if (pred) {
1814 pred->next = device->next;
1815 } else {
1816 mOpeningDevices = device->next;
1817 }
1818 delete device;
1819 } else {
1820 // Link into closing devices list.
1821 // The device will be deleted later after we have informed the client.
1822 device->next = mClosingDevices;
1823 mClosingDevices = device;
1824 }
1825}
1826
1827status_t EventHub::readNotifyLocked() {
1828 int res;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001829 char event_buf[512];
1830 int event_size;
1831 int event_pos = 0;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001832 struct inotify_event* event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001833
1834 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
1835 res = read(mINotifyFd, event_buf, sizeof(event_buf));
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001836 if (res < (int)sizeof(*event)) {
1837 if (errno == EINTR) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001838 ALOGW("could not get event, %s\n", strerror(errno));
1839 return -1;
1840 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001841
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001842 while (res >= (int)sizeof(*event)) {
1843 event = (struct inotify_event*)(event_buf + event_pos);
1844 if (event->len) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001845 if (event->wd == mInputWd) {
1846 std::string filename = StringPrintf("%s/%s", DEVICE_PATH, event->name);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001847 if (event->mask & IN_CREATE) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001848 openDeviceLocked(filename.c_str());
1849 } else {
1850 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
1851 closeDeviceByPathLocked(filename.c_str());
1852 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001853 } else if (event->wd == mVideoWd) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001854 if (isV4lTouchNode(event->name)) {
1855 std::string filename = StringPrintf("%s/%s", VIDEO_DEVICE_PATH, event->name);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001856 if (event->mask & IN_CREATE) {
1857 openVideoDeviceLocked(filename);
1858 } else {
1859 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
1860 closeVideoDeviceByPathLocked(filename);
1861 }
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001862 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001863 } else {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001864 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event->wd);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001865 }
1866 }
1867 event_size = sizeof(*event) + event->len;
1868 res -= event_size;
1869 event_pos += event_size;
1870 }
1871 return 0;
1872}
1873
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001874status_t EventHub::scanDirLocked(const char* dirname) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001875 char devname[PATH_MAX];
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001876 char* filename;
1877 DIR* dir;
1878 struct dirent* de;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001879 dir = opendir(dirname);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001880 if (dir == nullptr) return -1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001881 strcpy(devname, dirname);
1882 filename = devname + strlen(devname);
1883 *filename++ = '/';
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001884 while ((de = readdir(dir))) {
1885 if (de->d_name[0] == '.' &&
1886 (de->d_name[1] == '\0' || (de->d_name[1] == '.' && de->d_name[2] == '\0')))
Michael Wrightd02c5b62014-02-10 15:10:22 -08001887 continue;
1888 strcpy(filename, de->d_name);
1889 openDeviceLocked(devname);
1890 }
1891 closedir(dir);
1892 return 0;
1893}
1894
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001895/**
1896 * Look for all dirname/v4l-touch* devices, and open them.
1897 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001898status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001899 DIR* dir;
1900 struct dirent* de;
1901 dir = opendir(dirname.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001902 if (!dir) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001903 ALOGE("Could not open video directory %s", dirname.c_str());
1904 return BAD_VALUE;
1905 }
1906
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001907 while ((de = readdir(dir))) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001908 const char* name = de->d_name;
1909 if (isV4lTouchNode(name)) {
1910 ALOGI("Found touch video device %s", name);
1911 openVideoDeviceLocked(dirname + "/" + name);
1912 }
1913 }
1914 closedir(dir);
1915 return OK;
1916}
1917
Michael Wrightd02c5b62014-02-10 15:10:22 -08001918void EventHub::requestReopenDevices() {
1919 ALOGV("requestReopenDevices() called");
1920
1921 AutoMutex _l(mLock);
1922 mNeedToReopenDevices = true;
1923}
1924
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001925void EventHub::dump(std::string& dump) {
1926 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001927
1928 { // acquire lock
1929 AutoMutex _l(mLock);
1930
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001931 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001932
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001933 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001934
1935 for (size_t i = 0; i < mDevices.size(); i++) {
1936 const Device* device = mDevices.valueAt(i);
1937 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001938 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001939 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001940 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001941 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001942 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001943 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001944 dump += StringPrintf(INDENT3 "Classes: 0x%08x\n", device->classes);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001945 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001946 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001947 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
1948 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001949 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001950 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001951 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001952 "product=0x%04x, version=0x%04x\n",
1953 device->identifier.bus, device->identifier.vendor,
1954 device->identifier.product, device->identifier.version);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001955 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001956 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001957 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001958 device->keyMap.keyCharacterMapFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001959 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001960 device->configurationFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001961 dump += StringPrintf(INDENT3 "HaveKeyboardLayoutOverlay: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001962 toString(device->overlayKeyMap != nullptr));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001963 dump += INDENT3 "VideoDevice: ";
1964 if (device->videoDevice) {
1965 dump += device->videoDevice->dump() + "\n";
1966 } else {
1967 dump += "<none>\n";
1968 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001969 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001970
1971 dump += INDENT "Unattached video devices:\n";
1972 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
1973 dump += INDENT2 + videoDevice->dump() + "\n";
1974 }
1975 if (mUnattachedVideoDevices.empty()) {
1976 dump += INDENT2 "<none>\n";
1977 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001978 } // release lock
1979}
1980
1981void EventHub::monitor() {
1982 // Acquire and release the lock to ensure that the event hub has not deadlocked.
1983 mLock.lock();
1984 mLock.unlock();
1985}
1986
Michael Wrightd02c5b62014-02-10 15:10:22 -08001987}; // namespace android