blob: 6e9394317f8953c6bf01aa4696f9b5827f0d3147 [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
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>
Dan Albert677d87e2014-06-16 17:31:28 -070042#include <openssl/sha.h>
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070043#include <utils/Errors.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080044#include <utils/Log.h>
45#include <utils/Timers.h>
46#include <utils/threads.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080047
Michael Wrightd02c5b62014-02-10 15:10:22 -080048#include <input/KeyCharacterMap.h>
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070049#include <input/KeyLayoutMap.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080050#include <input/VirtualKeyMap.h>
51
Michael Wrightd02c5b62014-02-10 15:10:22 -080052/* this macro is used to tell if "bit" is set in "array"
53 * it selects a byte from the array, and does a boolean AND
54 * operation with a byte that only has the relevant bit set.
55 * eg. to check for the 12th bit, we do (array[1] & 1<<4)
56 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070057#define test_bit(bit, array) ((array)[(bit) / 8] & (1 << ((bit) % 8)))
Michael Wrightd02c5b62014-02-10 15:10:22 -080058
59/* this macro computes the number of bytes needed to represent a bit array of the specified size */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070060#define sizeof_bit_array(bits) (((bits) + 7) / 8)
Michael Wrightd02c5b62014-02-10 15:10:22 -080061
62#define INDENT " "
63#define INDENT2 " "
64#define INDENT3 " "
65
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080066using android::base::StringPrintf;
67
Michael Wrightd02c5b62014-02-10 15:10:22 -080068namespace android {
69
Siarhei Vishniakou25920312018-12-12 15:24:44 -080070static constexpr bool DEBUG = false;
71
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070072static const char* DEVICE_PATH = "/dev/input";
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080073// v4l2 devices go directly into /dev
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070074static const char* VIDEO_DEVICE_PATH = "/dev";
Michael Wrightd02c5b62014-02-10 15:10:22 -080075
Michael Wrightd02c5b62014-02-10 15:10:22 -080076static inline const char* toString(bool value) {
77 return value ? "true" : "false";
78}
79
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010080static std::string sha1(const std::string& in) {
Dan Albert677d87e2014-06-16 17:31:28 -070081 SHA_CTX ctx;
82 SHA1_Init(&ctx);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010083 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
Dan Albert677d87e2014-06-16 17:31:28 -070084 u_char digest[SHA_DIGEST_LENGTH];
85 SHA1_Final(digest, &ctx);
Michael Wrightd02c5b62014-02-10 15:10:22 -080086
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010087 std::string out;
Dan Albert677d87e2014-06-16 17:31:28 -070088 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010089 out += StringPrintf("%02x", digest[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -080090 }
91 return out;
92}
93
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080094/**
95 * Return true if name matches "v4l-touch*"
96 */
97static bool isV4lTouchNode(const char* name) {
98 return strstr(name, "v4l-touch") == name;
99}
100
Philip Quinn39b81682019-01-09 22:20:39 -0800101/**
102 * Returns true if V4L devices should be scanned.
103 *
104 * The system property ro.input.video_enabled can be used to control whether
105 * EventHub scans and opens V4L devices. As V4L does not support multiple
106 * clients, EventHub effectively blocks access to these devices when it opens
Siarhei Vishniakou29f88492019-04-05 14:11:43 -0700107 * them.
108 *
109 * Setting this to "false" would prevent any video devices from being discovered and
110 * associated with input devices.
111 *
112 * This property can be used as follows:
113 * 1. To turn off features that are dependent on video device presence.
114 * 2. During testing and development, to allow other clients to read video devices
115 * directly from /dev.
Philip Quinn39b81682019-01-09 22:20:39 -0800116 */
117static bool isV4lScanningEnabled() {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700118 return property_get_bool("ro.input.video_enabled", true /* default_value */);
Philip Quinn39b81682019-01-09 22:20:39 -0800119}
120
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800121static nsecs_t processEventTimestamp(const struct input_event& event) {
122 // Use the time specified in the event instead of the current time
123 // so that downstream code can get more accurate estimates of
124 // event dispatch latency from the time the event is enqueued onto
125 // the evdev client buffer.
126 //
127 // The event's timestamp fortuitously uses the same monotonic clock
128 // time base as the rest of Android. The kernel event device driver
129 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
130 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
131 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
132 // system call that also queries ktime_get_ts().
133
134 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.time.tv_sec) +
135 microseconds_to_nanoseconds(event.time.tv_usec);
136 return inputEventTime;
137}
138
Michael Wrightd02c5b62014-02-10 15:10:22 -0800139// --- Global Functions ---
140
141uint32_t getAbsAxisUsage(int32_t axis, uint32_t deviceClasses) {
142 // Touch devices get dibs on touch-related axes.
143 if (deviceClasses & INPUT_DEVICE_CLASS_TOUCH) {
144 switch (axis) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700145 case ABS_X:
146 case ABS_Y:
147 case ABS_PRESSURE:
148 case ABS_TOOL_WIDTH:
149 case ABS_DISTANCE:
150 case ABS_TILT_X:
151 case ABS_TILT_Y:
152 case ABS_MT_SLOT:
153 case ABS_MT_TOUCH_MAJOR:
154 case ABS_MT_TOUCH_MINOR:
155 case ABS_MT_WIDTH_MAJOR:
156 case ABS_MT_WIDTH_MINOR:
157 case ABS_MT_ORIENTATION:
158 case ABS_MT_POSITION_X:
159 case ABS_MT_POSITION_Y:
160 case ABS_MT_TOOL_TYPE:
161 case ABS_MT_BLOB_ID:
162 case ABS_MT_TRACKING_ID:
163 case ABS_MT_PRESSURE:
164 case ABS_MT_DISTANCE:
165 return INPUT_DEVICE_CLASS_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800166 }
167 }
168
Michael Wright842500e2015-03-13 17:32:02 -0700169 // External stylus gets the pressure axis
170 if (deviceClasses & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
171 if (axis == ABS_PRESSURE) {
172 return INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
173 }
174 }
175
Michael Wrightd02c5b62014-02-10 15:10:22 -0800176 // Joystick devices get the rest.
177 return deviceClasses & INPUT_DEVICE_CLASS_JOYSTICK;
178}
179
180// --- EventHub::Device ---
181
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100182EventHub::Device::Device(int fd, int32_t id, const std::string& path,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700183 const InputDeviceIdentifier& identifier)
184 : next(nullptr),
185 fd(fd),
186 id(id),
187 path(path),
188 identifier(identifier),
189 classes(0),
190 configuration(nullptr),
191 virtualKeyMap(nullptr),
192 ffEffectPlaying(false),
193 ffEffectId(-1),
194 controllerNumber(0),
195 enabled(true),
196 isVirtual(fd < 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800197 memset(keyBitmask, 0, sizeof(keyBitmask));
198 memset(absBitmask, 0, sizeof(absBitmask));
199 memset(relBitmask, 0, sizeof(relBitmask));
200 memset(swBitmask, 0, sizeof(swBitmask));
201 memset(ledBitmask, 0, sizeof(ledBitmask));
202 memset(ffBitmask, 0, sizeof(ffBitmask));
203 memset(propBitmask, 0, sizeof(propBitmask));
204}
205
206EventHub::Device::~Device() {
207 close();
208 delete configuration;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800209}
210
211void EventHub::Device::close() {
212 if (fd >= 0) {
213 ::close(fd);
214 fd = -1;
215 }
216}
217
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700218status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100219 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700220 if (fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100221 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700222 return -errno;
223 }
224 enabled = true;
225 return OK;
226}
227
228status_t EventHub::Device::disable() {
229 close();
230 enabled = false;
231 return OK;
232}
233
234bool EventHub::Device::hasValidFd() {
235 return !isVirtual && enabled;
236}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800237
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100238/**
239 * Get the capabilities for the current process.
240 * Crashes the system if unable to create / check / destroy the capabilities object.
241 */
242class Capabilities final {
243public:
244 explicit Capabilities() {
245 mCaps = cap_get_proc();
246 LOG_ALWAYS_FATAL_IF(mCaps == nullptr, "Could not get capabilities of the current process");
247 }
248
249 /**
250 * Check whether the current process has a specific capability
251 * in the set of effective capabilities.
252 * Return CAP_SET if the process has the requested capability
253 * Return CAP_CLEAR otherwise.
254 */
255 cap_flag_value_t checkEffectiveCapability(cap_value_t capability) {
256 cap_flag_value_t value;
257 const int result = cap_get_flag(mCaps, capability, CAP_EFFECTIVE, &value);
258 LOG_ALWAYS_FATAL_IF(result == -1, "Could not obtain the requested capability");
259 return value;
260 }
261
262 ~Capabilities() {
263 const int result = cap_free(mCaps);
264 LOG_ALWAYS_FATAL_IF(result == -1, "Could not release the capabilities structure");
265 }
266
267private:
268 cap_t mCaps;
269};
270
271static void ensureProcessCanBlockSuspend() {
272 Capabilities capabilities;
273 const bool canBlockSuspend =
274 capabilities.checkEffectiveCapability(CAP_BLOCK_SUSPEND) == CAP_SET;
275 LOG_ALWAYS_FATAL_IF(!canBlockSuspend,
276 "Input must be able to block suspend to properly process events");
277}
278
Michael Wrightd02c5b62014-02-10 15:10:22 -0800279// --- EventHub ---
280
Michael Wrightd02c5b62014-02-10 15:10:22 -0800281const int EventHub::EPOLL_MAX_EVENTS;
282
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700283EventHub::EventHub(void)
284 : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
285 mNextDeviceId(1),
286 mControllerNumbers(),
287 mOpeningDevices(nullptr),
288 mClosingDevices(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800289 mNeedToSendFinishedDeviceScan(false),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700290 mNeedToReopenDevices(false),
291 mNeedToScanDevices(true),
292 mPendingEventCount(0),
293 mPendingEventIndex(0),
294 mPendingINotify(false) {
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100295 ensureProcessCanBlockSuspend();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800296
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800297 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800298 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800299
300 mINotifyFd = inotify_init();
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800301 mInputWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700302 LOG_ALWAYS_FATAL_IF(mInputWd < 0, "Could not register INotify for %s: %s", DEVICE_PATH,
303 strerror(errno));
Philip Quinn39b81682019-01-09 22:20:39 -0800304 if (isV4lScanningEnabled()) {
305 mVideoWd = inotify_add_watch(mINotifyFd, VIDEO_DEVICE_PATH, IN_DELETE | IN_CREATE);
306 LOG_ALWAYS_FATAL_IF(mVideoWd < 0, "Could not register INotify for %s: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700307 VIDEO_DEVICE_PATH, strerror(errno));
Philip Quinn39b81682019-01-09 22:20:39 -0800308 } else {
309 mVideoWd = -1;
310 ALOGI("Video device scanning disabled");
311 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800312
Siarhei Vishniakou2d0e9482019-09-24 12:52:47 +0100313 struct epoll_event eventItem = {};
314 eventItem.events = EPOLLIN | EPOLLWAKEUP;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700315 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800316 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800317 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
318
319 int wakeFds[2];
320 result = pipe(wakeFds);
321 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
322
323 mWakeReadPipeFd = wakeFds[0];
324 mWakeWritePipeFd = wakeFds[1];
325
326 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
327 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700328 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800329
330 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
331 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700332 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800333
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700334 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800335 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
336 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700337 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800338}
339
340EventHub::~EventHub(void) {
341 closeAllDevicesLocked();
342
343 while (mClosingDevices) {
344 Device* device = mClosingDevices;
345 mClosingDevices = device->next;
346 delete device;
347 }
348
349 ::close(mEpollFd);
350 ::close(mINotifyFd);
351 ::close(mWakeReadPipeFd);
352 ::close(mWakeWritePipeFd);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800353}
354
355InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
356 AutoMutex _l(mLock);
357 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700358 if (device == nullptr) return InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800359 return device->identifier;
360}
361
362uint32_t EventHub::getDeviceClasses(int32_t deviceId) const {
363 AutoMutex _l(mLock);
364 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700365 if (device == nullptr) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800366 return device->classes;
367}
368
369int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
370 AutoMutex _l(mLock);
371 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700372 if (device == nullptr) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800373 return device->controllerNumber;
374}
375
376void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
377 AutoMutex _l(mLock);
378 Device* device = getDeviceLocked(deviceId);
379 if (device && device->configuration) {
380 *outConfiguration = *device->configuration;
381 } else {
382 outConfiguration->clear();
383 }
384}
385
386status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700387 RawAbsoluteAxisInfo* outAxisInfo) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800388 outAxisInfo->clear();
389
390 if (axis >= 0 && axis <= ABS_MAX) {
391 AutoMutex _l(mLock);
392
393 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700394 if (device && device->hasValidFd() && test_bit(axis, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800395 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700396 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
397 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
398 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800399 return -errno;
400 }
401
402 if (info.minimum != info.maximum) {
403 outAxisInfo->valid = true;
404 outAxisInfo->minValue = info.minimum;
405 outAxisInfo->maxValue = info.maximum;
406 outAxisInfo->flat = info.flat;
407 outAxisInfo->fuzz = info.fuzz;
408 outAxisInfo->resolution = info.resolution;
409 }
410 return OK;
411 }
412 }
413 return -1;
414}
415
416bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
417 if (axis >= 0 && axis <= REL_MAX) {
418 AutoMutex _l(mLock);
419
420 Device* device = getDeviceLocked(deviceId);
421 if (device) {
422 return test_bit(axis, device->relBitmask);
423 }
424 }
425 return false;
426}
427
428bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
429 if (property >= 0 && property <= INPUT_PROP_MAX) {
430 AutoMutex _l(mLock);
431
432 Device* device = getDeviceLocked(deviceId);
433 if (device) {
434 return test_bit(property, device->propBitmask);
435 }
436 }
437 return false;
438}
439
440int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
441 if (scanCode >= 0 && scanCode <= KEY_MAX) {
442 AutoMutex _l(mLock);
443
444 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700445 if (device && device->hasValidFd() && test_bit(scanCode, device->keyBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800446 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
447 memset(keyState, 0, sizeof(keyState));
448 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
449 return test_bit(scanCode, keyState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
450 }
451 }
452 }
453 return AKEY_STATE_UNKNOWN;
454}
455
456int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
457 AutoMutex _l(mLock);
458
459 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700460 if (device && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800461 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800462 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode, &scanCodes);
463 if (scanCodes.size() != 0) {
464 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
465 memset(keyState, 0, sizeof(keyState));
466 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
467 for (size_t i = 0; i < scanCodes.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800468 int32_t sc = scanCodes[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -0800469 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, keyState)) {
470 return AKEY_STATE_DOWN;
471 }
472 }
473 return AKEY_STATE_UP;
474 }
475 }
476 }
477 return AKEY_STATE_UNKNOWN;
478}
479
480int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
481 if (sw >= 0 && sw <= SW_MAX) {
482 AutoMutex _l(mLock);
483
484 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700485 if (device && device->hasValidFd() && test_bit(sw, device->swBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800486 uint8_t swState[sizeof_bit_array(SW_MAX + 1)];
487 memset(swState, 0, sizeof(swState));
488 if (ioctl(device->fd, EVIOCGSW(sizeof(swState)), swState) >= 0) {
489 return test_bit(sw, swState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
490 }
491 }
492 }
493 return AKEY_STATE_UNKNOWN;
494}
495
496status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
497 *outValue = 0;
498
499 if (axis >= 0 && axis <= ABS_MAX) {
500 AutoMutex _l(mLock);
501
502 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700503 if (device && device->hasValidFd() && test_bit(axis, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800504 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700505 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
506 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
507 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800508 return -errno;
509 }
510
511 *outValue = info.value;
512 return OK;
513 }
514 }
515 return -1;
516}
517
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700518bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes, const int32_t* keyCodes,
519 uint8_t* outFlags) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800520 AutoMutex _l(mLock);
521
522 Device* device = getDeviceLocked(deviceId);
523 if (device && device->keyMap.haveKeyLayout()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800524 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800525 for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) {
526 scanCodes.clear();
527
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700528 status_t err = device->keyMap.keyLayoutMap->findScanCodesForKey(keyCodes[codeIndex],
529 &scanCodes);
530 if (!err) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800531 // check the possible scan codes identified by the layout map against the
532 // map of codes actually emitted by the driver
533 for (size_t sc = 0; sc < scanCodes.size(); sc++) {
534 if (test_bit(scanCodes[sc], device->keyBitmask)) {
535 outFlags[codeIndex] = 1;
536 break;
537 }
538 }
539 }
540 }
541 return true;
542 }
543 return false;
544}
545
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700546status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
547 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800548 AutoMutex _l(mLock);
549 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700550 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800551
552 if (device) {
553 // Check the key character map first.
554 sp<KeyCharacterMap> kcm = device->getKeyCharacterMap();
Yi Kong9b14ac62018-07-17 13:48:38 -0700555 if (kcm != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800556 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
557 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700558 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800559 }
560 }
561
562 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700563 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800564 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700565 status = NO_ERROR;
566 }
567 }
568
569 if (status == NO_ERROR) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700570 if (kcm != nullptr) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700571 kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState);
572 } else {
573 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800574 }
575 }
576 }
577
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700578 if (status != NO_ERROR) {
579 *outKeycode = 0;
580 *outFlags = 0;
581 *outMetaState = metaState;
582 }
583
584 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800585}
586
587status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
588 AutoMutex _l(mLock);
589 Device* device = getDeviceLocked(deviceId);
590
591 if (device && device->keyMap.haveKeyLayout()) {
592 status_t err = device->keyMap.keyLayoutMap->mapAxis(scanCode, outAxisInfo);
593 if (err == NO_ERROR) {
594 return NO_ERROR;
595 }
596 }
597
598 return NAME_NOT_FOUND;
599}
600
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100601void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800602 AutoMutex _l(mLock);
603
604 mExcludedDevices = devices;
605}
606
607bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
608 AutoMutex _l(mLock);
609 Device* device = getDeviceLocked(deviceId);
610 if (device && scanCode >= 0 && scanCode <= KEY_MAX) {
611 if (test_bit(scanCode, device->keyBitmask)) {
612 return true;
613 }
614 }
615 return false;
616}
617
618bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
619 AutoMutex _l(mLock);
620 Device* device = getDeviceLocked(deviceId);
621 int32_t sc;
622 if (device && mapLed(device, led, &sc) == NO_ERROR) {
623 if (test_bit(sc, device->ledBitmask)) {
624 return true;
625 }
626 }
627 return false;
628}
629
630void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
631 AutoMutex _l(mLock);
632 Device* device = getDeviceLocked(deviceId);
633 setLedStateLocked(device, led, on);
634}
635
636void EventHub::setLedStateLocked(Device* device, int32_t led, bool on) {
637 int32_t sc;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700638 if (device && device->hasValidFd() && mapLed(device, led, &sc) != NAME_NOT_FOUND) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800639 struct input_event ev;
640 ev.time.tv_sec = 0;
641 ev.time.tv_usec = 0;
642 ev.type = EV_LED;
643 ev.code = sc;
644 ev.value = on ? 1 : 0;
645
646 ssize_t nWrite;
647 do {
648 nWrite = write(device->fd, &ev, sizeof(struct input_event));
649 } while (nWrite == -1 && errno == EINTR);
650 }
651}
652
653void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700654 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800655 outVirtualKeys.clear();
656
657 AutoMutex _l(mLock);
658 Device* device = getDeviceLocked(deviceId);
659 if (device && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800660 const std::vector<VirtualKeyDefinition> virtualKeys =
661 device->virtualKeyMap->getVirtualKeys();
662 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800663 }
664}
665
666sp<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
667 AutoMutex _l(mLock);
668 Device* device = getDeviceLocked(deviceId);
669 if (device) {
670 return device->getKeyCharacterMap();
671 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700672 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800673}
674
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700675bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, const sp<KeyCharacterMap>& map) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800676 AutoMutex _l(mLock);
677 Device* device = getDeviceLocked(deviceId);
678 if (device) {
679 if (map != device->overlayKeyMap) {
680 device->overlayKeyMap = map;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700681 device->combinedKeyMap = KeyCharacterMap::combine(device->keyMap.keyCharacterMap, map);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800682 return true;
683 }
684 }
685 return false;
686}
687
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100688static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
689 std::string rawDescriptor;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700690 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800691 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100692 if (!identifier.uniqueId.empty()) {
693 rawDescriptor += "uniqueId:";
694 rawDescriptor += identifier.uniqueId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800695 } else if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100696 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800697 }
698
699 if (identifier.vendor == 0 && identifier.product == 0) {
700 // If we don't know the vendor and product id, then the device is probably
701 // built-in so we need to rely on other information to uniquely identify
702 // the input device. Usually we try to avoid relying on the device name or
703 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100704 if (!identifier.name.empty()) {
705 rawDescriptor += "name:";
706 rawDescriptor += identifier.name;
707 } else if (!identifier.location.empty()) {
708 rawDescriptor += "location:";
709 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800710 }
711 }
712 identifier.descriptor = sha1(rawDescriptor);
713 return rawDescriptor;
714}
715
716void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
717 // Compute a device descriptor that uniquely identifies the device.
718 // The descriptor is assumed to be a stable identifier. Its value should not
719 // change between reboots, reconnections, firmware updates or new releases
720 // of Android. In practice we sometimes get devices that cannot be uniquely
721 // identified. In this case we enforce uniqueness between connected devices.
722 // Ideally, we also want the descriptor to be short and relatively opaque.
723
724 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100725 std::string rawDescriptor = generateDescriptor(identifier);
726 if (identifier.uniqueId.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800727 // If it didn't have a unique id check for conflicts and enforce
728 // uniqueness if necessary.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700729 while (getDeviceByDescriptorLocked(identifier.descriptor) != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800730 identifier.nonce++;
731 rawDescriptor = generateDescriptor(identifier);
732 }
733 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100734 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700735 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800736}
737
738void EventHub::vibrate(int32_t deviceId, nsecs_t duration) {
739 AutoMutex _l(mLock);
740 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700741 if (device && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800742 ff_effect effect;
743 memset(&effect, 0, sizeof(effect));
744 effect.type = FF_RUMBLE;
745 effect.id = device->ffEffectId;
746 effect.u.rumble.strong_magnitude = 0xc000;
747 effect.u.rumble.weak_magnitude = 0xc000;
748 effect.replay.length = (duration + 999999LL) / 1000000LL;
749 effect.replay.delay = 0;
750 if (ioctl(device->fd, EVIOCSFF, &effect)) {
751 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700752 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800753 return;
754 }
755 device->ffEffectId = effect.id;
756
757 struct input_event ev;
758 ev.time.tv_sec = 0;
759 ev.time.tv_usec = 0;
760 ev.type = EV_FF;
761 ev.code = device->ffEffectId;
762 ev.value = 1;
763 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
764 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700765 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800766 return;
767 }
768 device->ffEffectPlaying = true;
769 }
770}
771
772void EventHub::cancelVibrate(int32_t deviceId) {
773 AutoMutex _l(mLock);
774 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700775 if (device && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800776 if (device->ffEffectPlaying) {
777 device->ffEffectPlaying = false;
778
779 struct input_event ev;
780 ev.time.tv_sec = 0;
781 ev.time.tv_usec = 0;
782 ev.type = EV_FF;
783 ev.code = device->ffEffectId;
784 ev.value = 0;
785 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
786 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700787 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788 return;
789 }
790 }
791 }
792}
793
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100794EventHub::Device* EventHub::getDeviceByDescriptorLocked(const std::string& descriptor) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800795 size_t size = mDevices.size();
796 for (size_t i = 0; i < size; i++) {
797 Device* device = mDevices.valueAt(i);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100798 if (descriptor == device->identifier.descriptor) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800799 return device;
800 }
801 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700802 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800803}
804
805EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -0800806 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800807 deviceId = mBuiltInKeyboardId;
808 }
809 ssize_t index = mDevices.indexOfKey(deviceId);
810 return index >= 0 ? mDevices.valueAt(index) : NULL;
811}
812
813EventHub::Device* EventHub::getDeviceByPathLocked(const char* devicePath) const {
814 for (size_t i = 0; i < mDevices.size(); i++) {
815 Device* device = mDevices.valueAt(i);
816 if (device->path == devicePath) {
817 return device;
818 }
819 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700820 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800821}
822
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700823/**
824 * The file descriptor could be either input device, or a video device (associated with a
825 * specific input device). Check both cases here, and return the device that this event
826 * belongs to. Caller can compare the fd's once more to determine event type.
827 * Looks through all input devices, and only attached video devices. Unattached video
828 * devices are ignored.
829 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700830EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
831 for (size_t i = 0; i < mDevices.size(); i++) {
832 Device* device = mDevices.valueAt(i);
833 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700834 // This is an input device event
835 return device;
836 }
837 if (device->videoDevice && device->videoDevice->getFd() == fd) {
838 // This is a video device event
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700839 return device;
840 }
841 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700842 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
843 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700844 return nullptr;
845}
846
Michael Wrightd02c5b62014-02-10 15:10:22 -0800847size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
848 ALOG_ASSERT(bufferSize >= 1);
849
850 AutoMutex _l(mLock);
851
852 struct input_event readBuffer[bufferSize];
853
854 RawEvent* event = buffer;
855 size_t capacity = bufferSize;
856 bool awoken = false;
857 for (;;) {
858 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
859
860 // Reopen input devices if needed.
861 if (mNeedToReopenDevices) {
862 mNeedToReopenDevices = false;
863
864 ALOGI("Reopening all input devices due to a configuration change.");
865
866 closeAllDevicesLocked();
867 mNeedToScanDevices = true;
868 break; // return to the caller before we actually rescan
869 }
870
871 // Report any devices that had last been added/removed.
872 while (mClosingDevices) {
873 Device* device = mClosingDevices;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700874 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800875 mClosingDevices = device->next;
876 event->when = now;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700877 event->deviceId = (device->id == mBuiltInKeyboardId)
878 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
879 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800880 event->type = DEVICE_REMOVED;
881 event += 1;
882 delete device;
883 mNeedToSendFinishedDeviceScan = true;
884 if (--capacity == 0) {
885 break;
886 }
887 }
888
889 if (mNeedToScanDevices) {
890 mNeedToScanDevices = false;
891 scanDevicesLocked();
892 mNeedToSendFinishedDeviceScan = true;
893 }
894
Yi Kong9b14ac62018-07-17 13:48:38 -0700895 while (mOpeningDevices != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800896 Device* device = mOpeningDevices;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700897 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800898 mOpeningDevices = device->next;
899 event->when = now;
900 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
901 event->type = DEVICE_ADDED;
902 event += 1;
903 mNeedToSendFinishedDeviceScan = true;
904 if (--capacity == 0) {
905 break;
906 }
907 }
908
909 if (mNeedToSendFinishedDeviceScan) {
910 mNeedToSendFinishedDeviceScan = false;
911 event->when = now;
912 event->type = FINISHED_DEVICE_SCAN;
913 event += 1;
914 if (--capacity == 0) {
915 break;
916 }
917 }
918
919 // Grab the next input event.
920 bool deviceChanged = false;
921 while (mPendingEventIndex < mPendingEventCount) {
922 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700923 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800924 if (eventItem.events & EPOLLIN) {
925 mPendingINotify = true;
926 } else {
927 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
928 }
929 continue;
930 }
931
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700932 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800933 if (eventItem.events & EPOLLIN) {
934 ALOGV("awoken after wake()");
935 awoken = true;
936 char buffer[16];
937 ssize_t nRead;
938 do {
939 nRead = read(mWakeReadPipeFd, buffer, sizeof(buffer));
940 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(buffer));
941 } else {
942 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700943 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800944 }
945 continue;
946 }
947
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700948 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700949 if (!device) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700950 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
951 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700952 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800953 continue;
954 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700955 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
956 if (eventItem.events & EPOLLIN) {
957 size_t numFrames = device->videoDevice->readAndQueueFrames();
958 if (numFrames == 0) {
959 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700960 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700961 }
962 } else if (eventItem.events & EPOLLHUP) {
963 // TODO(b/121395353) - consider adding EPOLLRDHUP
964 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700965 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700966 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
967 device->videoDevice = nullptr;
968 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700969 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
970 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700971 ALOG_ASSERT(!DEBUG);
972 }
973 continue;
974 }
975 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -0800976 if (eventItem.events & EPOLLIN) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700977 int32_t readSize =
978 read(device->fd, readBuffer, sizeof(struct input_event) * capacity);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800979 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
980 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -0700981 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700982 " bufferSize: %zu capacity: %zu errno: %d)\n",
983 device->fd, readSize, bufferSize, capacity, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800984 deviceChanged = true;
985 closeDeviceLocked(device);
986 } else if (readSize < 0) {
987 if (errno != EAGAIN && errno != EINTR) {
988 ALOGW("could not get event (errno=%d)", errno);
989 }
990 } else if ((readSize % sizeof(struct input_event)) != 0) {
991 ALOGE("could not get event (wrong size: %d)", readSize);
992 } else {
993 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
994
995 size_t count = size_t(readSize) / sizeof(struct input_event);
996 for (size_t i = 0; i < count; i++) {
997 struct input_event& iev = readBuffer[i];
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800998 event->when = processEventTimestamp(iev);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800999 event->deviceId = deviceId;
1000 event->type = iev.type;
1001 event->code = iev.code;
1002 event->value = iev.value;
1003 event += 1;
1004 capacity -= 1;
1005 }
1006 if (capacity == 0) {
1007 // The result buffer is full. Reset the pending event index
1008 // so we will try to read the device again on the next iteration.
1009 mPendingEventIndex -= 1;
1010 break;
1011 }
1012 }
1013 } else if (eventItem.events & EPOLLHUP) {
1014 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001015 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001016 deviceChanged = true;
1017 closeDeviceLocked(device);
1018 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001019 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1020 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001021 }
1022 }
1023
1024 // readNotify() will modify the list of devices so this must be done after
1025 // processing all other events to ensure that we read all remaining events
1026 // before closing the devices.
1027 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
1028 mPendingINotify = false;
1029 readNotifyLocked();
1030 deviceChanged = true;
1031 }
1032
1033 // Report added or removed devices immediately.
1034 if (deviceChanged) {
1035 continue;
1036 }
1037
1038 // Return now if we have collected any events or if we were explicitly awoken.
1039 if (event != buffer || awoken) {
1040 break;
1041 }
1042
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001043 // Poll for events.
1044 // When a device driver has pending (unread) events, it acquires
1045 // a kernel wake lock. Once the last pending event has been read, the device
1046 // driver will release the kernel wake lock, but the epoll will hold the wakelock,
1047 // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
1048 // is called again for the same fd that produced the event.
1049 // Thus the system can only sleep if there are no events pending or
1050 // currently being processed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001051 //
1052 // The timeout is advisory only. If the device is asleep, it will not wake just to
1053 // service the timeout.
1054 mPendingEventIndex = 0;
1055
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001056 mLock.unlock(); // release lock before poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001057
1058 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1059
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001060 mLock.lock(); // reacquire lock after poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001061
1062 if (pollResult == 0) {
1063 // Timed out.
1064 mPendingEventCount = 0;
1065 break;
1066 }
1067
1068 if (pollResult < 0) {
1069 // An error occurred.
1070 mPendingEventCount = 0;
1071
1072 // Sleep after errors to avoid locking up the system.
1073 // Hopefully the error is transient.
1074 if (errno != EINTR) {
1075 ALOGW("poll failed (errno=%d)\n", errno);
1076 usleep(100000);
1077 }
1078 } else {
1079 // Some events occurred.
1080 mPendingEventCount = size_t(pollResult);
1081 }
1082 }
1083
1084 // All done, return the number of events we read.
1085 return event - buffer;
1086}
1087
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001088std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
1089 AutoMutex _l(mLock);
1090
1091 Device* device = getDeviceLocked(deviceId);
1092 if (!device || !device->videoDevice) {
1093 return {};
1094 }
1095 return device->videoDevice->consumeFrames();
1096}
1097
Michael Wrightd02c5b62014-02-10 15:10:22 -08001098void EventHub::wake() {
1099 ALOGV("wake() called");
1100
1101 ssize_t nWrite;
1102 do {
1103 nWrite = write(mWakeWritePipeFd, "W", 1);
1104 } while (nWrite == -1 && errno == EINTR);
1105
1106 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001107 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001108 }
1109}
1110
1111void EventHub::scanDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001112 status_t result = scanDirLocked(DEVICE_PATH);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001113 if (result < 0) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001114 ALOGE("scan dir failed for %s", DEVICE_PATH);
1115 }
Philip Quinn39b81682019-01-09 22:20:39 -08001116 if (isV4lScanningEnabled()) {
1117 result = scanVideoDirLocked(VIDEO_DEVICE_PATH);
1118 if (result != OK) {
1119 ALOGE("scan video dir failed for %s", VIDEO_DEVICE_PATH);
1120 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001121 }
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001122 if (mDevices.indexOfKey(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) < 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001123 createVirtualKeyboardLocked();
1124 }
1125}
1126
1127// ----------------------------------------------------------------------------
1128
1129static bool containsNonZeroByte(const uint8_t* array, uint32_t startIndex, uint32_t endIndex) {
1130 const uint8_t* end = array + endIndex;
1131 array += startIndex;
1132 while (array != end) {
1133 if (*(array++) != 0) {
1134 return true;
1135 }
1136 }
1137 return false;
1138}
1139
1140static const int32_t GAMEPAD_KEYCODES[] = {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001141 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C, //
1142 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z, //
1143 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1, //
1144 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2, //
1145 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR, //
1146 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE, //
Michael Wrightd02c5b62014-02-10 15:10:22 -08001147};
1148
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001149status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001150 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001151 struct epoll_event eventItem = {};
1152 eventItem.events = EPOLLIN | EPOLLWAKEUP;
1153 eventItem.data.fd = fd;
1154 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1155 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001156 return -errno;
1157 }
1158 return OK;
1159}
1160
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001161status_t EventHub::unregisterFdFromEpoll(int fd) {
1162 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
1163 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
1164 return -errno;
1165 }
1166 return OK;
1167}
1168
1169status_t EventHub::registerDeviceForEpollLocked(Device* device) {
1170 if (device == nullptr) {
1171 if (DEBUG) {
1172 LOG_ALWAYS_FATAL("Cannot call registerDeviceForEpollLocked with null Device");
1173 }
1174 return BAD_VALUE;
1175 }
1176 status_t result = registerFdForEpoll(device->fd);
1177 if (result != OK) {
1178 ALOGE("Could not add input device fd to epoll for device %" PRId32, device->id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001179 return result;
1180 }
1181 if (device->videoDevice) {
1182 registerVideoDeviceForEpollLocked(*device->videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001183 }
1184 return result;
1185}
1186
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001187void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
1188 status_t result = registerFdForEpoll(videoDevice.getFd());
1189 if (result != OK) {
1190 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
1191 }
1192}
1193
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001194status_t EventHub::unregisterDeviceFromEpollLocked(Device* device) {
1195 if (device->hasValidFd()) {
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001196 status_t result = unregisterFdFromEpoll(device->fd);
1197 if (result != OK) {
1198 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device->id);
1199 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001200 }
1201 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001202 if (device->videoDevice) {
1203 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1204 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001205 return OK;
1206}
1207
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001208void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
1209 if (videoDevice.hasValidFd()) {
1210 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
1211 if (result != OK) {
1212 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001213 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001214 }
1215 }
1216}
1217
1218status_t EventHub::openDeviceLocked(const char* devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001219 char buffer[80];
1220
1221 ALOGV("Opening device: %s", devicePath);
1222
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001223 int fd = open(devicePath, O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001224 if (fd < 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001225 ALOGE("could not open %s, %s\n", devicePath, strerror(errno));
1226 return -1;
1227 }
1228
1229 InputDeviceIdentifier identifier;
1230
1231 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001232 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001233 ALOGE("Could not get device name for %s: %s", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001234 } else {
1235 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001236 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237 }
1238
1239 // Check to see if the device is on our excluded list
1240 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001241 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001242 if (identifier.name == item) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001243 ALOGI("ignoring event id %s driver %s\n", devicePath, item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001244 close(fd);
1245 return -1;
1246 }
1247 }
1248
1249 // Get device driver version.
1250 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001251 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001252 ALOGE("could not get driver version for %s, %s\n", devicePath, strerror(errno));
1253 close(fd);
1254 return -1;
1255 }
1256
1257 // Get device identifier.
1258 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001259 if (ioctl(fd, EVIOCGID, &inputId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001260 ALOGE("could not get device input id for %s, %s\n", devicePath, strerror(errno));
1261 close(fd);
1262 return -1;
1263 }
1264 identifier.bus = inputId.bustype;
1265 identifier.product = inputId.product;
1266 identifier.vendor = inputId.vendor;
1267 identifier.version = inputId.version;
1268
1269 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001270 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
1271 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001272 } else {
1273 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001274 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001275 }
1276
1277 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001278 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
1279 // fprintf(stderr, "could not get idstring 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.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001283 }
1284
1285 // Fill in the descriptor.
1286 assignDescriptorLocked(identifier);
1287
Michael Wrightd02c5b62014-02-10 15:10:22 -08001288 // Allocate device. (The device object takes ownership of the fd at this point.)
1289 int32_t deviceId = mNextDeviceId++;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001290 Device* device = new Device(fd, deviceId, devicePath, identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001291
1292 ALOGV("add device %d: %s\n", deviceId, devicePath);
1293 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001294 " vendor %04x\n"
1295 " product %04x\n"
1296 " version %04x\n",
1297 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001298 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
1299 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
1300 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
1301 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001302 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
1303 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001304
1305 // Load the configuration file for the device.
1306 loadConfigurationLocked(device);
1307
1308 // Figure out the kinds of events the device reports.
1309 ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(device->keyBitmask)), device->keyBitmask);
1310 ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(device->absBitmask)), device->absBitmask);
1311 ioctl(fd, EVIOCGBIT(EV_REL, sizeof(device->relBitmask)), device->relBitmask);
1312 ioctl(fd, EVIOCGBIT(EV_SW, sizeof(device->swBitmask)), device->swBitmask);
1313 ioctl(fd, EVIOCGBIT(EV_LED, sizeof(device->ledBitmask)), device->ledBitmask);
1314 ioctl(fd, EVIOCGBIT(EV_FF, sizeof(device->ffBitmask)), device->ffBitmask);
1315 ioctl(fd, EVIOCGPROP(sizeof(device->propBitmask)), device->propBitmask);
1316
1317 // See if this is a keyboard. Ignore everything in the button range except for
1318 // joystick and gamepad buttons which are handled like keyboards for the most part.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001319 bool haveKeyboardKeys =
1320 containsNonZeroByte(device->keyBitmask, 0, sizeof_bit_array(BTN_MISC)) ||
Siarhei Vishniakoua0d2b802020-05-13 14:00:31 -07001321 containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_WHEEL),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001322 sizeof_bit_array(KEY_MAX + 1));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001323 bool haveGamepadButtons = containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_MISC),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001324 sizeof_bit_array(BTN_MOUSE)) ||
1325 containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_JOYSTICK),
1326 sizeof_bit_array(BTN_DIGI));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001327 if (haveKeyboardKeys || haveGamepadButtons) {
1328 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1329 }
1330
1331 // See if this is a cursor device such as a trackball or mouse.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001332 if (test_bit(BTN_MOUSE, device->keyBitmask) && test_bit(REL_X, device->relBitmask) &&
1333 test_bit(REL_Y, device->relBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001334 device->classes |= INPUT_DEVICE_CLASS_CURSOR;
1335 }
1336
Prashant Malani1941ff52015-08-11 18:29:28 -07001337 // See if this is a rotary encoder type device.
1338 String8 deviceType = String8();
1339 if (device->configuration &&
1340 device->configuration->tryGetProperty(String8("device.type"), deviceType)) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001341 if (!deviceType.compare(String8("rotaryEncoder"))) {
1342 device->classes |= INPUT_DEVICE_CLASS_ROTARY_ENCODER;
1343 }
Prashant Malani1941ff52015-08-11 18:29:28 -07001344 }
1345
Michael Wrightd02c5b62014-02-10 15:10:22 -08001346 // See if this is a touch pad.
1347 // Is this a new modern multi-touch driver?
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001348 if (test_bit(ABS_MT_POSITION_X, device->absBitmask) &&
1349 test_bit(ABS_MT_POSITION_Y, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001350 // Some joysticks such as the PS3 controller report axes that conflict
1351 // with the ABS_MT range. Try to confirm that the device really is
1352 // a touch screen.
1353 if (test_bit(BTN_TOUCH, device->keyBitmask) || !haveGamepadButtons) {
1354 device->classes |= INPUT_DEVICE_CLASS_TOUCH | INPUT_DEVICE_CLASS_TOUCH_MT;
1355 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001356 // Is this an old style single-touch driver?
1357 } else if (test_bit(BTN_TOUCH, device->keyBitmask) && test_bit(ABS_X, device->absBitmask) &&
1358 test_bit(ABS_Y, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001359 device->classes |= INPUT_DEVICE_CLASS_TOUCH;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001360 // Is this a BT stylus?
Michael Wright842500e2015-03-13 17:32:02 -07001361 } else if ((test_bit(ABS_PRESSURE, device->absBitmask) ||
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001362 test_bit(BTN_TOUCH, device->keyBitmask)) &&
1363 !test_bit(ABS_X, device->absBitmask) && !test_bit(ABS_Y, device->absBitmask)) {
Michael Wright842500e2015-03-13 17:32:02 -07001364 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
1365 // Keyboard will try to claim some of the buttons but we really want to reserve those so we
1366 // can fuse it with the touch screen data, so just take them back. Note this means an
1367 // external stylus cannot also be a keyboard device.
1368 device->classes &= ~INPUT_DEVICE_CLASS_KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001369 }
1370
1371 // See if this device is a joystick.
1372 // Assumes that joysticks always have gamepad buttons in order to distinguish them
1373 // from other devices such as accelerometers that also have absolute axes.
1374 if (haveGamepadButtons) {
1375 uint32_t assumedClasses = device->classes | INPUT_DEVICE_CLASS_JOYSTICK;
1376 for (int i = 0; i <= ABS_MAX; i++) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001377 if (test_bit(i, device->absBitmask) &&
1378 (getAbsAxisUsage(i, assumedClasses) & INPUT_DEVICE_CLASS_JOYSTICK)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001379 device->classes = assumedClasses;
1380 break;
1381 }
1382 }
1383 }
1384
1385 // Check whether this device has switches.
1386 for (int i = 0; i <= SW_MAX; i++) {
1387 if (test_bit(i, device->swBitmask)) {
1388 device->classes |= INPUT_DEVICE_CLASS_SWITCH;
1389 break;
1390 }
1391 }
1392
1393 // Check whether this device supports the vibrator.
1394 if (test_bit(FF_RUMBLE, device->ffBitmask)) {
1395 device->classes |= INPUT_DEVICE_CLASS_VIBRATOR;
1396 }
1397
1398 // Configure virtual keys.
1399 if ((device->classes & INPUT_DEVICE_CLASS_TOUCH)) {
1400 // Load the virtual keys for the touch screen, if any.
1401 // We do this now so that we can make sure to load the keymap if necessary.
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001402 bool success = loadVirtualKeyMapLocked(device);
1403 if (success) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001404 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1405 }
1406 }
1407
1408 // Load the key map.
1409 // We need to do this for joysticks too because the key layout may specify axes.
1410 status_t keyMapStatus = NAME_NOT_FOUND;
1411 if (device->classes & (INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_JOYSTICK)) {
1412 // Load the keymap for the device.
1413 keyMapStatus = loadKeyMapLocked(device);
1414 }
1415
1416 // Configure the keyboard, gamepad or virtual keyboard.
1417 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1418 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001419 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
1420 isEligibleBuiltInKeyboard(device->identifier, device->configuration, &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001421 mBuiltInKeyboardId = device->id;
1422 }
1423
1424 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
1425 if (hasKeycodeLocked(device, AKEYCODE_Q)) {
1426 device->classes |= INPUT_DEVICE_CLASS_ALPHAKEY;
1427 }
1428
1429 // See if this device has a DPAD.
1430 if (hasKeycodeLocked(device, AKEYCODE_DPAD_UP) &&
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001431 hasKeycodeLocked(device, AKEYCODE_DPAD_DOWN) &&
1432 hasKeycodeLocked(device, AKEYCODE_DPAD_LEFT) &&
1433 hasKeycodeLocked(device, AKEYCODE_DPAD_RIGHT) &&
1434 hasKeycodeLocked(device, AKEYCODE_DPAD_CENTER)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001435 device->classes |= INPUT_DEVICE_CLASS_DPAD;
1436 }
1437
1438 // See if this device has a gamepad.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001439 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES) / sizeof(GAMEPAD_KEYCODES[0]); i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001440 if (hasKeycodeLocked(device, GAMEPAD_KEYCODES[i])) {
1441 device->classes |= INPUT_DEVICE_CLASS_GAMEPAD;
1442 break;
1443 }
1444 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001445 }
1446
1447 // If the device isn't recognized as something we handle, don't monitor it.
1448 if (device->classes == 0) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001449 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath,
1450 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001451 delete device;
1452 return -1;
1453 }
1454
Tim Kilbourn063ff532015-04-08 10:26:18 -07001455 // Determine whether the device has a mic.
1456 if (deviceHasMicLocked(device)) {
1457 device->classes |= INPUT_DEVICE_CLASS_MIC;
1458 }
1459
Michael Wrightd02c5b62014-02-10 15:10:22 -08001460 // Determine whether the device is external or internal.
1461 if (isExternalDeviceLocked(device)) {
1462 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL;
1463 }
1464
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001465 if (device->classes & (INPUT_DEVICE_CLASS_JOYSTICK | INPUT_DEVICE_CLASS_DPAD) &&
1466 device->classes & INPUT_DEVICE_CLASS_GAMEPAD) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001467 device->controllerNumber = getNextControllerNumberLocked(device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001468 setLedForControllerLocked(device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001469 }
1470
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001471 // Find a matching video device by comparing device names
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001472 // This should be done before registerDeviceForEpollLocked, so that both fds are added to epoll
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001473 for (std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
1474 if (device->identifier.name == videoDevice->getName()) {
1475 device->videoDevice = std::move(videoDevice);
1476 break;
1477 }
1478 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001479 mUnattachedVideoDevices
1480 .erase(std::remove_if(mUnattachedVideoDevices.begin(), mUnattachedVideoDevices.end(),
1481 [](const std::unique_ptr<TouchVideoDevice>& videoDevice) {
1482 return videoDevice == nullptr;
1483 }),
1484 mUnattachedVideoDevices.end());
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001485
1486 if (registerDeviceForEpollLocked(device) != OK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001487 delete device;
1488 return -1;
1489 }
1490
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001491 configureFd(device);
1492
1493 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=0x%x, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001494 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
1495 deviceId, fd, devicePath, device->identifier.name.c_str(), device->classes,
1496 device->configurationFile.c_str(), device->keyMap.keyLayoutFile.c_str(),
1497 device->keyMap.keyCharacterMapFile.c_str(), toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001498
1499 addDeviceLocked(device);
1500 return OK;
1501}
1502
1503void EventHub::configureFd(Device* device) {
1504 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
1505 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1506 // Disable kernel key repeat since we handle it ourselves
1507 unsigned int repeatRate[] = {0, 0};
1508 if (ioctl(device->fd, EVIOCSREP, repeatRate)) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001509 ALOGW("Unable to disable kernel key repeat for %s: %s", device->path.c_str(),
1510 strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001511 }
1512 }
1513
Michael Wrightd02c5b62014-02-10 15:10:22 -08001514 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
1515 // associated with input events. This is important because the input system
1516 // uses the timestamps extensively and assumes they were recorded using the monotonic
1517 // clock.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001518 int clockId = CLOCK_MONOTONIC;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001519 bool usingClockIoctl = !ioctl(device->fd, EVIOCSCLOCKID, &clockId);
Atif Niyaz4180aa42019-05-10 16:27:48 -07001520 ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001521}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001522
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001523void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
1524 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
1525 if (!videoDevice) {
1526 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
1527 return;
1528 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001529 // Transfer ownership of this video device to a matching input device
1530 for (size_t i = 0; i < mDevices.size(); i++) {
1531 Device* device = mDevices.valueAt(i);
1532 if (videoDevice->getName() == device->identifier.name) {
1533 device->videoDevice = std::move(videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001534 if (device->enabled) {
1535 registerVideoDeviceForEpollLocked(*device->videoDevice);
1536 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001537 return;
1538 }
1539 }
1540
1541 // Couldn't find a matching input device, so just add it to a temporary holding queue.
1542 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001543 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001544 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001545 mUnattachedVideoDevices.push_back(std::move(videoDevice));
1546}
1547
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001548bool EventHub::isDeviceEnabled(int32_t deviceId) {
1549 AutoMutex _l(mLock);
1550 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001551 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001552 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1553 return false;
1554 }
1555 return device->enabled;
1556}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001557
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001558status_t EventHub::enableDevice(int32_t deviceId) {
1559 AutoMutex _l(mLock);
1560 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001561 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001562 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1563 return BAD_VALUE;
1564 }
1565 if (device->enabled) {
1566 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
1567 return OK;
1568 }
1569 status_t result = device->enable();
1570 if (result != OK) {
1571 ALOGE("Failed to enable device %" PRId32, deviceId);
1572 return result;
1573 }
1574
1575 configureFd(device);
1576
1577 return registerDeviceForEpollLocked(device);
1578}
1579
1580status_t EventHub::disableDevice(int32_t deviceId) {
1581 AutoMutex _l(mLock);
1582 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001583 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001584 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1585 return BAD_VALUE;
1586 }
1587 if (!device->enabled) {
1588 ALOGW("Duplicate call to %s, input device already disabled", __func__);
1589 return OK;
1590 }
1591 unregisterDeviceFromEpollLocked(device);
1592 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001593}
1594
1595void EventHub::createVirtualKeyboardLocked() {
1596 InputDeviceIdentifier identifier;
1597 identifier.name = "Virtual";
1598 identifier.uniqueId = "<virtual>";
1599 assignDescriptorLocked(identifier);
1600
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001601 Device* device =
1602 new Device(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>", identifier);
1603 device->classes = INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_ALPHAKEY |
1604 INPUT_DEVICE_CLASS_DPAD | INPUT_DEVICE_CLASS_VIRTUAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001605 loadKeyMapLocked(device);
1606 addDeviceLocked(device);
1607}
1608
1609void EventHub::addDeviceLocked(Device* device) {
1610 mDevices.add(device->id, device);
1611 device->next = mOpeningDevices;
1612 mOpeningDevices = device;
1613}
1614
1615void EventHub::loadConfigurationLocked(Device* device) {
Chris Ye1d927aa2020-07-04 18:22:41 -07001616 device->configurationFile =
1617 getInputDeviceConfigurationFilePathByDeviceIdentifier(device->identifier,
1618 InputDeviceConfigurationFileType::
1619 CONFIGURATION);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001620 if (device->configurationFile.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001621 ALOGD("No input device configuration file found for device '%s'.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001622 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001623 } else {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001624 status_t status = PropertyMap::load(String8(device->configurationFile.c_str()),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001625 &device->configuration);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001626 if (status) {
1627 ALOGE("Error loading input device configuration file for device '%s'. "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001628 "Using default configuration.",
1629 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001630 }
1631 }
1632}
1633
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001634bool EventHub::loadVirtualKeyMapLocked(Device* device) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001635 // The virtual key map is supplied by the kernel as a system board property file.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001636 std::string path;
1637 path += "/sys/board_properties/virtualkeys.";
Siarhei Vishniakoub45635c2019-02-20 19:22:09 -06001638 path += device->identifier.getCanonicalName();
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001639 if (access(path.c_str(), R_OK)) {
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001640 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001641 }
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001642 device->virtualKeyMap = VirtualKeyMap::load(path);
1643 return device->virtualKeyMap != nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001644}
1645
1646status_t EventHub::loadKeyMapLocked(Device* device) {
1647 return device->keyMap.load(device->identifier, device->configuration);
1648}
1649
1650bool EventHub::isExternalDeviceLocked(Device* device) {
1651 if (device->configuration) {
1652 bool value;
1653 if (device->configuration->tryGetProperty(String8("device.internal"), value)) {
1654 return !value;
1655 }
1656 }
1657 return device->identifier.bus == BUS_USB || device->identifier.bus == BUS_BLUETOOTH;
1658}
1659
Tim Kilbourn063ff532015-04-08 10:26:18 -07001660bool EventHub::deviceHasMicLocked(Device* device) {
1661 if (device->configuration) {
1662 bool value;
1663 if (device->configuration->tryGetProperty(String8("audio.mic"), value)) {
1664 return value;
1665 }
1666 }
1667 return false;
1668}
1669
Michael Wrightd02c5b62014-02-10 15:10:22 -08001670int32_t EventHub::getNextControllerNumberLocked(Device* device) {
1671 if (mControllerNumbers.isFull()) {
1672 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001673 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001674 return 0;
1675 }
1676 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
1677 // one
1678 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
1679}
1680
1681void EventHub::releaseControllerNumberLocked(Device* device) {
1682 int32_t num = device->controllerNumber;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001683 device->controllerNumber = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001684 if (num == 0) {
1685 return;
1686 }
1687 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
1688}
1689
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001690void EventHub::setLedForControllerLocked(Device* device) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001691 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
1692 setLedStateLocked(device, ALED_CONTROLLER_1 + i, device->controllerNumber == i + 1);
1693 }
1694}
1695
1696bool EventHub::hasKeycodeLocked(Device* device, int keycode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001697 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001698 return false;
1699 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001700
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001701 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001702 device->keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes);
1703 const size_t N = scanCodes.size();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001704 for (size_t i = 0; i < N && i <= KEY_MAX; i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001705 int32_t sc = scanCodes[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001706 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, device->keyBitmask)) {
1707 return true;
1708 }
1709 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001710
Michael Wrightd02c5b62014-02-10 15:10:22 -08001711 return false;
1712}
1713
1714status_t EventHub::mapLed(Device* device, int32_t led, int32_t* outScanCode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001715 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001716 return NAME_NOT_FOUND;
1717 }
1718
1719 int32_t scanCode;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001720 if (device->keyMap.keyLayoutMap->findScanCodeForLed(led, &scanCode) != NAME_NOT_FOUND) {
1721 if (scanCode >= 0 && scanCode <= LED_MAX && test_bit(scanCode, device->ledBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001722 *outScanCode = scanCode;
1723 return NO_ERROR;
1724 }
1725 }
1726 return NAME_NOT_FOUND;
1727}
1728
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001729void EventHub::closeDeviceByPathLocked(const char* devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001730 Device* device = getDeviceByPathLocked(devicePath);
1731 if (device) {
1732 closeDeviceLocked(device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001733 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001734 }
1735 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001736}
1737
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001738/**
1739 * Find the video device by filename, and close it.
1740 * The video device is closed by path during an inotify event, where we don't have the
1741 * additional context about the video device fd, or the associated input device.
1742 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001743void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001744 // A video device may be owned by an existing input device, or it may be stored in
1745 // the mUnattachedVideoDevices queue. Check both locations.
1746 for (size_t i = 0; i < mDevices.size(); i++) {
1747 Device* device = mDevices.valueAt(i);
1748 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001749 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001750 device->videoDevice = nullptr;
1751 return;
1752 }
1753 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001754 mUnattachedVideoDevices
1755 .erase(std::remove_if(mUnattachedVideoDevices.begin(), mUnattachedVideoDevices.end(),
1756 [&devicePath](
1757 const std::unique_ptr<TouchVideoDevice>& videoDevice) {
1758 return videoDevice->getPath() == devicePath;
1759 }),
1760 mUnattachedVideoDevices.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001761}
1762
1763void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001764 mUnattachedVideoDevices.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001765 while (mDevices.size() > 0) {
1766 closeDeviceLocked(mDevices.valueAt(mDevices.size() - 1));
1767 }
1768}
1769
1770void EventHub::closeDeviceLocked(Device* device) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001771 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=0x%x", device->path.c_str(),
1772 device->identifier.name.c_str(), device->id, device->fd, device->classes);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001773
1774 if (device->id == mBuiltInKeyboardId) {
1775 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001776 device->path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001777 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
1778 }
1779
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001780 unregisterDeviceFromEpollLocked(device);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001781 if (device->videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001782 // This must be done after the video device is removed from epoll
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001783 mUnattachedVideoDevices.push_back(std::move(device->videoDevice));
1784 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001785
1786 releaseControllerNumberLocked(device);
1787
1788 mDevices.removeItem(device->id);
1789 device->close();
1790
1791 // Unlink for opening devices list if it is present.
Yi Kong9b14ac62018-07-17 13:48:38 -07001792 Device* pred = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001793 bool found = false;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001794 for (Device* entry = mOpeningDevices; entry != nullptr;) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001795 if (entry == device) {
1796 found = true;
1797 break;
1798 }
1799 pred = entry;
1800 entry = entry->next;
1801 }
1802 if (found) {
1803 // Unlink the device from the opening devices list then delete it.
1804 // We don't need to tell the client that the device was closed because
1805 // it does not even know it was opened in the first place.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001806 ALOGI("Device %s was immediately closed after opening.", device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001807 if (pred) {
1808 pred->next = device->next;
1809 } else {
1810 mOpeningDevices = device->next;
1811 }
1812 delete device;
1813 } else {
1814 // Link into closing devices list.
1815 // The device will be deleted later after we have informed the client.
1816 device->next = mClosingDevices;
1817 mClosingDevices = device;
1818 }
1819}
1820
1821status_t EventHub::readNotifyLocked() {
1822 int res;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001823 char event_buf[512];
1824 int event_size;
1825 int event_pos = 0;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001826 struct inotify_event* event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001827
1828 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
1829 res = read(mINotifyFd, event_buf, sizeof(event_buf));
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001830 if (res < (int)sizeof(*event)) {
1831 if (errno == EINTR) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001832 ALOGW("could not get event, %s\n", strerror(errno));
1833 return -1;
1834 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001835
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001836 while (res >= (int)sizeof(*event)) {
1837 event = (struct inotify_event*)(event_buf + event_pos);
1838 if (event->len) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001839 if (event->wd == mInputWd) {
1840 std::string filename = StringPrintf("%s/%s", DEVICE_PATH, event->name);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001841 if (event->mask & IN_CREATE) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001842 openDeviceLocked(filename.c_str());
1843 } else {
1844 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
1845 closeDeviceByPathLocked(filename.c_str());
1846 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001847 } else if (event->wd == mVideoWd) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001848 if (isV4lTouchNode(event->name)) {
1849 std::string filename = StringPrintf("%s/%s", VIDEO_DEVICE_PATH, event->name);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001850 if (event->mask & IN_CREATE) {
1851 openVideoDeviceLocked(filename);
1852 } else {
1853 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
1854 closeVideoDeviceByPathLocked(filename);
1855 }
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001856 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001857 } else {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001858 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event->wd);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001859 }
1860 }
1861 event_size = sizeof(*event) + event->len;
1862 res -= event_size;
1863 event_pos += event_size;
1864 }
1865 return 0;
1866}
1867
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001868status_t EventHub::scanDirLocked(const char* dirname) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001869 char devname[PATH_MAX];
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001870 char* filename;
1871 DIR* dir;
1872 struct dirent* de;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001873 dir = opendir(dirname);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001874 if (dir == nullptr) return -1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001875 strcpy(devname, dirname);
1876 filename = devname + strlen(devname);
1877 *filename++ = '/';
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001878 while ((de = readdir(dir))) {
1879 if (de->d_name[0] == '.' &&
1880 (de->d_name[1] == '\0' || (de->d_name[1] == '.' && de->d_name[2] == '\0')))
Michael Wrightd02c5b62014-02-10 15:10:22 -08001881 continue;
1882 strcpy(filename, de->d_name);
1883 openDeviceLocked(devname);
1884 }
1885 closedir(dir);
1886 return 0;
1887}
1888
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001889/**
1890 * Look for all dirname/v4l-touch* devices, and open them.
1891 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001892status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001893 DIR* dir;
1894 struct dirent* de;
1895 dir = opendir(dirname.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001896 if (!dir) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001897 ALOGE("Could not open video directory %s", dirname.c_str());
1898 return BAD_VALUE;
1899 }
1900
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001901 while ((de = readdir(dir))) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001902 const char* name = de->d_name;
1903 if (isV4lTouchNode(name)) {
1904 ALOGI("Found touch video device %s", name);
1905 openVideoDeviceLocked(dirname + "/" + name);
1906 }
1907 }
1908 closedir(dir);
1909 return OK;
1910}
1911
Michael Wrightd02c5b62014-02-10 15:10:22 -08001912void EventHub::requestReopenDevices() {
1913 ALOGV("requestReopenDevices() called");
1914
1915 AutoMutex _l(mLock);
1916 mNeedToReopenDevices = true;
1917}
1918
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001919void EventHub::dump(std::string& dump) {
1920 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001921
1922 { // acquire lock
1923 AutoMutex _l(mLock);
1924
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001925 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001926
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001927 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001928
1929 for (size_t i = 0; i < mDevices.size(); i++) {
1930 const Device* device = mDevices.valueAt(i);
1931 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001932 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001933 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001934 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001935 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001936 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001937 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001938 dump += StringPrintf(INDENT3 "Classes: 0x%08x\n", device->classes);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001939 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001940 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001941 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
1942 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001943 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001944 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001945 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001946 "product=0x%04x, version=0x%04x\n",
1947 device->identifier.bus, device->identifier.vendor,
1948 device->identifier.product, device->identifier.version);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001949 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001950 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001951 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001952 device->keyMap.keyCharacterMapFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001953 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001954 device->configurationFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001955 dump += StringPrintf(INDENT3 "HaveKeyboardLayoutOverlay: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001956 toString(device->overlayKeyMap != nullptr));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001957 dump += INDENT3 "VideoDevice: ";
1958 if (device->videoDevice) {
1959 dump += device->videoDevice->dump() + "\n";
1960 } else {
1961 dump += "<none>\n";
1962 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001963 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001964
1965 dump += INDENT "Unattached video devices:\n";
1966 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
1967 dump += INDENT2 + videoDevice->dump() + "\n";
1968 }
1969 if (mUnattachedVideoDevices.empty()) {
1970 dump += INDENT2 "<none>\n";
1971 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001972 } // release lock
1973}
1974
1975void EventHub::monitor() {
1976 // Acquire and release the lock to ensure that the event hub has not deadlocked.
1977 mLock.lock();
1978 mLock.unlock();
1979}
1980
Michael Wrightd02c5b62014-02-10 15:10:22 -08001981}; // namespace android