blob: c15ecfd66b517f3165979403eee4b652fe790b0b [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>
27#include <sys/epoll.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070028#include <sys/inotify.h>
29#include <sys/ioctl.h>
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070030#include <sys/limits.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070031#include <unistd.h>
32
Michael Wrightd02c5b62014-02-10 15:10:22 -080033#define LOG_TAG "EventHub"
34
35// #define LOG_NDEBUG 0
36
37#include "EventHub.h"
38
39#include <hardware_legacy/power.h>
40
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080041#include <android-base/stringprintf.h>
Philip Quinn39b81682019-01-09 22:20:39 -080042#include <cutils/properties.h>
Dan Albert677d87e2014-06-16 17:31:28 -070043#include <openssl/sha.h>
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070044#include <utils/Errors.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080045#include <utils/Log.h>
46#include <utils/Timers.h>
47#include <utils/threads.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080048
Michael Wrightd02c5b62014-02-10 15:10:22 -080049#include <input/KeyCharacterMap.h>
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070050#include <input/KeyLayoutMap.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080051#include <input/VirtualKeyMap.h>
52
Michael Wrightd02c5b62014-02-10 15:10:22 -080053/* this macro is used to tell if "bit" is set in "array"
54 * it selects a byte from the array, and does a boolean AND
55 * operation with a byte that only has the relevant bit set.
56 * eg. to check for the 12th bit, we do (array[1] & 1<<4)
57 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070058#define test_bit(bit, array) ((array)[(bit) / 8] & (1 << ((bit) % 8)))
Michael Wrightd02c5b62014-02-10 15:10:22 -080059
60/* this macro computes the number of bytes needed to represent a bit array of the specified size */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070061#define sizeof_bit_array(bits) (((bits) + 7) / 8)
Michael Wrightd02c5b62014-02-10 15:10:22 -080062
63#define INDENT " "
64#define INDENT2 " "
65#define INDENT3 " "
66
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080067using android::base::StringPrintf;
68
Michael Wrightd02c5b62014-02-10 15:10:22 -080069namespace android {
70
Siarhei Vishniakou25920312018-12-12 15:24:44 -080071static constexpr bool DEBUG = false;
72
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070073static const char* WAKE_LOCK_ID = "KeyEvents";
74static const char* DEVICE_PATH = "/dev/input";
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080075// v4l2 devices go directly into /dev
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070076static const char* VIDEO_DEVICE_PATH = "/dev";
Michael Wrightd02c5b62014-02-10 15:10:22 -080077
Michael Wrightd02c5b62014-02-10 15:10:22 -080078static inline const char* toString(bool value) {
79 return value ? "true" : "false";
80}
81
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010082static std::string sha1(const std::string& in) {
Dan Albert677d87e2014-06-16 17:31:28 -070083 SHA_CTX ctx;
84 SHA1_Init(&ctx);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010085 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
Dan Albert677d87e2014-06-16 17:31:28 -070086 u_char digest[SHA_DIGEST_LENGTH];
87 SHA1_Final(digest, &ctx);
Michael Wrightd02c5b62014-02-10 15:10:22 -080088
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010089 std::string out;
Dan Albert677d87e2014-06-16 17:31:28 -070090 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010091 out += StringPrintf("%02x", digest[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -080092 }
93 return out;
94}
95
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080096/**
97 * Return true if name matches "v4l-touch*"
98 */
99static bool isV4lTouchNode(const char* name) {
100 return strstr(name, "v4l-touch") == name;
101}
102
Philip Quinn39b81682019-01-09 22:20:39 -0800103/**
104 * Returns true if V4L devices should be scanned.
105 *
106 * The system property ro.input.video_enabled can be used to control whether
107 * EventHub scans and opens V4L devices. As V4L does not support multiple
108 * clients, EventHub effectively blocks access to these devices when it opens
Siarhei Vishniakou29f88492019-04-05 14:11:43 -0700109 * them.
110 *
111 * Setting this to "false" would prevent any video devices from being discovered and
112 * associated with input devices.
113 *
114 * This property can be used as follows:
115 * 1. To turn off features that are dependent on video device presence.
116 * 2. During testing and development, to allow other clients to read video devices
117 * directly from /dev.
Philip Quinn39b81682019-01-09 22:20:39 -0800118 */
119static bool isV4lScanningEnabled() {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700120 return property_get_bool("ro.input.video_enabled", true /* default_value */);
Philip Quinn39b81682019-01-09 22:20:39 -0800121}
122
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800123static nsecs_t processEventTimestamp(const struct input_event& event) {
124 // Use the time specified in the event instead of the current time
125 // so that downstream code can get more accurate estimates of
126 // event dispatch latency from the time the event is enqueued onto
127 // the evdev client buffer.
128 //
129 // The event's timestamp fortuitously uses the same monotonic clock
130 // time base as the rest of Android. The kernel event device driver
131 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
132 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
133 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
134 // system call that also queries ktime_get_ts().
135
136 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.time.tv_sec) +
137 microseconds_to_nanoseconds(event.time.tv_usec);
138 return inputEventTime;
139}
140
Michael Wrightd02c5b62014-02-10 15:10:22 -0800141// --- Global Functions ---
142
143uint32_t getAbsAxisUsage(int32_t axis, uint32_t deviceClasses) {
144 // Touch devices get dibs on touch-related axes.
145 if (deviceClasses & INPUT_DEVICE_CLASS_TOUCH) {
146 switch (axis) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700147 case ABS_X:
148 case ABS_Y:
149 case ABS_PRESSURE:
150 case ABS_TOOL_WIDTH:
151 case ABS_DISTANCE:
152 case ABS_TILT_X:
153 case ABS_TILT_Y:
154 case ABS_MT_SLOT:
155 case ABS_MT_TOUCH_MAJOR:
156 case ABS_MT_TOUCH_MINOR:
157 case ABS_MT_WIDTH_MAJOR:
158 case ABS_MT_WIDTH_MINOR:
159 case ABS_MT_ORIENTATION:
160 case ABS_MT_POSITION_X:
161 case ABS_MT_POSITION_Y:
162 case ABS_MT_TOOL_TYPE:
163 case ABS_MT_BLOB_ID:
164 case ABS_MT_TRACKING_ID:
165 case ABS_MT_PRESSURE:
166 case ABS_MT_DISTANCE:
167 return INPUT_DEVICE_CLASS_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800168 }
169 }
170
Michael Wright842500e2015-03-13 17:32:02 -0700171 // External stylus gets the pressure axis
172 if (deviceClasses & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
173 if (axis == ABS_PRESSURE) {
174 return INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
175 }
176 }
177
Michael Wrightd02c5b62014-02-10 15:10:22 -0800178 // Joystick devices get the rest.
179 return deviceClasses & INPUT_DEVICE_CLASS_JOYSTICK;
180}
181
182// --- EventHub::Device ---
183
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100184EventHub::Device::Device(int fd, int32_t id, const std::string& path,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700185 const InputDeviceIdentifier& identifier)
186 : next(nullptr),
187 fd(fd),
188 id(id),
189 path(path),
190 identifier(identifier),
191 classes(0),
192 configuration(nullptr),
193 virtualKeyMap(nullptr),
194 ffEffectPlaying(false),
195 ffEffectId(-1),
196 controllerNumber(0),
197 enabled(true),
198 isVirtual(fd < 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800199 memset(keyBitmask, 0, sizeof(keyBitmask));
200 memset(absBitmask, 0, sizeof(absBitmask));
201 memset(relBitmask, 0, sizeof(relBitmask));
202 memset(swBitmask, 0, sizeof(swBitmask));
203 memset(ledBitmask, 0, sizeof(ledBitmask));
204 memset(ffBitmask, 0, sizeof(ffBitmask));
205 memset(propBitmask, 0, sizeof(propBitmask));
206}
207
208EventHub::Device::~Device() {
209 close();
210 delete configuration;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800211}
212
213void EventHub::Device::close() {
214 if (fd >= 0) {
215 ::close(fd);
216 fd = -1;
217 }
218}
219
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700220status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100221 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700222 if (fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100223 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700224 return -errno;
225 }
226 enabled = true;
227 return OK;
228}
229
230status_t EventHub::Device::disable() {
231 close();
232 enabled = false;
233 return OK;
234}
235
236bool EventHub::Device::hasValidFd() {
237 return !isVirtual && enabled;
238}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800239
240// --- EventHub ---
241
Michael Wrightd02c5b62014-02-10 15:10:22 -0800242const int EventHub::EPOLL_MAX_EVENTS;
243
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700244EventHub::EventHub(void)
245 : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
246 mNextDeviceId(1),
247 mControllerNumbers(),
248 mOpeningDevices(nullptr),
249 mClosingDevices(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800250 mNeedToSendFinishedDeviceScan(false),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700251 mNeedToReopenDevices(false),
252 mNeedToScanDevices(true),
253 mPendingEventCount(0),
254 mPendingEventIndex(0),
255 mPendingINotify(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800256 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
257
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800258 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800259 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800260
261 mINotifyFd = inotify_init();
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800262 mInputWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700263 LOG_ALWAYS_FATAL_IF(mInputWd < 0, "Could not register INotify for %s: %s", DEVICE_PATH,
264 strerror(errno));
Philip Quinn39b81682019-01-09 22:20:39 -0800265 if (isV4lScanningEnabled()) {
266 mVideoWd = inotify_add_watch(mINotifyFd, VIDEO_DEVICE_PATH, IN_DELETE | IN_CREATE);
267 LOG_ALWAYS_FATAL_IF(mVideoWd < 0, "Could not register INotify for %s: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700268 VIDEO_DEVICE_PATH, strerror(errno));
Philip Quinn39b81682019-01-09 22:20:39 -0800269 } else {
270 mVideoWd = -1;
271 ALOGI("Video device scanning disabled");
272 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800273
274 struct epoll_event eventItem;
275 memset(&eventItem, 0, sizeof(eventItem));
276 eventItem.events = EPOLLIN;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700277 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800278 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800279 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
280
281 int wakeFds[2];
282 result = pipe(wakeFds);
283 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
284
285 mWakeReadPipeFd = wakeFds[0];
286 mWakeWritePipeFd = wakeFds[1];
287
288 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
289 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700290 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800291
292 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
293 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700294 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800295
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700296 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800297 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
298 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700299 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800300}
301
302EventHub::~EventHub(void) {
303 closeAllDevicesLocked();
304
305 while (mClosingDevices) {
306 Device* device = mClosingDevices;
307 mClosingDevices = device->next;
308 delete device;
309 }
310
311 ::close(mEpollFd);
312 ::close(mINotifyFd);
313 ::close(mWakeReadPipeFd);
314 ::close(mWakeWritePipeFd);
315
316 release_wake_lock(WAKE_LOCK_ID);
317}
318
319InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
320 AutoMutex _l(mLock);
321 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700322 if (device == nullptr) return InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800323 return device->identifier;
324}
325
326uint32_t EventHub::getDeviceClasses(int32_t deviceId) const {
327 AutoMutex _l(mLock);
328 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700329 if (device == nullptr) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800330 return device->classes;
331}
332
333int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
334 AutoMutex _l(mLock);
335 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700336 if (device == nullptr) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800337 return device->controllerNumber;
338}
339
340void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
341 AutoMutex _l(mLock);
342 Device* device = getDeviceLocked(deviceId);
343 if (device && device->configuration) {
344 *outConfiguration = *device->configuration;
345 } else {
346 outConfiguration->clear();
347 }
348}
349
350status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700351 RawAbsoluteAxisInfo* outAxisInfo) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800352 outAxisInfo->clear();
353
354 if (axis >= 0 && axis <= ABS_MAX) {
355 AutoMutex _l(mLock);
356
357 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700358 if (device && device->hasValidFd() && test_bit(axis, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800359 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700360 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
361 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
362 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800363 return -errno;
364 }
365
366 if (info.minimum != info.maximum) {
367 outAxisInfo->valid = true;
368 outAxisInfo->minValue = info.minimum;
369 outAxisInfo->maxValue = info.maximum;
370 outAxisInfo->flat = info.flat;
371 outAxisInfo->fuzz = info.fuzz;
372 outAxisInfo->resolution = info.resolution;
373 }
374 return OK;
375 }
376 }
377 return -1;
378}
379
380bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
381 if (axis >= 0 && axis <= REL_MAX) {
382 AutoMutex _l(mLock);
383
384 Device* device = getDeviceLocked(deviceId);
385 if (device) {
386 return test_bit(axis, device->relBitmask);
387 }
388 }
389 return false;
390}
391
392bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
393 if (property >= 0 && property <= INPUT_PROP_MAX) {
394 AutoMutex _l(mLock);
395
396 Device* device = getDeviceLocked(deviceId);
397 if (device) {
398 return test_bit(property, device->propBitmask);
399 }
400 }
401 return false;
402}
403
404int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
405 if (scanCode >= 0 && scanCode <= KEY_MAX) {
406 AutoMutex _l(mLock);
407
408 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700409 if (device && device->hasValidFd() && test_bit(scanCode, device->keyBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800410 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
411 memset(keyState, 0, sizeof(keyState));
412 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
413 return test_bit(scanCode, keyState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
414 }
415 }
416 }
417 return AKEY_STATE_UNKNOWN;
418}
419
420int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
421 AutoMutex _l(mLock);
422
423 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700424 if (device && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800425 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800426 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode, &scanCodes);
427 if (scanCodes.size() != 0) {
428 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
429 memset(keyState, 0, sizeof(keyState));
430 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
431 for (size_t i = 0; i < scanCodes.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800432 int32_t sc = scanCodes[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -0800433 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, keyState)) {
434 return AKEY_STATE_DOWN;
435 }
436 }
437 return AKEY_STATE_UP;
438 }
439 }
440 }
441 return AKEY_STATE_UNKNOWN;
442}
443
444int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
445 if (sw >= 0 && sw <= SW_MAX) {
446 AutoMutex _l(mLock);
447
448 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700449 if (device && device->hasValidFd() && test_bit(sw, device->swBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800450 uint8_t swState[sizeof_bit_array(SW_MAX + 1)];
451 memset(swState, 0, sizeof(swState));
452 if (ioctl(device->fd, EVIOCGSW(sizeof(swState)), swState) >= 0) {
453 return test_bit(sw, swState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
454 }
455 }
456 }
457 return AKEY_STATE_UNKNOWN;
458}
459
460status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
461 *outValue = 0;
462
463 if (axis >= 0 && axis <= ABS_MAX) {
464 AutoMutex _l(mLock);
465
466 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700467 if (device && device->hasValidFd() && test_bit(axis, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800468 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700469 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
470 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
471 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800472 return -errno;
473 }
474
475 *outValue = info.value;
476 return OK;
477 }
478 }
479 return -1;
480}
481
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700482bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes, const int32_t* keyCodes,
483 uint8_t* outFlags) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800484 AutoMutex _l(mLock);
485
486 Device* device = getDeviceLocked(deviceId);
487 if (device && device->keyMap.haveKeyLayout()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800488 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800489 for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) {
490 scanCodes.clear();
491
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700492 status_t err = device->keyMap.keyLayoutMap->findScanCodesForKey(keyCodes[codeIndex],
493 &scanCodes);
494 if (!err) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800495 // check the possible scan codes identified by the layout map against the
496 // map of codes actually emitted by the driver
497 for (size_t sc = 0; sc < scanCodes.size(); sc++) {
498 if (test_bit(scanCodes[sc], device->keyBitmask)) {
499 outFlags[codeIndex] = 1;
500 break;
501 }
502 }
503 }
504 }
505 return true;
506 }
507 return false;
508}
509
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700510status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
511 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800512 AutoMutex _l(mLock);
513 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700514 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800515
516 if (device) {
517 // Check the key character map first.
518 sp<KeyCharacterMap> kcm = device->getKeyCharacterMap();
Yi Kong9b14ac62018-07-17 13:48:38 -0700519 if (kcm != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800520 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
521 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700522 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800523 }
524 }
525
526 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700527 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800528 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700529 status = NO_ERROR;
530 }
531 }
532
533 if (status == NO_ERROR) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700534 if (kcm != nullptr) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700535 kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState);
536 } else {
537 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800538 }
539 }
540 }
541
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700542 if (status != NO_ERROR) {
543 *outKeycode = 0;
544 *outFlags = 0;
545 *outMetaState = metaState;
546 }
547
548 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800549}
550
551status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
552 AutoMutex _l(mLock);
553 Device* device = getDeviceLocked(deviceId);
554
555 if (device && device->keyMap.haveKeyLayout()) {
556 status_t err = device->keyMap.keyLayoutMap->mapAxis(scanCode, outAxisInfo);
557 if (err == NO_ERROR) {
558 return NO_ERROR;
559 }
560 }
561
562 return NAME_NOT_FOUND;
563}
564
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100565void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800566 AutoMutex _l(mLock);
567
568 mExcludedDevices = devices;
569}
570
571bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
572 AutoMutex _l(mLock);
573 Device* device = getDeviceLocked(deviceId);
574 if (device && scanCode >= 0 && scanCode <= KEY_MAX) {
575 if (test_bit(scanCode, device->keyBitmask)) {
576 return true;
577 }
578 }
579 return false;
580}
581
582bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
583 AutoMutex _l(mLock);
584 Device* device = getDeviceLocked(deviceId);
585 int32_t sc;
586 if (device && mapLed(device, led, &sc) == NO_ERROR) {
587 if (test_bit(sc, device->ledBitmask)) {
588 return true;
589 }
590 }
591 return false;
592}
593
594void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
595 AutoMutex _l(mLock);
596 Device* device = getDeviceLocked(deviceId);
597 setLedStateLocked(device, led, on);
598}
599
600void EventHub::setLedStateLocked(Device* device, int32_t led, bool on) {
601 int32_t sc;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700602 if (device && device->hasValidFd() && mapLed(device, led, &sc) != NAME_NOT_FOUND) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800603 struct input_event ev;
604 ev.time.tv_sec = 0;
605 ev.time.tv_usec = 0;
606 ev.type = EV_LED;
607 ev.code = sc;
608 ev.value = on ? 1 : 0;
609
610 ssize_t nWrite;
611 do {
612 nWrite = write(device->fd, &ev, sizeof(struct input_event));
613 } while (nWrite == -1 && errno == EINTR);
614 }
615}
616
617void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700618 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800619 outVirtualKeys.clear();
620
621 AutoMutex _l(mLock);
622 Device* device = getDeviceLocked(deviceId);
623 if (device && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800624 const std::vector<VirtualKeyDefinition> virtualKeys =
625 device->virtualKeyMap->getVirtualKeys();
626 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800627 }
628}
629
630sp<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
631 AutoMutex _l(mLock);
632 Device* device = getDeviceLocked(deviceId);
633 if (device) {
634 return device->getKeyCharacterMap();
635 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700636 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800637}
638
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700639bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, const sp<KeyCharacterMap>& map) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800640 AutoMutex _l(mLock);
641 Device* device = getDeviceLocked(deviceId);
642 if (device) {
643 if (map != device->overlayKeyMap) {
644 device->overlayKeyMap = map;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700645 device->combinedKeyMap = KeyCharacterMap::combine(device->keyMap.keyCharacterMap, map);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800646 return true;
647 }
648 }
649 return false;
650}
651
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100652static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
653 std::string rawDescriptor;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700654 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800655 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100656 if (!identifier.uniqueId.empty()) {
657 rawDescriptor += "uniqueId:";
658 rawDescriptor += identifier.uniqueId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800659 } else if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100660 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800661 }
662
663 if (identifier.vendor == 0 && identifier.product == 0) {
664 // If we don't know the vendor and product id, then the device is probably
665 // built-in so we need to rely on other information to uniquely identify
666 // the input device. Usually we try to avoid relying on the device name or
667 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100668 if (!identifier.name.empty()) {
669 rawDescriptor += "name:";
670 rawDescriptor += identifier.name;
671 } else if (!identifier.location.empty()) {
672 rawDescriptor += "location:";
673 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800674 }
675 }
676 identifier.descriptor = sha1(rawDescriptor);
677 return rawDescriptor;
678}
679
680void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
681 // Compute a device descriptor that uniquely identifies the device.
682 // The descriptor is assumed to be a stable identifier. Its value should not
683 // change between reboots, reconnections, firmware updates or new releases
684 // of Android. In practice we sometimes get devices that cannot be uniquely
685 // identified. In this case we enforce uniqueness between connected devices.
686 // Ideally, we also want the descriptor to be short and relatively opaque.
687
688 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100689 std::string rawDescriptor = generateDescriptor(identifier);
690 if (identifier.uniqueId.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800691 // If it didn't have a unique id check for conflicts and enforce
692 // uniqueness if necessary.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700693 while (getDeviceByDescriptorLocked(identifier.descriptor) != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800694 identifier.nonce++;
695 rawDescriptor = generateDescriptor(identifier);
696 }
697 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100698 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700699 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800700}
701
702void EventHub::vibrate(int32_t deviceId, nsecs_t duration) {
703 AutoMutex _l(mLock);
704 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700705 if (device && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800706 ff_effect effect;
707 memset(&effect, 0, sizeof(effect));
708 effect.type = FF_RUMBLE;
709 effect.id = device->ffEffectId;
710 effect.u.rumble.strong_magnitude = 0xc000;
711 effect.u.rumble.weak_magnitude = 0xc000;
712 effect.replay.length = (duration + 999999LL) / 1000000LL;
713 effect.replay.delay = 0;
714 if (ioctl(device->fd, EVIOCSFF, &effect)) {
715 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700716 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800717 return;
718 }
719 device->ffEffectId = effect.id;
720
721 struct input_event ev;
722 ev.time.tv_sec = 0;
723 ev.time.tv_usec = 0;
724 ev.type = EV_FF;
725 ev.code = device->ffEffectId;
726 ev.value = 1;
727 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
728 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700729 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800730 return;
731 }
732 device->ffEffectPlaying = true;
733 }
734}
735
736void EventHub::cancelVibrate(int32_t deviceId) {
737 AutoMutex _l(mLock);
738 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700739 if (device && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800740 if (device->ffEffectPlaying) {
741 device->ffEffectPlaying = false;
742
743 struct input_event ev;
744 ev.time.tv_sec = 0;
745 ev.time.tv_usec = 0;
746 ev.type = EV_FF;
747 ev.code = device->ffEffectId;
748 ev.value = 0;
749 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
750 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700751 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800752 return;
753 }
754 }
755 }
756}
757
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100758EventHub::Device* EventHub::getDeviceByDescriptorLocked(const std::string& descriptor) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800759 size_t size = mDevices.size();
760 for (size_t i = 0; i < size; i++) {
761 Device* device = mDevices.valueAt(i);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100762 if (descriptor == device->identifier.descriptor) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800763 return device;
764 }
765 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700766 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800767}
768
769EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -0800770 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800771 deviceId = mBuiltInKeyboardId;
772 }
773 ssize_t index = mDevices.indexOfKey(deviceId);
774 return index >= 0 ? mDevices.valueAt(index) : NULL;
775}
776
777EventHub::Device* EventHub::getDeviceByPathLocked(const char* devicePath) const {
778 for (size_t i = 0; i < mDevices.size(); i++) {
779 Device* device = mDevices.valueAt(i);
780 if (device->path == devicePath) {
781 return device;
782 }
783 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700784 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800785}
786
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700787/**
788 * The file descriptor could be either input device, or a video device (associated with a
789 * specific input device). Check both cases here, and return the device that this event
790 * belongs to. Caller can compare the fd's once more to determine event type.
791 * Looks through all input devices, and only attached video devices. Unattached video
792 * devices are ignored.
793 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700794EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
795 for (size_t i = 0; i < mDevices.size(); i++) {
796 Device* device = mDevices.valueAt(i);
797 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700798 // This is an input device event
799 return device;
800 }
801 if (device->videoDevice && device->videoDevice->getFd() == fd) {
802 // This is a video device event
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700803 return device;
804 }
805 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700806 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
807 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700808 return nullptr;
809}
810
Michael Wrightd02c5b62014-02-10 15:10:22 -0800811size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
812 ALOG_ASSERT(bufferSize >= 1);
813
814 AutoMutex _l(mLock);
815
816 struct input_event readBuffer[bufferSize];
817
818 RawEvent* event = buffer;
819 size_t capacity = bufferSize;
820 bool awoken = false;
821 for (;;) {
822 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
823
824 // Reopen input devices if needed.
825 if (mNeedToReopenDevices) {
826 mNeedToReopenDevices = false;
827
828 ALOGI("Reopening all input devices due to a configuration change.");
829
830 closeAllDevicesLocked();
831 mNeedToScanDevices = true;
832 break; // return to the caller before we actually rescan
833 }
834
835 // Report any devices that had last been added/removed.
836 while (mClosingDevices) {
837 Device* device = mClosingDevices;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700838 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800839 mClosingDevices = device->next;
840 event->when = now;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700841 event->deviceId = (device->id == mBuiltInKeyboardId)
842 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
843 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800844 event->type = DEVICE_REMOVED;
845 event += 1;
846 delete device;
847 mNeedToSendFinishedDeviceScan = true;
848 if (--capacity == 0) {
849 break;
850 }
851 }
852
853 if (mNeedToScanDevices) {
854 mNeedToScanDevices = false;
855 scanDevicesLocked();
856 mNeedToSendFinishedDeviceScan = true;
857 }
858
Yi Kong9b14ac62018-07-17 13:48:38 -0700859 while (mOpeningDevices != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800860 Device* device = mOpeningDevices;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700861 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800862 mOpeningDevices = device->next;
863 event->when = now;
864 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
865 event->type = DEVICE_ADDED;
866 event += 1;
867 mNeedToSendFinishedDeviceScan = true;
868 if (--capacity == 0) {
869 break;
870 }
871 }
872
873 if (mNeedToSendFinishedDeviceScan) {
874 mNeedToSendFinishedDeviceScan = false;
875 event->when = now;
876 event->type = FINISHED_DEVICE_SCAN;
877 event += 1;
878 if (--capacity == 0) {
879 break;
880 }
881 }
882
883 // Grab the next input event.
884 bool deviceChanged = false;
885 while (mPendingEventIndex < mPendingEventCount) {
886 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700887 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800888 if (eventItem.events & EPOLLIN) {
889 mPendingINotify = true;
890 } else {
891 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
892 }
893 continue;
894 }
895
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700896 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800897 if (eventItem.events & EPOLLIN) {
898 ALOGV("awoken after wake()");
899 awoken = true;
900 char buffer[16];
901 ssize_t nRead;
902 do {
903 nRead = read(mWakeReadPipeFd, buffer, sizeof(buffer));
904 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(buffer));
905 } else {
906 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700907 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800908 }
909 continue;
910 }
911
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700912 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700913 if (!device) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700914 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
915 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700916 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800917 continue;
918 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700919 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
920 if (eventItem.events & EPOLLIN) {
921 size_t numFrames = device->videoDevice->readAndQueueFrames();
922 if (numFrames == 0) {
923 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700924 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700925 }
926 } else if (eventItem.events & EPOLLHUP) {
927 // TODO(b/121395353) - consider adding EPOLLRDHUP
928 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700929 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700930 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
931 device->videoDevice = nullptr;
932 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700933 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
934 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700935 ALOG_ASSERT(!DEBUG);
936 }
937 continue;
938 }
939 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -0800940 if (eventItem.events & EPOLLIN) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700941 int32_t readSize =
942 read(device->fd, readBuffer, sizeof(struct input_event) * capacity);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800943 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
944 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -0700945 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700946 " bufferSize: %zu capacity: %zu errno: %d)\n",
947 device->fd, readSize, bufferSize, capacity, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800948 deviceChanged = true;
949 closeDeviceLocked(device);
950 } else if (readSize < 0) {
951 if (errno != EAGAIN && errno != EINTR) {
952 ALOGW("could not get event (errno=%d)", errno);
953 }
954 } else if ((readSize % sizeof(struct input_event)) != 0) {
955 ALOGE("could not get event (wrong size: %d)", readSize);
956 } else {
957 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
958
959 size_t count = size_t(readSize) / sizeof(struct input_event);
960 for (size_t i = 0; i < count; i++) {
961 struct input_event& iev = readBuffer[i];
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800962 event->when = processEventTimestamp(iev);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800963 event->deviceId = deviceId;
964 event->type = iev.type;
965 event->code = iev.code;
966 event->value = iev.value;
967 event += 1;
968 capacity -= 1;
969 }
970 if (capacity == 0) {
971 // The result buffer is full. Reset the pending event index
972 // so we will try to read the device again on the next iteration.
973 mPendingEventIndex -= 1;
974 break;
975 }
976 }
977 } else if (eventItem.events & EPOLLHUP) {
978 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700979 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800980 deviceChanged = true;
981 closeDeviceLocked(device);
982 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700983 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
984 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800985 }
986 }
987
988 // readNotify() will modify the list of devices so this must be done after
989 // processing all other events to ensure that we read all remaining events
990 // before closing the devices.
991 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
992 mPendingINotify = false;
993 readNotifyLocked();
994 deviceChanged = true;
995 }
996
997 // Report added or removed devices immediately.
998 if (deviceChanged) {
999 continue;
1000 }
1001
1002 // Return now if we have collected any events or if we were explicitly awoken.
1003 if (event != buffer || awoken) {
1004 break;
1005 }
1006
1007 // Poll for events. Mind the wake lock dance!
1008 // We hold a wake lock at all times except during epoll_wait(). This works due to some
1009 // subtle choreography. When a device driver has pending (unread) events, it acquires
1010 // a kernel wake lock. However, once the last pending event has been read, the device
1011 // driver will release the kernel wake lock. To prevent the system from going to sleep
1012 // when this happens, the EventHub holds onto its own user wake lock while the client
1013 // is processing events. Thus the system can only sleep if there are no events
1014 // pending or currently being processed.
1015 //
1016 // The timeout is advisory only. If the device is asleep, it will not wake just to
1017 // service the timeout.
1018 mPendingEventIndex = 0;
1019
1020 mLock.unlock(); // release lock before poll, must be before release_wake_lock
1021 release_wake_lock(WAKE_LOCK_ID);
1022
1023 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1024
1025 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
1026 mLock.lock(); // reacquire lock after poll, must be after acquire_wake_lock
1027
1028 if (pollResult == 0) {
1029 // Timed out.
1030 mPendingEventCount = 0;
1031 break;
1032 }
1033
1034 if (pollResult < 0) {
1035 // An error occurred.
1036 mPendingEventCount = 0;
1037
1038 // Sleep after errors to avoid locking up the system.
1039 // Hopefully the error is transient.
1040 if (errno != EINTR) {
1041 ALOGW("poll failed (errno=%d)\n", errno);
1042 usleep(100000);
1043 }
1044 } else {
1045 // Some events occurred.
1046 mPendingEventCount = size_t(pollResult);
1047 }
1048 }
1049
1050 // All done, return the number of events we read.
1051 return event - buffer;
1052}
1053
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001054std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
1055 AutoMutex _l(mLock);
1056
1057 Device* device = getDeviceLocked(deviceId);
1058 if (!device || !device->videoDevice) {
1059 return {};
1060 }
1061 return device->videoDevice->consumeFrames();
1062}
1063
Michael Wrightd02c5b62014-02-10 15:10:22 -08001064void EventHub::wake() {
1065 ALOGV("wake() called");
1066
1067 ssize_t nWrite;
1068 do {
1069 nWrite = write(mWakeWritePipeFd, "W", 1);
1070 } while (nWrite == -1 && errno == EINTR);
1071
1072 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001073 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001074 }
1075}
1076
1077void EventHub::scanDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001078 status_t result = scanDirLocked(DEVICE_PATH);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001079 if (result < 0) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001080 ALOGE("scan dir failed for %s", DEVICE_PATH);
1081 }
Philip Quinn39b81682019-01-09 22:20:39 -08001082 if (isV4lScanningEnabled()) {
1083 result = scanVideoDirLocked(VIDEO_DEVICE_PATH);
1084 if (result != OK) {
1085 ALOGE("scan video dir failed for %s", VIDEO_DEVICE_PATH);
1086 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001087 }
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001088 if (mDevices.indexOfKey(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) < 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001089 createVirtualKeyboardLocked();
1090 }
1091}
1092
1093// ----------------------------------------------------------------------------
1094
1095static bool containsNonZeroByte(const uint8_t* array, uint32_t startIndex, uint32_t endIndex) {
1096 const uint8_t* end = array + endIndex;
1097 array += startIndex;
1098 while (array != end) {
1099 if (*(array++) != 0) {
1100 return true;
1101 }
1102 }
1103 return false;
1104}
1105
1106static const int32_t GAMEPAD_KEYCODES[] = {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001107 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C, //
1108 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z, //
1109 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1, //
1110 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2, //
1111 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR, //
1112 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE, //
Michael Wrightd02c5b62014-02-10 15:10:22 -08001113};
1114
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001115status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001116 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001117 struct epoll_event eventItem = {};
1118 eventItem.events = EPOLLIN | EPOLLWAKEUP;
1119 eventItem.data.fd = fd;
1120 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1121 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001122 return -errno;
1123 }
1124 return OK;
1125}
1126
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001127status_t EventHub::unregisterFdFromEpoll(int fd) {
1128 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
1129 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
1130 return -errno;
1131 }
1132 return OK;
1133}
1134
1135status_t EventHub::registerDeviceForEpollLocked(Device* device) {
1136 if (device == nullptr) {
1137 if (DEBUG) {
1138 LOG_ALWAYS_FATAL("Cannot call registerDeviceForEpollLocked with null Device");
1139 }
1140 return BAD_VALUE;
1141 }
1142 status_t result = registerFdForEpoll(device->fd);
1143 if (result != OK) {
1144 ALOGE("Could not add input device fd to epoll for device %" PRId32, device->id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001145 return result;
1146 }
1147 if (device->videoDevice) {
1148 registerVideoDeviceForEpollLocked(*device->videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001149 }
1150 return result;
1151}
1152
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001153void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
1154 status_t result = registerFdForEpoll(videoDevice.getFd());
1155 if (result != OK) {
1156 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
1157 }
1158}
1159
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001160status_t EventHub::unregisterDeviceFromEpollLocked(Device* device) {
1161 if (device->hasValidFd()) {
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001162 status_t result = unregisterFdFromEpoll(device->fd);
1163 if (result != OK) {
1164 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device->id);
1165 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001166 }
1167 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001168 if (device->videoDevice) {
1169 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1170 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001171 return OK;
1172}
1173
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001174void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
1175 if (videoDevice.hasValidFd()) {
1176 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
1177 if (result != OK) {
1178 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001179 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001180 }
1181 }
1182}
1183
1184status_t EventHub::openDeviceLocked(const char* devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001185 char buffer[80];
1186
1187 ALOGV("Opening device: %s", devicePath);
1188
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001189 int fd = open(devicePath, O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001190 if (fd < 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001191 ALOGE("could not open %s, %s\n", devicePath, strerror(errno));
1192 return -1;
1193 }
1194
1195 InputDeviceIdentifier identifier;
1196
1197 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001198 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001199 ALOGE("Could not get device name for %s: %s", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001200 } else {
1201 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001202 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001203 }
1204
1205 // Check to see if the device is on our excluded list
1206 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001207 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001208 if (identifier.name == item) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001209 ALOGI("ignoring event id %s driver %s\n", devicePath, item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001210 close(fd);
1211 return -1;
1212 }
1213 }
1214
1215 // Get device driver version.
1216 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001217 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001218 ALOGE("could not get driver version for %s, %s\n", devicePath, strerror(errno));
1219 close(fd);
1220 return -1;
1221 }
1222
1223 // Get device identifier.
1224 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001225 if (ioctl(fd, EVIOCGID, &inputId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001226 ALOGE("could not get device input id for %s, %s\n", devicePath, strerror(errno));
1227 close(fd);
1228 return -1;
1229 }
1230 identifier.bus = inputId.bustype;
1231 identifier.product = inputId.product;
1232 identifier.vendor = inputId.vendor;
1233 identifier.version = inputId.version;
1234
1235 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001236 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
1237 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001238 } else {
1239 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001240 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001241 }
1242
1243 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001244 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
1245 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001246 } else {
1247 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001248 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001249 }
1250
1251 // Fill in the descriptor.
1252 assignDescriptorLocked(identifier);
1253
Michael Wrightd02c5b62014-02-10 15:10:22 -08001254 // Allocate device. (The device object takes ownership of the fd at this point.)
1255 int32_t deviceId = mNextDeviceId++;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001256 Device* device = new Device(fd, deviceId, devicePath, identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001257
1258 ALOGV("add device %d: %s\n", deviceId, devicePath);
1259 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001260 " vendor %04x\n"
1261 " product %04x\n"
1262 " version %04x\n",
1263 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001264 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
1265 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
1266 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
1267 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001268 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
1269 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001270
1271 // Load the configuration file for the device.
1272 loadConfigurationLocked(device);
1273
1274 // Figure out the kinds of events the device reports.
1275 ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(device->keyBitmask)), device->keyBitmask);
1276 ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(device->absBitmask)), device->absBitmask);
1277 ioctl(fd, EVIOCGBIT(EV_REL, sizeof(device->relBitmask)), device->relBitmask);
1278 ioctl(fd, EVIOCGBIT(EV_SW, sizeof(device->swBitmask)), device->swBitmask);
1279 ioctl(fd, EVIOCGBIT(EV_LED, sizeof(device->ledBitmask)), device->ledBitmask);
1280 ioctl(fd, EVIOCGBIT(EV_FF, sizeof(device->ffBitmask)), device->ffBitmask);
1281 ioctl(fd, EVIOCGPROP(sizeof(device->propBitmask)), device->propBitmask);
1282
1283 // See if this is a keyboard. Ignore everything in the button range except for
1284 // joystick and gamepad buttons which are handled like keyboards for the most part.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001285 bool haveKeyboardKeys =
1286 containsNonZeroByte(device->keyBitmask, 0, sizeof_bit_array(BTN_MISC)) ||
1287 containsNonZeroByte(device->keyBitmask, sizeof_bit_array(KEY_OK),
1288 sizeof_bit_array(KEY_MAX + 1));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001289 bool haveGamepadButtons = containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_MISC),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001290 sizeof_bit_array(BTN_MOUSE)) ||
1291 containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_JOYSTICK),
1292 sizeof_bit_array(BTN_DIGI));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001293 if (haveKeyboardKeys || haveGamepadButtons) {
1294 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1295 }
1296
1297 // See if this is a cursor device such as a trackball or mouse.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001298 if (test_bit(BTN_MOUSE, device->keyBitmask) && test_bit(REL_X, device->relBitmask) &&
1299 test_bit(REL_Y, device->relBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001300 device->classes |= INPUT_DEVICE_CLASS_CURSOR;
1301 }
1302
Prashant Malani1941ff52015-08-11 18:29:28 -07001303 // See if this is a rotary encoder type device.
1304 String8 deviceType = String8();
1305 if (device->configuration &&
1306 device->configuration->tryGetProperty(String8("device.type"), deviceType)) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001307 if (!deviceType.compare(String8("rotaryEncoder"))) {
1308 device->classes |= INPUT_DEVICE_CLASS_ROTARY_ENCODER;
1309 }
Prashant Malani1941ff52015-08-11 18:29:28 -07001310 }
1311
Michael Wrightd02c5b62014-02-10 15:10:22 -08001312 // See if this is a touch pad.
1313 // Is this a new modern multi-touch driver?
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001314 if (test_bit(ABS_MT_POSITION_X, device->absBitmask) &&
1315 test_bit(ABS_MT_POSITION_Y, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001316 // Some joysticks such as the PS3 controller report axes that conflict
1317 // with the ABS_MT range. Try to confirm that the device really is
1318 // a touch screen.
1319 if (test_bit(BTN_TOUCH, device->keyBitmask) || !haveGamepadButtons) {
1320 device->classes |= INPUT_DEVICE_CLASS_TOUCH | INPUT_DEVICE_CLASS_TOUCH_MT;
1321 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001322 // Is this an old style single-touch driver?
1323 } else if (test_bit(BTN_TOUCH, device->keyBitmask) && test_bit(ABS_X, device->absBitmask) &&
1324 test_bit(ABS_Y, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001325 device->classes |= INPUT_DEVICE_CLASS_TOUCH;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001326 // Is this a BT stylus?
Michael Wright842500e2015-03-13 17:32:02 -07001327 } else if ((test_bit(ABS_PRESSURE, device->absBitmask) ||
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001328 test_bit(BTN_TOUCH, device->keyBitmask)) &&
1329 !test_bit(ABS_X, device->absBitmask) && !test_bit(ABS_Y, device->absBitmask)) {
Michael Wright842500e2015-03-13 17:32:02 -07001330 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
1331 // Keyboard will try to claim some of the buttons but we really want to reserve those so we
1332 // can fuse it with the touch screen data, so just take them back. Note this means an
1333 // external stylus cannot also be a keyboard device.
1334 device->classes &= ~INPUT_DEVICE_CLASS_KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001335 }
1336
1337 // See if this device is a joystick.
1338 // Assumes that joysticks always have gamepad buttons in order to distinguish them
1339 // from other devices such as accelerometers that also have absolute axes.
1340 if (haveGamepadButtons) {
1341 uint32_t assumedClasses = device->classes | INPUT_DEVICE_CLASS_JOYSTICK;
1342 for (int i = 0; i <= ABS_MAX; i++) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001343 if (test_bit(i, device->absBitmask) &&
1344 (getAbsAxisUsage(i, assumedClasses) & INPUT_DEVICE_CLASS_JOYSTICK)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001345 device->classes = assumedClasses;
1346 break;
1347 }
1348 }
1349 }
1350
1351 // Check whether this device has switches.
1352 for (int i = 0; i <= SW_MAX; i++) {
1353 if (test_bit(i, device->swBitmask)) {
1354 device->classes |= INPUT_DEVICE_CLASS_SWITCH;
1355 break;
1356 }
1357 }
1358
1359 // Check whether this device supports the vibrator.
1360 if (test_bit(FF_RUMBLE, device->ffBitmask)) {
1361 device->classes |= INPUT_DEVICE_CLASS_VIBRATOR;
1362 }
1363
1364 // Configure virtual keys.
1365 if ((device->classes & INPUT_DEVICE_CLASS_TOUCH)) {
1366 // Load the virtual keys for the touch screen, if any.
1367 // We do this now so that we can make sure to load the keymap if necessary.
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001368 bool success = loadVirtualKeyMapLocked(device);
1369 if (success) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001370 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1371 }
1372 }
1373
1374 // Load the key map.
1375 // We need to do this for joysticks too because the key layout may specify axes.
1376 status_t keyMapStatus = NAME_NOT_FOUND;
1377 if (device->classes & (INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_JOYSTICK)) {
1378 // Load the keymap for the device.
1379 keyMapStatus = loadKeyMapLocked(device);
1380 }
1381
1382 // Configure the keyboard, gamepad or virtual keyboard.
1383 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1384 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001385 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
1386 isEligibleBuiltInKeyboard(device->identifier, device->configuration, &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001387 mBuiltInKeyboardId = device->id;
1388 }
1389
1390 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
1391 if (hasKeycodeLocked(device, AKEYCODE_Q)) {
1392 device->classes |= INPUT_DEVICE_CLASS_ALPHAKEY;
1393 }
1394
1395 // See if this device has a DPAD.
1396 if (hasKeycodeLocked(device, AKEYCODE_DPAD_UP) &&
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001397 hasKeycodeLocked(device, AKEYCODE_DPAD_DOWN) &&
1398 hasKeycodeLocked(device, AKEYCODE_DPAD_LEFT) &&
1399 hasKeycodeLocked(device, AKEYCODE_DPAD_RIGHT) &&
1400 hasKeycodeLocked(device, AKEYCODE_DPAD_CENTER)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001401 device->classes |= INPUT_DEVICE_CLASS_DPAD;
1402 }
1403
1404 // See if this device has a gamepad.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001405 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES) / sizeof(GAMEPAD_KEYCODES[0]); i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001406 if (hasKeycodeLocked(device, GAMEPAD_KEYCODES[i])) {
1407 device->classes |= INPUT_DEVICE_CLASS_GAMEPAD;
1408 break;
1409 }
1410 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001411 }
1412
1413 // If the device isn't recognized as something we handle, don't monitor it.
1414 if (device->classes == 0) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001415 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath,
1416 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001417 delete device;
1418 return -1;
1419 }
1420
Tim Kilbourn063ff532015-04-08 10:26:18 -07001421 // Determine whether the device has a mic.
1422 if (deviceHasMicLocked(device)) {
1423 device->classes |= INPUT_DEVICE_CLASS_MIC;
1424 }
1425
Michael Wrightd02c5b62014-02-10 15:10:22 -08001426 // Determine whether the device is external or internal.
1427 if (isExternalDeviceLocked(device)) {
1428 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL;
1429 }
1430
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001431 if (device->classes & (INPUT_DEVICE_CLASS_JOYSTICK | INPUT_DEVICE_CLASS_DPAD) &&
1432 device->classes & INPUT_DEVICE_CLASS_GAMEPAD) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001433 device->controllerNumber = getNextControllerNumberLocked(device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001434 setLedForControllerLocked(device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001435 }
1436
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001437 // Find a matching video device by comparing device names
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001438 // This should be done before registerDeviceForEpollLocked, so that both fds are added to epoll
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001439 for (std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
1440 if (device->identifier.name == videoDevice->getName()) {
1441 device->videoDevice = std::move(videoDevice);
1442 break;
1443 }
1444 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001445 mUnattachedVideoDevices
1446 .erase(std::remove_if(mUnattachedVideoDevices.begin(), mUnattachedVideoDevices.end(),
1447 [](const std::unique_ptr<TouchVideoDevice>& videoDevice) {
1448 return videoDevice == nullptr;
1449 }),
1450 mUnattachedVideoDevices.end());
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001451
1452 if (registerDeviceForEpollLocked(device) != OK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001453 delete device;
1454 return -1;
1455 }
1456
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001457 configureFd(device);
1458
1459 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=0x%x, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001460 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
1461 deviceId, fd, devicePath, device->identifier.name.c_str(), device->classes,
1462 device->configurationFile.c_str(), device->keyMap.keyLayoutFile.c_str(),
1463 device->keyMap.keyCharacterMapFile.c_str(), toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001464
1465 addDeviceLocked(device);
1466 return OK;
1467}
1468
1469void EventHub::configureFd(Device* device) {
1470 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
1471 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1472 // Disable kernel key repeat since we handle it ourselves
1473 unsigned int repeatRate[] = {0, 0};
1474 if (ioctl(device->fd, EVIOCSREP, repeatRate)) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001475 ALOGW("Unable to disable kernel key repeat for %s: %s", device->path.c_str(),
1476 strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001477 }
1478 }
1479
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
1481 // associated with input events. This is important because the input system
1482 // uses the timestamps extensively and assumes they were recorded using the monotonic
1483 // clock.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001484 int clockId = CLOCK_MONOTONIC;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001485 bool usingClockIoctl = !ioctl(device->fd, EVIOCSCLOCKID, &clockId);
Atif Niyaz4180aa42019-05-10 16:27:48 -07001486 ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001487}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001488
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001489void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
1490 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
1491 if (!videoDevice) {
1492 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
1493 return;
1494 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001495 // Transfer ownership of this video device to a matching input device
1496 for (size_t i = 0; i < mDevices.size(); i++) {
1497 Device* device = mDevices.valueAt(i);
1498 if (videoDevice->getName() == device->identifier.name) {
1499 device->videoDevice = std::move(videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001500 if (device->enabled) {
1501 registerVideoDeviceForEpollLocked(*device->videoDevice);
1502 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001503 return;
1504 }
1505 }
1506
1507 // Couldn't find a matching input device, so just add it to a temporary holding queue.
1508 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001509 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001510 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001511 mUnattachedVideoDevices.push_back(std::move(videoDevice));
1512}
1513
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001514bool EventHub::isDeviceEnabled(int32_t deviceId) {
1515 AutoMutex _l(mLock);
1516 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001517 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001518 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1519 return false;
1520 }
1521 return device->enabled;
1522}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001523
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001524status_t EventHub::enableDevice(int32_t deviceId) {
1525 AutoMutex _l(mLock);
1526 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001527 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001528 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1529 return BAD_VALUE;
1530 }
1531 if (device->enabled) {
1532 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
1533 return OK;
1534 }
1535 status_t result = device->enable();
1536 if (result != OK) {
1537 ALOGE("Failed to enable device %" PRId32, deviceId);
1538 return result;
1539 }
1540
1541 configureFd(device);
1542
1543 return registerDeviceForEpollLocked(device);
1544}
1545
1546status_t EventHub::disableDevice(int32_t deviceId) {
1547 AutoMutex _l(mLock);
1548 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001549 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001550 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1551 return BAD_VALUE;
1552 }
1553 if (!device->enabled) {
1554 ALOGW("Duplicate call to %s, input device already disabled", __func__);
1555 return OK;
1556 }
1557 unregisterDeviceFromEpollLocked(device);
1558 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001559}
1560
1561void EventHub::createVirtualKeyboardLocked() {
1562 InputDeviceIdentifier identifier;
1563 identifier.name = "Virtual";
1564 identifier.uniqueId = "<virtual>";
1565 assignDescriptorLocked(identifier);
1566
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001567 Device* device =
1568 new Device(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>", identifier);
1569 device->classes = INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_ALPHAKEY |
1570 INPUT_DEVICE_CLASS_DPAD | INPUT_DEVICE_CLASS_VIRTUAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001571 loadKeyMapLocked(device);
1572 addDeviceLocked(device);
1573}
1574
1575void EventHub::addDeviceLocked(Device* device) {
1576 mDevices.add(device->id, device);
1577 device->next = mOpeningDevices;
1578 mOpeningDevices = device;
1579}
1580
1581void EventHub::loadConfigurationLocked(Device* device) {
1582 device->configurationFile = getInputDeviceConfigurationFilePathByDeviceIdentifier(
1583 device->identifier, INPUT_DEVICE_CONFIGURATION_FILE_TYPE_CONFIGURATION);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001584 if (device->configurationFile.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001585 ALOGD("No input device configuration file found for device '%s'.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001586 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001587 } else {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001588 status_t status = PropertyMap::load(String8(device->configurationFile.c_str()),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001589 &device->configuration);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001590 if (status) {
1591 ALOGE("Error loading input device configuration file for device '%s'. "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001592 "Using default configuration.",
1593 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001594 }
1595 }
1596}
1597
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001598bool EventHub::loadVirtualKeyMapLocked(Device* device) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001599 // The virtual key map is supplied by the kernel as a system board property file.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001600 std::string path;
1601 path += "/sys/board_properties/virtualkeys.";
Siarhei Vishniakoub45635c2019-02-20 19:22:09 -06001602 path += device->identifier.getCanonicalName();
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001603 if (access(path.c_str(), R_OK)) {
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001604 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001605 }
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001606 device->virtualKeyMap = VirtualKeyMap::load(path);
1607 return device->virtualKeyMap != nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001608}
1609
1610status_t EventHub::loadKeyMapLocked(Device* device) {
1611 return device->keyMap.load(device->identifier, device->configuration);
1612}
1613
1614bool EventHub::isExternalDeviceLocked(Device* device) {
1615 if (device->configuration) {
1616 bool value;
1617 if (device->configuration->tryGetProperty(String8("device.internal"), value)) {
1618 return !value;
1619 }
1620 }
1621 return device->identifier.bus == BUS_USB || device->identifier.bus == BUS_BLUETOOTH;
1622}
1623
Tim Kilbourn063ff532015-04-08 10:26:18 -07001624bool EventHub::deviceHasMicLocked(Device* device) {
1625 if (device->configuration) {
1626 bool value;
1627 if (device->configuration->tryGetProperty(String8("audio.mic"), value)) {
1628 return value;
1629 }
1630 }
1631 return false;
1632}
1633
Michael Wrightd02c5b62014-02-10 15:10:22 -08001634int32_t EventHub::getNextControllerNumberLocked(Device* device) {
1635 if (mControllerNumbers.isFull()) {
1636 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001637 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001638 return 0;
1639 }
1640 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
1641 // one
1642 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
1643}
1644
1645void EventHub::releaseControllerNumberLocked(Device* device) {
1646 int32_t num = device->controllerNumber;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001647 device->controllerNumber = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001648 if (num == 0) {
1649 return;
1650 }
1651 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
1652}
1653
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001654void EventHub::setLedForControllerLocked(Device* device) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001655 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
1656 setLedStateLocked(device, ALED_CONTROLLER_1 + i, device->controllerNumber == i + 1);
1657 }
1658}
1659
1660bool EventHub::hasKeycodeLocked(Device* device, int keycode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001661 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001662 return false;
1663 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001664
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001665 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001666 device->keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes);
1667 const size_t N = scanCodes.size();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001668 for (size_t i = 0; i < N && i <= KEY_MAX; i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001669 int32_t sc = scanCodes[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001670 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, device->keyBitmask)) {
1671 return true;
1672 }
1673 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001674
Michael Wrightd02c5b62014-02-10 15:10:22 -08001675 return false;
1676}
1677
1678status_t EventHub::mapLed(Device* device, int32_t led, int32_t* outScanCode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001679 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001680 return NAME_NOT_FOUND;
1681 }
1682
1683 int32_t scanCode;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001684 if (device->keyMap.keyLayoutMap->findScanCodeForLed(led, &scanCode) != NAME_NOT_FOUND) {
1685 if (scanCode >= 0 && scanCode <= LED_MAX && test_bit(scanCode, device->ledBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001686 *outScanCode = scanCode;
1687 return NO_ERROR;
1688 }
1689 }
1690 return NAME_NOT_FOUND;
1691}
1692
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001693void EventHub::closeDeviceByPathLocked(const char* devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001694 Device* device = getDeviceByPathLocked(devicePath);
1695 if (device) {
1696 closeDeviceLocked(device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001697 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001698 }
1699 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001700}
1701
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001702/**
1703 * Find the video device by filename, and close it.
1704 * The video device is closed by path during an inotify event, where we don't have the
1705 * additional context about the video device fd, or the associated input device.
1706 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001707void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001708 // A video device may be owned by an existing input device, or it may be stored in
1709 // the mUnattachedVideoDevices queue. Check both locations.
1710 for (size_t i = 0; i < mDevices.size(); i++) {
1711 Device* device = mDevices.valueAt(i);
1712 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001713 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001714 device->videoDevice = nullptr;
1715 return;
1716 }
1717 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001718 mUnattachedVideoDevices
1719 .erase(std::remove_if(mUnattachedVideoDevices.begin(), mUnattachedVideoDevices.end(),
1720 [&devicePath](
1721 const std::unique_ptr<TouchVideoDevice>& videoDevice) {
1722 return videoDevice->getPath() == devicePath;
1723 }),
1724 mUnattachedVideoDevices.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001725}
1726
1727void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001728 mUnattachedVideoDevices.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001729 while (mDevices.size() > 0) {
1730 closeDeviceLocked(mDevices.valueAt(mDevices.size() - 1));
1731 }
1732}
1733
1734void EventHub::closeDeviceLocked(Device* device) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001735 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=0x%x", device->path.c_str(),
1736 device->identifier.name.c_str(), device->id, device->fd, device->classes);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001737
1738 if (device->id == mBuiltInKeyboardId) {
1739 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001740 device->path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001741 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
1742 }
1743
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001744 unregisterDeviceFromEpollLocked(device);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001745 if (device->videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001746 // This must be done after the video device is removed from epoll
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001747 mUnattachedVideoDevices.push_back(std::move(device->videoDevice));
1748 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001749
1750 releaseControllerNumberLocked(device);
1751
1752 mDevices.removeItem(device->id);
1753 device->close();
1754
1755 // Unlink for opening devices list if it is present.
Yi Kong9b14ac62018-07-17 13:48:38 -07001756 Device* pred = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001757 bool found = false;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001758 for (Device* entry = mOpeningDevices; entry != nullptr;) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001759 if (entry == device) {
1760 found = true;
1761 break;
1762 }
1763 pred = entry;
1764 entry = entry->next;
1765 }
1766 if (found) {
1767 // Unlink the device from the opening devices list then delete it.
1768 // We don't need to tell the client that the device was closed because
1769 // it does not even know it was opened in the first place.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001770 ALOGI("Device %s was immediately closed after opening.", device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001771 if (pred) {
1772 pred->next = device->next;
1773 } else {
1774 mOpeningDevices = device->next;
1775 }
1776 delete device;
1777 } else {
1778 // Link into closing devices list.
1779 // The device will be deleted later after we have informed the client.
1780 device->next = mClosingDevices;
1781 mClosingDevices = device;
1782 }
1783}
1784
1785status_t EventHub::readNotifyLocked() {
1786 int res;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001787 char event_buf[512];
1788 int event_size;
1789 int event_pos = 0;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001790 struct inotify_event* event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001791
1792 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
1793 res = read(mINotifyFd, event_buf, sizeof(event_buf));
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001794 if (res < (int)sizeof(*event)) {
1795 if (errno == EINTR) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001796 ALOGW("could not get event, %s\n", strerror(errno));
1797 return -1;
1798 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001800 while (res >= (int)sizeof(*event)) {
1801 event = (struct inotify_event*)(event_buf + event_pos);
1802 if (event->len) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001803 if (event->wd == mInputWd) {
1804 std::string filename = StringPrintf("%s/%s", DEVICE_PATH, event->name);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001805 if (event->mask & IN_CREATE) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001806 openDeviceLocked(filename.c_str());
1807 } else {
1808 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
1809 closeDeviceByPathLocked(filename.c_str());
1810 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001811 } else if (event->wd == mVideoWd) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001812 if (isV4lTouchNode(event->name)) {
1813 std::string filename = StringPrintf("%s/%s", VIDEO_DEVICE_PATH, event->name);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001814 if (event->mask & IN_CREATE) {
1815 openVideoDeviceLocked(filename);
1816 } else {
1817 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
1818 closeVideoDeviceByPathLocked(filename);
1819 }
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001820 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001821 } else {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001822 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event->wd);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001823 }
1824 }
1825 event_size = sizeof(*event) + event->len;
1826 res -= event_size;
1827 event_pos += event_size;
1828 }
1829 return 0;
1830}
1831
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001832status_t EventHub::scanDirLocked(const char* dirname) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001833 char devname[PATH_MAX];
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001834 char* filename;
1835 DIR* dir;
1836 struct dirent* de;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001837 dir = opendir(dirname);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001838 if (dir == nullptr) return -1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001839 strcpy(devname, dirname);
1840 filename = devname + strlen(devname);
1841 *filename++ = '/';
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001842 while ((de = readdir(dir))) {
1843 if (de->d_name[0] == '.' &&
1844 (de->d_name[1] == '\0' || (de->d_name[1] == '.' && de->d_name[2] == '\0')))
Michael Wrightd02c5b62014-02-10 15:10:22 -08001845 continue;
1846 strcpy(filename, de->d_name);
1847 openDeviceLocked(devname);
1848 }
1849 closedir(dir);
1850 return 0;
1851}
1852
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001853/**
1854 * Look for all dirname/v4l-touch* devices, and open them.
1855 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001856status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001857 DIR* dir;
1858 struct dirent* de;
1859 dir = opendir(dirname.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001860 if (!dir) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001861 ALOGE("Could not open video directory %s", dirname.c_str());
1862 return BAD_VALUE;
1863 }
1864
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001865 while ((de = readdir(dir))) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001866 const char* name = de->d_name;
1867 if (isV4lTouchNode(name)) {
1868 ALOGI("Found touch video device %s", name);
1869 openVideoDeviceLocked(dirname + "/" + name);
1870 }
1871 }
1872 closedir(dir);
1873 return OK;
1874}
1875
Michael Wrightd02c5b62014-02-10 15:10:22 -08001876void EventHub::requestReopenDevices() {
1877 ALOGV("requestReopenDevices() called");
1878
1879 AutoMutex _l(mLock);
1880 mNeedToReopenDevices = true;
1881}
1882
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001883void EventHub::dump(std::string& dump) {
1884 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001885
1886 { // acquire lock
1887 AutoMutex _l(mLock);
1888
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001889 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001890
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001891 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001892
1893 for (size_t i = 0; i < mDevices.size(); i++) {
1894 const Device* device = mDevices.valueAt(i);
1895 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001896 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001897 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001898 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001899 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001900 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001901 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001902 dump += StringPrintf(INDENT3 "Classes: 0x%08x\n", device->classes);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001903 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001904 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001905 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
1906 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001907 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001908 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001909 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001910 "product=0x%04x, version=0x%04x\n",
1911 device->identifier.bus, device->identifier.vendor,
1912 device->identifier.product, device->identifier.version);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001913 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001914 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001915 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001916 device->keyMap.keyCharacterMapFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001917 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001918 device->configurationFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001919 dump += StringPrintf(INDENT3 "HaveKeyboardLayoutOverlay: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001920 toString(device->overlayKeyMap != nullptr));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001921 dump += INDENT3 "VideoDevice: ";
1922 if (device->videoDevice) {
1923 dump += device->videoDevice->dump() + "\n";
1924 } else {
1925 dump += "<none>\n";
1926 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001927 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001928
1929 dump += INDENT "Unattached video devices:\n";
1930 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
1931 dump += INDENT2 + videoDevice->dump() + "\n";
1932 }
1933 if (mUnattachedVideoDevices.empty()) {
1934 dump += INDENT2 "<none>\n";
1935 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001936 } // release lock
1937}
1938
1939void EventHub::monitor() {
1940 // Acquire and release the lock to ensure that the event hub has not deadlocked.
1941 mLock.lock();
1942 mLock.unlock();
1943}
1944
Michael Wrightd02c5b62014-02-10 15:10:22 -08001945}; // namespace android