blob: 0544ec16c578dca78843c092f1897148655b29bd [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>
28#include <sys/limits.h>
29#include <sys/inotify.h>
30#include <sys/ioctl.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070031#include <sys/utsname.h>
32#include <unistd.h>
33
Michael Wrightd02c5b62014-02-10 15:10:22 -080034#define LOG_TAG "EventHub"
35
36// #define LOG_NDEBUG 0
37
38#include "EventHub.h"
39
40#include <hardware_legacy/power.h>
41
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080042#include <android-base/stringprintf.h>
Philip Quinn39b81682019-01-09 22:20:39 -080043#include <cutils/properties.h>
Dan Albert677d87e2014-06-16 17:31:28 -070044#include <openssl/sha.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080045#include <utils/Log.h>
46#include <utils/Timers.h>
47#include <utils/threads.h>
48#include <utils/Errors.h>
49
Michael Wrightd02c5b62014-02-10 15:10:22 -080050#include <input/KeyLayoutMap.h>
51#include <input/KeyCharacterMap.h>
52#include <input/VirtualKeyMap.h>
53
Michael Wrightd02c5b62014-02-10 15:10:22 -080054/* this macro is used to tell if "bit" is set in "array"
55 * it selects a byte from the array, and does a boolean AND
56 * operation with a byte that only has the relevant bit set.
57 * eg. to check for the 12th bit, we do (array[1] & 1<<4)
58 */
Chih-Hung Hsieh4a186d42016-05-20 11:33:26 -070059#define test_bit(bit, array) ((array)[(bit)/8] & (1<<((bit)%8)))
Michael Wrightd02c5b62014-02-10 15:10:22 -080060
61/* this macro computes the number of bytes needed to represent a bit array of the specified size */
Chih-Hung Hsieh4a186d42016-05-20 11:33:26 -070062#define sizeof_bit_array(bits) (((bits) + 7) / 8)
Michael Wrightd02c5b62014-02-10 15:10:22 -080063
64#define INDENT " "
65#define INDENT2 " "
66#define INDENT3 " "
67
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080068using android::base::StringPrintf;
69
Michael Wrightd02c5b62014-02-10 15:10:22 -080070namespace android {
71
Siarhei Vishniakou25920312018-12-12 15:24:44 -080072static constexpr bool DEBUG = false;
73
Michael Wrightd02c5b62014-02-10 15:10:22 -080074static const char *WAKE_LOCK_ID = "KeyEvents";
75static const char *DEVICE_PATH = "/dev/input";
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080076// v4l2 devices go directly into /dev
77static const char *VIDEO_DEVICE_PATH = "/dev";
Michael Wrightd02c5b62014-02-10 15:10:22 -080078
Michael Wrightd02c5b62014-02-10 15:10:22 -080079static inline const char* toString(bool value) {
80 return value ? "true" : "false";
81}
82
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010083static std::string sha1(const std::string& in) {
Dan Albert677d87e2014-06-16 17:31:28 -070084 SHA_CTX ctx;
85 SHA1_Init(&ctx);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010086 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
Dan Albert677d87e2014-06-16 17:31:28 -070087 u_char digest[SHA_DIGEST_LENGTH];
88 SHA1_Final(digest, &ctx);
Michael Wrightd02c5b62014-02-10 15:10:22 -080089
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010090 std::string out;
Dan Albert677d87e2014-06-16 17:31:28 -070091 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010092 out += StringPrintf("%02x", digest[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -080093 }
94 return out;
95}
96
97static void getLinuxRelease(int* major, int* minor) {
98 struct utsname info;
99 if (uname(&info) || sscanf(info.release, "%d.%d", major, minor) <= 0) {
100 *major = 0, *minor = 0;
101 ALOGE("Could not get linux version: %s", strerror(errno));
102 }
103}
104
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800105/**
106 * Return true if name matches "v4l-touch*"
107 */
108static bool isV4lTouchNode(const char* name) {
109 return strstr(name, "v4l-touch") == name;
110}
111
Philip Quinn39b81682019-01-09 22:20:39 -0800112/**
113 * Returns true if V4L devices should be scanned.
114 *
115 * The system property ro.input.video_enabled can be used to control whether
116 * EventHub scans and opens V4L devices. As V4L does not support multiple
117 * clients, EventHub effectively blocks access to these devices when it opens
118 * them. This property enables other clients to read these devices for testing
119 * and development.
120 */
121static bool isV4lScanningEnabled() {
122 return property_get_bool("ro.input.video_enabled", true /* default_value */);
123}
124
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800125static nsecs_t processEventTimestamp(const struct input_event& event) {
126 // Use the time specified in the event instead of the current time
127 // so that downstream code can get more accurate estimates of
128 // event dispatch latency from the time the event is enqueued onto
129 // the evdev client buffer.
130 //
131 // The event's timestamp fortuitously uses the same monotonic clock
132 // time base as the rest of Android. The kernel event device driver
133 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
134 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
135 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
136 // system call that also queries ktime_get_ts().
137
138 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.time.tv_sec) +
139 microseconds_to_nanoseconds(event.time.tv_usec);
140 return inputEventTime;
141}
142
Michael Wrightd02c5b62014-02-10 15:10:22 -0800143// --- Global Functions ---
144
145uint32_t getAbsAxisUsage(int32_t axis, uint32_t deviceClasses) {
146 // Touch devices get dibs on touch-related axes.
147 if (deviceClasses & INPUT_DEVICE_CLASS_TOUCH) {
148 switch (axis) {
149 case ABS_X:
150 case ABS_Y:
151 case ABS_PRESSURE:
152 case ABS_TOOL_WIDTH:
153 case ABS_DISTANCE:
154 case ABS_TILT_X:
155 case ABS_TILT_Y:
156 case ABS_MT_SLOT:
157 case ABS_MT_TOUCH_MAJOR:
158 case ABS_MT_TOUCH_MINOR:
159 case ABS_MT_WIDTH_MAJOR:
160 case ABS_MT_WIDTH_MINOR:
161 case ABS_MT_ORIENTATION:
162 case ABS_MT_POSITION_X:
163 case ABS_MT_POSITION_Y:
164 case ABS_MT_TOOL_TYPE:
165 case ABS_MT_BLOB_ID:
166 case ABS_MT_TRACKING_ID:
167 case ABS_MT_PRESSURE:
168 case ABS_MT_DISTANCE:
169 return INPUT_DEVICE_CLASS_TOUCH;
170 }
171 }
172
Michael Wright842500e2015-03-13 17:32:02 -0700173 // External stylus gets the pressure axis
174 if (deviceClasses & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
175 if (axis == ABS_PRESSURE) {
176 return INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
177 }
178 }
179
Michael Wrightd02c5b62014-02-10 15:10:22 -0800180 // Joystick devices get the rest.
181 return deviceClasses & INPUT_DEVICE_CLASS_JOYSTICK;
182}
183
184// --- EventHub::Device ---
185
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100186EventHub::Device::Device(int fd, int32_t id, const std::string& path,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800187 const InputDeviceIdentifier& identifier) :
Yi Kong9b14ac62018-07-17 13:48:38 -0700188 next(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800189 fd(fd), id(id), path(path), identifier(identifier),
Yi Kong9b14ac62018-07-17 13:48:38 -0700190 classes(0), configuration(nullptr), virtualKeyMap(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800191 ffEffectPlaying(false), ffEffectId(-1), controllerNumber(0),
Siarhei Vishniakou88786812018-11-09 15:36:21 -0800192 enabled(true), isVirtual(fd < 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800193 memset(keyBitmask, 0, sizeof(keyBitmask));
194 memset(absBitmask, 0, sizeof(absBitmask));
195 memset(relBitmask, 0, sizeof(relBitmask));
196 memset(swBitmask, 0, sizeof(swBitmask));
197 memset(ledBitmask, 0, sizeof(ledBitmask));
198 memset(ffBitmask, 0, sizeof(ffBitmask));
199 memset(propBitmask, 0, sizeof(propBitmask));
200}
201
202EventHub::Device::~Device() {
203 close();
204 delete configuration;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800205}
206
207void EventHub::Device::close() {
208 if (fd >= 0) {
209 ::close(fd);
210 fd = -1;
211 }
212}
213
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700214status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100215 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700216 if(fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100217 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700218 return -errno;
219 }
220 enabled = true;
221 return OK;
222}
223
224status_t EventHub::Device::disable() {
225 close();
226 enabled = false;
227 return OK;
228}
229
230bool EventHub::Device::hasValidFd() {
231 return !isVirtual && enabled;
232}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800233
234// --- EventHub ---
235
Michael Wrightd02c5b62014-02-10 15:10:22 -0800236const int EventHub::EPOLL_MAX_EVENTS;
237
238EventHub::EventHub(void) :
239 mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD), mNextDeviceId(1), mControllerNumbers(),
Yi Kong9b14ac62018-07-17 13:48:38 -0700240 mOpeningDevices(nullptr), mClosingDevices(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800241 mNeedToSendFinishedDeviceScan(false),
242 mNeedToReopenDevices(false), mNeedToScanDevices(true),
243 mPendingEventCount(0), mPendingEventIndex(0), mPendingINotify(false) {
244 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
245
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800246 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800247 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800248
249 mINotifyFd = inotify_init();
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800250 mInputWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
251 LOG_ALWAYS_FATAL_IF(mInputWd < 0, "Could not register INotify for %s: %s",
252 DEVICE_PATH, strerror(errno));
Philip Quinn39b81682019-01-09 22:20:39 -0800253 if (isV4lScanningEnabled()) {
254 mVideoWd = inotify_add_watch(mINotifyFd, VIDEO_DEVICE_PATH, IN_DELETE | IN_CREATE);
255 LOG_ALWAYS_FATAL_IF(mVideoWd < 0, "Could not register INotify for %s: %s",
256 VIDEO_DEVICE_PATH, strerror(errno));
257 } else {
258 mVideoWd = -1;
259 ALOGI("Video device scanning disabled");
260 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800261
262 struct epoll_event eventItem;
263 memset(&eventItem, 0, sizeof(eventItem));
264 eventItem.events = EPOLLIN;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700265 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800266 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800267 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
268
269 int wakeFds[2];
270 result = pipe(wakeFds);
271 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
272
273 mWakeReadPipeFd = wakeFds[0];
274 mWakeWritePipeFd = wakeFds[1];
275
276 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
277 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
278 errno);
279
280 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
281 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
282 errno);
283
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700284 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800285 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
286 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
287 errno);
288
289 int major, minor;
290 getLinuxRelease(&major, &minor);
291 // EPOLLWAKEUP was introduced in kernel 3.5
292 mUsingEpollWakeup = major > 3 || (major == 3 && minor >= 5);
293}
294
295EventHub::~EventHub(void) {
296 closeAllDevicesLocked();
297
298 while (mClosingDevices) {
299 Device* device = mClosingDevices;
300 mClosingDevices = device->next;
301 delete device;
302 }
303
304 ::close(mEpollFd);
305 ::close(mINotifyFd);
306 ::close(mWakeReadPipeFd);
307 ::close(mWakeWritePipeFd);
308
309 release_wake_lock(WAKE_LOCK_ID);
310}
311
312InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
313 AutoMutex _l(mLock);
314 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700315 if (device == nullptr) return InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800316 return device->identifier;
317}
318
319uint32_t EventHub::getDeviceClasses(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 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800323 return device->classes;
324}
325
326int32_t EventHub::getDeviceControllerNumber(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->controllerNumber;
331}
332
333void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
334 AutoMutex _l(mLock);
335 Device* device = getDeviceLocked(deviceId);
336 if (device && device->configuration) {
337 *outConfiguration = *device->configuration;
338 } else {
339 outConfiguration->clear();
340 }
341}
342
343status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
344 RawAbsoluteAxisInfo* outAxisInfo) const {
345 outAxisInfo->clear();
346
347 if (axis >= 0 && axis <= ABS_MAX) {
348 AutoMutex _l(mLock);
349
350 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700351 if (device && device->hasValidFd() && test_bit(axis, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800352 struct input_absinfo info;
353 if(ioctl(device->fd, EVIOCGABS(axis), &info)) {
354 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100355 axis, device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800356 return -errno;
357 }
358
359 if (info.minimum != info.maximum) {
360 outAxisInfo->valid = true;
361 outAxisInfo->minValue = info.minimum;
362 outAxisInfo->maxValue = info.maximum;
363 outAxisInfo->flat = info.flat;
364 outAxisInfo->fuzz = info.fuzz;
365 outAxisInfo->resolution = info.resolution;
366 }
367 return OK;
368 }
369 }
370 return -1;
371}
372
373bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
374 if (axis >= 0 && axis <= REL_MAX) {
375 AutoMutex _l(mLock);
376
377 Device* device = getDeviceLocked(deviceId);
378 if (device) {
379 return test_bit(axis, device->relBitmask);
380 }
381 }
382 return false;
383}
384
385bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
386 if (property >= 0 && property <= INPUT_PROP_MAX) {
387 AutoMutex _l(mLock);
388
389 Device* device = getDeviceLocked(deviceId);
390 if (device) {
391 return test_bit(property, device->propBitmask);
392 }
393 }
394 return false;
395}
396
397int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
398 if (scanCode >= 0 && scanCode <= KEY_MAX) {
399 AutoMutex _l(mLock);
400
401 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700402 if (device && device->hasValidFd() && test_bit(scanCode, device->keyBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800403 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
404 memset(keyState, 0, sizeof(keyState));
405 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
406 return test_bit(scanCode, keyState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
407 }
408 }
409 }
410 return AKEY_STATE_UNKNOWN;
411}
412
413int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
414 AutoMutex _l(mLock);
415
416 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700417 if (device && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800418 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800419 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode, &scanCodes);
420 if (scanCodes.size() != 0) {
421 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
422 memset(keyState, 0, sizeof(keyState));
423 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
424 for (size_t i = 0; i < scanCodes.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800425 int32_t sc = scanCodes[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -0800426 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, keyState)) {
427 return AKEY_STATE_DOWN;
428 }
429 }
430 return AKEY_STATE_UP;
431 }
432 }
433 }
434 return AKEY_STATE_UNKNOWN;
435}
436
437int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
438 if (sw >= 0 && sw <= SW_MAX) {
439 AutoMutex _l(mLock);
440
441 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700442 if (device && device->hasValidFd() && test_bit(sw, device->swBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800443 uint8_t swState[sizeof_bit_array(SW_MAX + 1)];
444 memset(swState, 0, sizeof(swState));
445 if (ioctl(device->fd, EVIOCGSW(sizeof(swState)), swState) >= 0) {
446 return test_bit(sw, swState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
447 }
448 }
449 }
450 return AKEY_STATE_UNKNOWN;
451}
452
453status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
454 *outValue = 0;
455
456 if (axis >= 0 && axis <= ABS_MAX) {
457 AutoMutex _l(mLock);
458
459 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700460 if (device && device->hasValidFd() && test_bit(axis, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800461 struct input_absinfo info;
462 if(ioctl(device->fd, EVIOCGABS(axis), &info)) {
463 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100464 axis, device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800465 return -errno;
466 }
467
468 *outValue = info.value;
469 return OK;
470 }
471 }
472 return -1;
473}
474
475bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes,
476 const int32_t* keyCodes, uint8_t* outFlags) const {
477 AutoMutex _l(mLock);
478
479 Device* device = getDeviceLocked(deviceId);
480 if (device && device->keyMap.haveKeyLayout()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800481 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800482 for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) {
483 scanCodes.clear();
484
485 status_t err = device->keyMap.keyLayoutMap->findScanCodesForKey(
486 keyCodes[codeIndex], &scanCodes);
487 if (! err) {
488 // check the possible scan codes identified by the layout map against the
489 // map of codes actually emitted by the driver
490 for (size_t sc = 0; sc < scanCodes.size(); sc++) {
491 if (test_bit(scanCodes[sc], device->keyBitmask)) {
492 outFlags[codeIndex] = 1;
493 break;
494 }
495 }
496 }
497 }
498 return true;
499 }
500 return false;
501}
502
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700503status_t EventHub::mapKey(int32_t deviceId,
504 int32_t scanCode, int32_t usageCode, int32_t metaState,
505 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800506 AutoMutex _l(mLock);
507 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700508 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800509
510 if (device) {
511 // Check the key character map first.
512 sp<KeyCharacterMap> kcm = device->getKeyCharacterMap();
Yi Kong9b14ac62018-07-17 13:48:38 -0700513 if (kcm != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800514 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
515 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700516 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800517 }
518 }
519
520 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700521 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800522 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700523 status = NO_ERROR;
524 }
525 }
526
527 if (status == NO_ERROR) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700528 if (kcm != nullptr) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700529 kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState);
530 } else {
531 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800532 }
533 }
534 }
535
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700536 if (status != NO_ERROR) {
537 *outKeycode = 0;
538 *outFlags = 0;
539 *outMetaState = metaState;
540 }
541
542 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800543}
544
545status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
546 AutoMutex _l(mLock);
547 Device* device = getDeviceLocked(deviceId);
548
549 if (device && device->keyMap.haveKeyLayout()) {
550 status_t err = device->keyMap.keyLayoutMap->mapAxis(scanCode, outAxisInfo);
551 if (err == NO_ERROR) {
552 return NO_ERROR;
553 }
554 }
555
556 return NAME_NOT_FOUND;
557}
558
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100559void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800560 AutoMutex _l(mLock);
561
562 mExcludedDevices = devices;
563}
564
565bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
566 AutoMutex _l(mLock);
567 Device* device = getDeviceLocked(deviceId);
568 if (device && scanCode >= 0 && scanCode <= KEY_MAX) {
569 if (test_bit(scanCode, device->keyBitmask)) {
570 return true;
571 }
572 }
573 return false;
574}
575
576bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
577 AutoMutex _l(mLock);
578 Device* device = getDeviceLocked(deviceId);
579 int32_t sc;
580 if (device && mapLed(device, led, &sc) == NO_ERROR) {
581 if (test_bit(sc, device->ledBitmask)) {
582 return true;
583 }
584 }
585 return false;
586}
587
588void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
589 AutoMutex _l(mLock);
590 Device* device = getDeviceLocked(deviceId);
591 setLedStateLocked(device, led, on);
592}
593
594void EventHub::setLedStateLocked(Device* device, int32_t led, bool on) {
595 int32_t sc;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700596 if (device && device->hasValidFd() && mapLed(device, led, &sc) != NAME_NOT_FOUND) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800597 struct input_event ev;
598 ev.time.tv_sec = 0;
599 ev.time.tv_usec = 0;
600 ev.type = EV_LED;
601 ev.code = sc;
602 ev.value = on ? 1 : 0;
603
604 ssize_t nWrite;
605 do {
606 nWrite = write(device->fd, &ev, sizeof(struct input_event));
607 } while (nWrite == -1 && errno == EINTR);
608 }
609}
610
611void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800612 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800613 outVirtualKeys.clear();
614
615 AutoMutex _l(mLock);
616 Device* device = getDeviceLocked(deviceId);
617 if (device && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800618 const std::vector<VirtualKeyDefinition> virtualKeys =
619 device->virtualKeyMap->getVirtualKeys();
620 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800621 }
622}
623
624sp<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
625 AutoMutex _l(mLock);
626 Device* device = getDeviceLocked(deviceId);
627 if (device) {
628 return device->getKeyCharacterMap();
629 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700630 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800631}
632
633bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId,
634 const sp<KeyCharacterMap>& map) {
635 AutoMutex _l(mLock);
636 Device* device = getDeviceLocked(deviceId);
637 if (device) {
638 if (map != device->overlayKeyMap) {
639 device->overlayKeyMap = map;
640 device->combinedKeyMap = KeyCharacterMap::combine(
641 device->keyMap.keyCharacterMap, map);
642 return true;
643 }
644 }
645 return false;
646}
647
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100648static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
649 std::string rawDescriptor;
650 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800651 identifier.product);
652 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100653 if (!identifier.uniqueId.empty()) {
654 rawDescriptor += "uniqueId:";
655 rawDescriptor += identifier.uniqueId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800656 } else if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100657 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800658 }
659
660 if (identifier.vendor == 0 && identifier.product == 0) {
661 // If we don't know the vendor and product id, then the device is probably
662 // built-in so we need to rely on other information to uniquely identify
663 // the input device. Usually we try to avoid relying on the device name or
664 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100665 if (!identifier.name.empty()) {
666 rawDescriptor += "name:";
667 rawDescriptor += identifier.name;
668 } else if (!identifier.location.empty()) {
669 rawDescriptor += "location:";
670 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800671 }
672 }
673 identifier.descriptor = sha1(rawDescriptor);
674 return rawDescriptor;
675}
676
677void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
678 // Compute a device descriptor that uniquely identifies the device.
679 // The descriptor is assumed to be a stable identifier. Its value should not
680 // change between reboots, reconnections, firmware updates or new releases
681 // of Android. In practice we sometimes get devices that cannot be uniquely
682 // identified. In this case we enforce uniqueness between connected devices.
683 // Ideally, we also want the descriptor to be short and relatively opaque.
684
685 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100686 std::string rawDescriptor = generateDescriptor(identifier);
687 if (identifier.uniqueId.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800688 // If it didn't have a unique id check for conflicts and enforce
689 // uniqueness if necessary.
Yi Kong9b14ac62018-07-17 13:48:38 -0700690 while(getDeviceByDescriptorLocked(identifier.descriptor) != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800691 identifier.nonce++;
692 rawDescriptor = generateDescriptor(identifier);
693 }
694 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100695 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
696 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800697}
698
699void EventHub::vibrate(int32_t deviceId, nsecs_t duration) {
700 AutoMutex _l(mLock);
701 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700702 if (device && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800703 ff_effect effect;
704 memset(&effect, 0, sizeof(effect));
705 effect.type = FF_RUMBLE;
706 effect.id = device->ffEffectId;
707 effect.u.rumble.strong_magnitude = 0xc000;
708 effect.u.rumble.weak_magnitude = 0xc000;
709 effect.replay.length = (duration + 999999LL) / 1000000LL;
710 effect.replay.delay = 0;
711 if (ioctl(device->fd, EVIOCSFF, &effect)) {
712 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100713 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800714 return;
715 }
716 device->ffEffectId = effect.id;
717
718 struct input_event ev;
719 ev.time.tv_sec = 0;
720 ev.time.tv_usec = 0;
721 ev.type = EV_FF;
722 ev.code = device->ffEffectId;
723 ev.value = 1;
724 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
725 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100726 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800727 return;
728 }
729 device->ffEffectPlaying = true;
730 }
731}
732
733void EventHub::cancelVibrate(int32_t deviceId) {
734 AutoMutex _l(mLock);
735 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700736 if (device && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800737 if (device->ffEffectPlaying) {
738 device->ffEffectPlaying = false;
739
740 struct input_event ev;
741 ev.time.tv_sec = 0;
742 ev.time.tv_usec = 0;
743 ev.type = EV_FF;
744 ev.code = device->ffEffectId;
745 ev.value = 0;
746 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
747 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100748 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800749 return;
750 }
751 }
752 }
753}
754
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100755EventHub::Device* EventHub::getDeviceByDescriptorLocked(const std::string& descriptor) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800756 size_t size = mDevices.size();
757 for (size_t i = 0; i < size; i++) {
758 Device* device = mDevices.valueAt(i);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100759 if (descriptor == device->identifier.descriptor) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800760 return device;
761 }
762 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700763 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800764}
765
766EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -0800767 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800768 deviceId = mBuiltInKeyboardId;
769 }
770 ssize_t index = mDevices.indexOfKey(deviceId);
771 return index >= 0 ? mDevices.valueAt(index) : NULL;
772}
773
774EventHub::Device* EventHub::getDeviceByPathLocked(const char* devicePath) const {
775 for (size_t i = 0; i < mDevices.size(); i++) {
776 Device* device = mDevices.valueAt(i);
777 if (device->path == devicePath) {
778 return device;
779 }
780 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700781 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800782}
783
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700784/**
785 * The file descriptor could be either input device, or a video device (associated with a
786 * specific input device). Check both cases here, and return the device that this event
787 * belongs to. Caller can compare the fd's once more to determine event type.
788 * Looks through all input devices, and only attached video devices. Unattached video
789 * devices are ignored.
790 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700791EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
792 for (size_t i = 0; i < mDevices.size(); i++) {
793 Device* device = mDevices.valueAt(i);
794 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700795 // This is an input device event
796 return device;
797 }
798 if (device->videoDevice && device->videoDevice->getFd() == fd) {
799 // This is a video device event
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700800 return device;
801 }
802 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700803 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
804 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700805 return nullptr;
806}
807
Michael Wrightd02c5b62014-02-10 15:10:22 -0800808size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
809 ALOG_ASSERT(bufferSize >= 1);
810
811 AutoMutex _l(mLock);
812
813 struct input_event readBuffer[bufferSize];
814
815 RawEvent* event = buffer;
816 size_t capacity = bufferSize;
817 bool awoken = false;
818 for (;;) {
819 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
820
821 // Reopen input devices if needed.
822 if (mNeedToReopenDevices) {
823 mNeedToReopenDevices = false;
824
825 ALOGI("Reopening all input devices due to a configuration change.");
826
827 closeAllDevicesLocked();
828 mNeedToScanDevices = true;
829 break; // return to the caller before we actually rescan
830 }
831
832 // Report any devices that had last been added/removed.
833 while (mClosingDevices) {
834 Device* device = mClosingDevices;
835 ALOGV("Reporting device closed: id=%d, name=%s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100836 device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800837 mClosingDevices = device->next;
838 event->when = now;
Prabir Pradhancae4b3a2019-02-05 18:51:32 -0800839 event->deviceId = (device->id == mBuiltInKeyboardId) ?
840 ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800841 event->type = DEVICE_REMOVED;
842 event += 1;
843 delete device;
844 mNeedToSendFinishedDeviceScan = true;
845 if (--capacity == 0) {
846 break;
847 }
848 }
849
850 if (mNeedToScanDevices) {
851 mNeedToScanDevices = false;
852 scanDevicesLocked();
853 mNeedToSendFinishedDeviceScan = true;
854 }
855
Yi Kong9b14ac62018-07-17 13:48:38 -0700856 while (mOpeningDevices != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800857 Device* device = mOpeningDevices;
858 ALOGV("Reporting device opened: id=%d, name=%s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100859 device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800860 mOpeningDevices = device->next;
861 event->when = now;
862 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
863 event->type = DEVICE_ADDED;
864 event += 1;
865 mNeedToSendFinishedDeviceScan = true;
866 if (--capacity == 0) {
867 break;
868 }
869 }
870
871 if (mNeedToSendFinishedDeviceScan) {
872 mNeedToSendFinishedDeviceScan = false;
873 event->when = now;
874 event->type = FINISHED_DEVICE_SCAN;
875 event += 1;
876 if (--capacity == 0) {
877 break;
878 }
879 }
880
881 // Grab the next input event.
882 bool deviceChanged = false;
883 while (mPendingEventIndex < mPendingEventCount) {
884 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700885 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800886 if (eventItem.events & EPOLLIN) {
887 mPendingINotify = true;
888 } else {
889 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
890 }
891 continue;
892 }
893
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700894 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800895 if (eventItem.events & EPOLLIN) {
896 ALOGV("awoken after wake()");
897 awoken = true;
898 char buffer[16];
899 ssize_t nRead;
900 do {
901 nRead = read(mWakeReadPipeFd, buffer, sizeof(buffer));
902 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(buffer));
903 } else {
904 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
905 eventItem.events);
906 }
907 continue;
908 }
909
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700910 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700911 if (!device) {
912 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.",
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700913 eventItem.events, eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700914 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800915 continue;
916 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700917 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
918 if (eventItem.events & EPOLLIN) {
919 size_t numFrames = device->videoDevice->readAndQueueFrames();
920 if (numFrames == 0) {
921 ALOGE("Received epoll event for video device %s, but could not read frame",
922 device->videoDevice->getName().c_str());
923 }
924 } else if (eventItem.events & EPOLLHUP) {
925 // TODO(b/121395353) - consider adding EPOLLRDHUP
926 ALOGI("Removing video device %s due to epoll hang-up event.",
927 device->videoDevice->getName().c_str());
928 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
929 device->videoDevice = nullptr;
930 } else {
931 ALOGW("Received unexpected epoll event 0x%08x for device %s.",
932 eventItem.events, device->videoDevice->getName().c_str());
933 ALOG_ASSERT(!DEBUG);
934 }
935 continue;
936 }
937 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -0800938 if (eventItem.events & EPOLLIN) {
939 int32_t readSize = read(device->fd, readBuffer,
940 sizeof(struct input_event) * capacity);
941 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
942 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -0700943 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
944 " bufferSize: %zu capacity: %zu errno: %d)\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800945 device->fd, readSize, bufferSize, capacity, errno);
946 deviceChanged = true;
947 closeDeviceLocked(device);
948 } else if (readSize < 0) {
949 if (errno != EAGAIN && errno != EINTR) {
950 ALOGW("could not get event (errno=%d)", errno);
951 }
952 } else if ((readSize % sizeof(struct input_event)) != 0) {
953 ALOGE("could not get event (wrong size: %d)", readSize);
954 } else {
955 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
956
957 size_t count = size_t(readSize) / sizeof(struct input_event);
958 for (size_t i = 0; i < count; i++) {
959 struct input_event& iev = readBuffer[i];
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800960 event->when = processEventTimestamp(iev);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800961 event->deviceId = deviceId;
962 event->type = iev.type;
963 event->code = iev.code;
964 event->value = iev.value;
965 event += 1;
966 capacity -= 1;
967 }
968 if (capacity == 0) {
969 // The result buffer is full. Reset the pending event index
970 // so we will try to read the device again on the next iteration.
971 mPendingEventIndex -= 1;
972 break;
973 }
974 }
975 } else if (eventItem.events & EPOLLHUP) {
976 ALOGI("Removing device %s due to epoll hang-up event.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100977 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800978 deviceChanged = true;
979 closeDeviceLocked(device);
980 } else {
981 ALOGW("Received unexpected epoll event 0x%08x for device %s.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100982 eventItem.events, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800983 }
984 }
985
986 // readNotify() will modify the list of devices so this must be done after
987 // processing all other events to ensure that we read all remaining events
988 // before closing the devices.
989 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
990 mPendingINotify = false;
991 readNotifyLocked();
992 deviceChanged = true;
993 }
994
995 // Report added or removed devices immediately.
996 if (deviceChanged) {
997 continue;
998 }
999
1000 // Return now if we have collected any events or if we were explicitly awoken.
1001 if (event != buffer || awoken) {
1002 break;
1003 }
1004
1005 // Poll for events. Mind the wake lock dance!
1006 // We hold a wake lock at all times except during epoll_wait(). This works due to some
1007 // subtle choreography. When a device driver has pending (unread) events, it acquires
1008 // a kernel wake lock. However, once the last pending event has been read, the device
1009 // driver will release the kernel wake lock. To prevent the system from going to sleep
1010 // when this happens, the EventHub holds onto its own user wake lock while the client
1011 // is processing events. Thus the system can only sleep if there are no events
1012 // pending or currently being processed.
1013 //
1014 // The timeout is advisory only. If the device is asleep, it will not wake just to
1015 // service the timeout.
1016 mPendingEventIndex = 0;
1017
1018 mLock.unlock(); // release lock before poll, must be before release_wake_lock
1019 release_wake_lock(WAKE_LOCK_ID);
1020
1021 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1022
1023 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
1024 mLock.lock(); // reacquire lock after poll, must be after acquire_wake_lock
1025
1026 if (pollResult == 0) {
1027 // Timed out.
1028 mPendingEventCount = 0;
1029 break;
1030 }
1031
1032 if (pollResult < 0) {
1033 // An error occurred.
1034 mPendingEventCount = 0;
1035
1036 // Sleep after errors to avoid locking up the system.
1037 // Hopefully the error is transient.
1038 if (errno != EINTR) {
1039 ALOGW("poll failed (errno=%d)\n", errno);
1040 usleep(100000);
1041 }
1042 } else {
1043 // Some events occurred.
1044 mPendingEventCount = size_t(pollResult);
1045 }
1046 }
1047
1048 // All done, return the number of events we read.
1049 return event - buffer;
1050}
1051
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001052std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
1053 AutoMutex _l(mLock);
1054
1055 Device* device = getDeviceLocked(deviceId);
1056 if (!device || !device->videoDevice) {
1057 return {};
1058 }
1059 return device->videoDevice->consumeFrames();
1060}
1061
Michael Wrightd02c5b62014-02-10 15:10:22 -08001062void EventHub::wake() {
1063 ALOGV("wake() called");
1064
1065 ssize_t nWrite;
1066 do {
1067 nWrite = write(mWakeWritePipeFd, "W", 1);
1068 } while (nWrite == -1 && errno == EINTR);
1069
1070 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001071 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001072 }
1073}
1074
1075void EventHub::scanDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001076 status_t result = scanDirLocked(DEVICE_PATH);
1077 if(result < 0) {
1078 ALOGE("scan dir failed for %s", DEVICE_PATH);
1079 }
Philip Quinn39b81682019-01-09 22:20:39 -08001080 if (isV4lScanningEnabled()) {
1081 result = scanVideoDirLocked(VIDEO_DEVICE_PATH);
1082 if (result != OK) {
1083 ALOGE("scan video dir failed for %s", VIDEO_DEVICE_PATH);
1084 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001085 }
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001086 if (mDevices.indexOfKey(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) < 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001087 createVirtualKeyboardLocked();
1088 }
1089}
1090
1091// ----------------------------------------------------------------------------
1092
1093static bool containsNonZeroByte(const uint8_t* array, uint32_t startIndex, uint32_t endIndex) {
1094 const uint8_t* end = array + endIndex;
1095 array += startIndex;
1096 while (array != end) {
1097 if (*(array++) != 0) {
1098 return true;
1099 }
1100 }
1101 return false;
1102}
1103
1104static const int32_t GAMEPAD_KEYCODES[] = {
1105 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C,
1106 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z,
1107 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1,
1108 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2,
1109 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR,
1110 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001111};
1112
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001113status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001114 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001115 struct epoll_event eventItem = {};
1116 eventItem.events = EPOLLIN | EPOLLWAKEUP;
1117 eventItem.data.fd = fd;
1118 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1119 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001120 return -errno;
1121 }
1122 return OK;
1123}
1124
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001125status_t EventHub::unregisterFdFromEpoll(int fd) {
1126 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
1127 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
1128 return -errno;
1129 }
1130 return OK;
1131}
1132
1133status_t EventHub::registerDeviceForEpollLocked(Device* device) {
1134 if (device == nullptr) {
1135 if (DEBUG) {
1136 LOG_ALWAYS_FATAL("Cannot call registerDeviceForEpollLocked with null Device");
1137 }
1138 return BAD_VALUE;
1139 }
1140 status_t result = registerFdForEpoll(device->fd);
1141 if (result != OK) {
1142 ALOGE("Could not add input device fd to epoll for device %" PRId32, device->id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001143 return result;
1144 }
1145 if (device->videoDevice) {
1146 registerVideoDeviceForEpollLocked(*device->videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001147 }
1148 return result;
1149}
1150
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001151void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
1152 status_t result = registerFdForEpoll(videoDevice.getFd());
1153 if (result != OK) {
1154 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
1155 }
1156}
1157
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001158status_t EventHub::unregisterDeviceFromEpollLocked(Device* device) {
1159 if (device->hasValidFd()) {
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001160 status_t result = unregisterFdFromEpoll(device->fd);
1161 if (result != OK) {
1162 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device->id);
1163 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001164 }
1165 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001166 if (device->videoDevice) {
1167 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1168 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001169 return OK;
1170}
1171
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001172void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
1173 if (videoDevice.hasValidFd()) {
1174 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
1175 if (result != OK) {
1176 ALOGW("Could not remove video device fd from epoll for device: %s",
1177 videoDevice.getName().c_str());
1178 }
1179 }
1180}
1181
1182status_t EventHub::openDeviceLocked(const char* devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001183 char buffer[80];
1184
1185 ALOGV("Opening device: %s", devicePath);
1186
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001187 int fd = open(devicePath, O_RDWR | O_CLOEXEC | O_NONBLOCK);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001188 if(fd < 0) {
1189 ALOGE("could not open %s, %s\n", devicePath, strerror(errno));
1190 return -1;
1191 }
1192
1193 InputDeviceIdentifier identifier;
1194
1195 // Get device name.
1196 if(ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001197 ALOGE("Could not get device name for %s: %s", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001198 } else {
1199 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001200 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001201 }
1202
1203 // Check to see if the device is on our excluded list
1204 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001205 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001206 if (identifier.name == item) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001207 ALOGI("ignoring event id %s driver %s\n", devicePath, item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001208 close(fd);
1209 return -1;
1210 }
1211 }
1212
1213 // Get device driver version.
1214 int driverVersion;
1215 if(ioctl(fd, EVIOCGVERSION, &driverVersion)) {
1216 ALOGE("could not get driver version for %s, %s\n", devicePath, strerror(errno));
1217 close(fd);
1218 return -1;
1219 }
1220
1221 // Get device identifier.
1222 struct input_id inputId;
1223 if(ioctl(fd, EVIOCGID, &inputId)) {
1224 ALOGE("could not get device input id for %s, %s\n", devicePath, strerror(errno));
1225 close(fd);
1226 return -1;
1227 }
1228 identifier.bus = inputId.bustype;
1229 identifier.product = inputId.product;
1230 identifier.vendor = inputId.vendor;
1231 identifier.version = inputId.version;
1232
1233 // Get device physical location.
1234 if(ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
1235 //fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
1236 } else {
1237 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001238 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001239 }
1240
1241 // Get device unique id.
1242 if(ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
1243 //fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
1244 } else {
1245 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001246 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001247 }
1248
1249 // Fill in the descriptor.
1250 assignDescriptorLocked(identifier);
1251
Michael Wrightd02c5b62014-02-10 15:10:22 -08001252 // Allocate device. (The device object takes ownership of the fd at this point.)
1253 int32_t deviceId = mNextDeviceId++;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001254 Device* device = new Device(fd, deviceId, devicePath, identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001255
1256 ALOGV("add device %d: %s\n", deviceId, devicePath);
1257 ALOGV(" bus: %04x\n"
1258 " vendor %04x\n"
1259 " product %04x\n"
1260 " version %04x\n",
1261 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001262 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
1263 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
1264 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
1265 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001266 ALOGV(" driver: v%d.%d.%d\n",
1267 driverVersion >> 16, (driverVersion >> 8) & 0xff, driverVersion & 0xff);
1268
1269 // Load the configuration file for the device.
1270 loadConfigurationLocked(device);
1271
1272 // Figure out the kinds of events the device reports.
1273 ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(device->keyBitmask)), device->keyBitmask);
1274 ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(device->absBitmask)), device->absBitmask);
1275 ioctl(fd, EVIOCGBIT(EV_REL, sizeof(device->relBitmask)), device->relBitmask);
1276 ioctl(fd, EVIOCGBIT(EV_SW, sizeof(device->swBitmask)), device->swBitmask);
1277 ioctl(fd, EVIOCGBIT(EV_LED, sizeof(device->ledBitmask)), device->ledBitmask);
1278 ioctl(fd, EVIOCGBIT(EV_FF, sizeof(device->ffBitmask)), device->ffBitmask);
1279 ioctl(fd, EVIOCGPROP(sizeof(device->propBitmask)), device->propBitmask);
1280
1281 // See if this is a keyboard. Ignore everything in the button range except for
1282 // joystick and gamepad buttons which are handled like keyboards for the most part.
1283 bool haveKeyboardKeys = containsNonZeroByte(device->keyBitmask, 0, sizeof_bit_array(BTN_MISC))
1284 || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(KEY_OK),
1285 sizeof_bit_array(KEY_MAX + 1));
1286 bool haveGamepadButtons = containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_MISC),
1287 sizeof_bit_array(BTN_MOUSE))
1288 || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_JOYSTICK),
1289 sizeof_bit_array(BTN_DIGI));
1290 if (haveKeyboardKeys || haveGamepadButtons) {
1291 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1292 }
1293
1294 // See if this is a cursor device such as a trackball or mouse.
1295 if (test_bit(BTN_MOUSE, device->keyBitmask)
1296 && test_bit(REL_X, device->relBitmask)
1297 && test_bit(REL_Y, device->relBitmask)) {
1298 device->classes |= INPUT_DEVICE_CLASS_CURSOR;
1299 }
1300
Prashant Malani1941ff52015-08-11 18:29:28 -07001301 // See if this is a rotary encoder type device.
1302 String8 deviceType = String8();
1303 if (device->configuration &&
1304 device->configuration->tryGetProperty(String8("device.type"), deviceType)) {
1305 if (!deviceType.compare(String8("rotaryEncoder"))) {
1306 device->classes |= INPUT_DEVICE_CLASS_ROTARY_ENCODER;
1307 }
1308 }
1309
Michael Wrightd02c5b62014-02-10 15:10:22 -08001310 // See if this is a touch pad.
1311 // Is this a new modern multi-touch driver?
1312 if (test_bit(ABS_MT_POSITION_X, device->absBitmask)
1313 && test_bit(ABS_MT_POSITION_Y, device->absBitmask)) {
1314 // Some joysticks such as the PS3 controller report axes that conflict
1315 // with the ABS_MT range. Try to confirm that the device really is
1316 // a touch screen.
1317 if (test_bit(BTN_TOUCH, device->keyBitmask) || !haveGamepadButtons) {
1318 device->classes |= INPUT_DEVICE_CLASS_TOUCH | INPUT_DEVICE_CLASS_TOUCH_MT;
1319 }
1320 // Is this an old style single-touch driver?
1321 } else if (test_bit(BTN_TOUCH, device->keyBitmask)
1322 && test_bit(ABS_X, device->absBitmask)
1323 && test_bit(ABS_Y, device->absBitmask)) {
1324 device->classes |= INPUT_DEVICE_CLASS_TOUCH;
Michael Wright842500e2015-03-13 17:32:02 -07001325 // Is this a BT stylus?
1326 } else if ((test_bit(ABS_PRESSURE, device->absBitmask) ||
1327 test_bit(BTN_TOUCH, device->keyBitmask))
1328 && !test_bit(ABS_X, device->absBitmask)
1329 && !test_bit(ABS_Y, device->absBitmask)) {
1330 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++) {
1343 if (test_bit(i, device->absBitmask)
1344 && (getAbsAxisUsage(i, assumedClasses) & INPUT_DEVICE_CLASS_JOYSTICK)) {
1345 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.
1385 if (!keyMapStatus
1386 && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD
1387 && isEligibleBuiltInKeyboard(device->identifier,
1388 device->configuration, &device->keyMap)) {
1389 mBuiltInKeyboardId = device->id;
1390 }
1391
1392 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
1393 if (hasKeycodeLocked(device, AKEYCODE_Q)) {
1394 device->classes |= INPUT_DEVICE_CLASS_ALPHAKEY;
1395 }
1396
1397 // See if this device has a DPAD.
1398 if (hasKeycodeLocked(device, AKEYCODE_DPAD_UP) &&
1399 hasKeycodeLocked(device, AKEYCODE_DPAD_DOWN) &&
1400 hasKeycodeLocked(device, AKEYCODE_DPAD_LEFT) &&
1401 hasKeycodeLocked(device, AKEYCODE_DPAD_RIGHT) &&
1402 hasKeycodeLocked(device, AKEYCODE_DPAD_CENTER)) {
1403 device->classes |= INPUT_DEVICE_CLASS_DPAD;
1404 }
1405
1406 // See if this device has a gamepad.
1407 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES)/sizeof(GAMEPAD_KEYCODES[0]); i++) {
1408 if (hasKeycodeLocked(device, GAMEPAD_KEYCODES[i])) {
1409 device->classes |= INPUT_DEVICE_CLASS_GAMEPAD;
1410 break;
1411 }
1412 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001413 }
1414
1415 // If the device isn't recognized as something we handle, don't monitor it.
1416 if (device->classes == 0) {
1417 ALOGV("Dropping device: id=%d, path='%s', name='%s'",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001418 deviceId, devicePath, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001419 delete device;
1420 return -1;
1421 }
1422
Tim Kilbourn063ff532015-04-08 10:26:18 -07001423 // Determine whether the device has a mic.
1424 if (deviceHasMicLocked(device)) {
1425 device->classes |= INPUT_DEVICE_CLASS_MIC;
1426 }
1427
Michael Wrightd02c5b62014-02-10 15:10:22 -08001428 // Determine whether the device is external or internal.
1429 if (isExternalDeviceLocked(device)) {
1430 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL;
1431 }
1432
Michael Wright42f2c6a2014-03-12 10:33:03 -07001433 if (device->classes & (INPUT_DEVICE_CLASS_JOYSTICK | INPUT_DEVICE_CLASS_DPAD)
1434 && device->classes & INPUT_DEVICE_CLASS_GAMEPAD) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001435 device->controllerNumber = getNextControllerNumberLocked(device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001436 setLedForControllerLocked(device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001437 }
1438
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001439 // Find a matching video device by comparing device names
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001440 // This should be done before registerDeviceForEpollLocked, so that both fds are added to epoll
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001441 for (std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
1442 if (device->identifier.name == videoDevice->getName()) {
1443 device->videoDevice = std::move(videoDevice);
1444 break;
1445 }
1446 }
1447 mUnattachedVideoDevices.erase(std::remove_if(mUnattachedVideoDevices.begin(),
1448 mUnattachedVideoDevices.end(),
1449 [](const std::unique_ptr<TouchVideoDevice>& videoDevice){
1450 return videoDevice == nullptr; }), 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, "
1460 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001461 deviceId, fd, devicePath, device->identifier.name.c_str(),
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001462 device->classes,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001463 device->configurationFile.c_str(),
1464 device->keyMap.keyLayoutFile.c_str(),
1465 device->keyMap.keyCharacterMapFile.c_str(),
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001466 toString(mBuiltInKeyboardId == deviceId));
1467
1468 addDeviceLocked(device);
1469 return OK;
1470}
1471
1472void EventHub::configureFd(Device* device) {
1473 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
1474 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1475 // Disable kernel key repeat since we handle it ourselves
1476 unsigned int repeatRate[] = {0, 0};
1477 if (ioctl(device->fd, EVIOCSREP, repeatRate)) {
1478 ALOGW("Unable to disable kernel key repeat for %s: %s",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001479 device->path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001480 }
1481 }
1482
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001483 std::string wakeMechanism = "EPOLLWAKEUP";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001484 if (!mUsingEpollWakeup) {
1485#ifndef EVIOCSSUSPENDBLOCK
1486 // uapi headers don't include EVIOCSSUSPENDBLOCK, and future kernels
1487 // will use an epoll flag instead, so as long as we want to support
1488 // this feature, we need to be prepared to define the ioctl ourselves.
1489#define EVIOCSSUSPENDBLOCK _IOW('E', 0x91, int)
1490#endif
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001491 if (ioctl(device->fd, EVIOCSSUSPENDBLOCK, 1)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001492 wakeMechanism = "<none>";
1493 } else {
1494 wakeMechanism = "EVIOCSSUSPENDBLOCK";
1495 }
1496 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001497 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
1498 // associated with input events. This is important because the input system
1499 // uses the timestamps extensively and assumes they were recorded using the monotonic
1500 // clock.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001501 int clockId = CLOCK_MONOTONIC;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001502 bool usingClockIoctl = !ioctl(device->fd, EVIOCSCLOCKID, &clockId);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001503 ALOGI("wakeMechanism=%s, usingClockIoctl=%s", wakeMechanism.c_str(),
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001504 toString(usingClockIoctl));
1505}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001506
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001507void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
1508 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
1509 if (!videoDevice) {
1510 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
1511 return;
1512 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001513 // Transfer ownership of this video device to a matching input device
1514 for (size_t i = 0; i < mDevices.size(); i++) {
1515 Device* device = mDevices.valueAt(i);
1516 if (videoDevice->getName() == device->identifier.name) {
1517 device->videoDevice = std::move(videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001518 if (device->enabled) {
1519 registerVideoDeviceForEpollLocked(*device->videoDevice);
1520 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001521 return;
1522 }
1523 }
1524
1525 // Couldn't find a matching input device, so just add it to a temporary holding queue.
1526 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001527 ALOGI("Adding video device %s to list of unattached video devices",
1528 videoDevice->getName().c_str());
1529 mUnattachedVideoDevices.push_back(std::move(videoDevice));
1530}
1531
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001532bool EventHub::isDeviceEnabled(int32_t deviceId) {
1533 AutoMutex _l(mLock);
1534 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001535 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001536 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1537 return false;
1538 }
1539 return device->enabled;
1540}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001541
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001542status_t EventHub::enableDevice(int32_t deviceId) {
1543 AutoMutex _l(mLock);
1544 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001545 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001546 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1547 return BAD_VALUE;
1548 }
1549 if (device->enabled) {
1550 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
1551 return OK;
1552 }
1553 status_t result = device->enable();
1554 if (result != OK) {
1555 ALOGE("Failed to enable device %" PRId32, deviceId);
1556 return result;
1557 }
1558
1559 configureFd(device);
1560
1561 return registerDeviceForEpollLocked(device);
1562}
1563
1564status_t EventHub::disableDevice(int32_t deviceId) {
1565 AutoMutex _l(mLock);
1566 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001567 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001568 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1569 return BAD_VALUE;
1570 }
1571 if (!device->enabled) {
1572 ALOGW("Duplicate call to %s, input device already disabled", __func__);
1573 return OK;
1574 }
1575 unregisterDeviceFromEpollLocked(device);
1576 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001577}
1578
1579void EventHub::createVirtualKeyboardLocked() {
1580 InputDeviceIdentifier identifier;
1581 identifier.name = "Virtual";
1582 identifier.uniqueId = "<virtual>";
1583 assignDescriptorLocked(identifier);
1584
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001585 Device* device = new Device(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
1586 identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001587 device->classes = INPUT_DEVICE_CLASS_KEYBOARD
1588 | INPUT_DEVICE_CLASS_ALPHAKEY
1589 | INPUT_DEVICE_CLASS_DPAD
1590 | INPUT_DEVICE_CLASS_VIRTUAL;
1591 loadKeyMapLocked(device);
1592 addDeviceLocked(device);
1593}
1594
1595void EventHub::addDeviceLocked(Device* device) {
1596 mDevices.add(device->id, device);
1597 device->next = mOpeningDevices;
1598 mOpeningDevices = device;
1599}
1600
1601void EventHub::loadConfigurationLocked(Device* device) {
1602 device->configurationFile = getInputDeviceConfigurationFilePathByDeviceIdentifier(
1603 device->identifier, INPUT_DEVICE_CONFIGURATION_FILE_TYPE_CONFIGURATION);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001604 if (device->configurationFile.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001605 ALOGD("No input device configuration file found for device '%s'.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001606 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001607 } else {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001608 status_t status = PropertyMap::load(String8(device->configurationFile.c_str()),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001609 &device->configuration);
1610 if (status) {
1611 ALOGE("Error loading input device configuration file for device '%s'. "
1612 "Using default configuration.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001613 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001614 }
1615 }
1616}
1617
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001618bool EventHub::loadVirtualKeyMapLocked(Device* device) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001619 // The virtual key map is supplied by the kernel as a system board property file.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001620 std::string path;
1621 path += "/sys/board_properties/virtualkeys.";
Siarhei Vishniakoub45635c2019-02-20 19:22:09 -06001622 path += device->identifier.getCanonicalName();
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001623 if (access(path.c_str(), R_OK)) {
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001624 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001625 }
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001626 device->virtualKeyMap = VirtualKeyMap::load(path);
1627 return device->virtualKeyMap != nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001628}
1629
1630status_t EventHub::loadKeyMapLocked(Device* device) {
1631 return device->keyMap.load(device->identifier, device->configuration);
1632}
1633
1634bool EventHub::isExternalDeviceLocked(Device* device) {
1635 if (device->configuration) {
1636 bool value;
1637 if (device->configuration->tryGetProperty(String8("device.internal"), value)) {
1638 return !value;
1639 }
1640 }
1641 return device->identifier.bus == BUS_USB || device->identifier.bus == BUS_BLUETOOTH;
1642}
1643
Tim Kilbourn063ff532015-04-08 10:26:18 -07001644bool EventHub::deviceHasMicLocked(Device* device) {
1645 if (device->configuration) {
1646 bool value;
1647 if (device->configuration->tryGetProperty(String8("audio.mic"), value)) {
1648 return value;
1649 }
1650 }
1651 return false;
1652}
1653
Michael Wrightd02c5b62014-02-10 15:10:22 -08001654int32_t EventHub::getNextControllerNumberLocked(Device* device) {
1655 if (mControllerNumbers.isFull()) {
1656 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001657 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001658 return 0;
1659 }
1660 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
1661 // one
1662 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
1663}
1664
1665void EventHub::releaseControllerNumberLocked(Device* device) {
1666 int32_t num = device->controllerNumber;
1667 device->controllerNumber= 0;
1668 if (num == 0) {
1669 return;
1670 }
1671 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
1672}
1673
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001674void EventHub::setLedForControllerLocked(Device* device) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001675 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
1676 setLedStateLocked(device, ALED_CONTROLLER_1 + i, device->controllerNumber == i + 1);
1677 }
1678}
1679
1680bool EventHub::hasKeycodeLocked(Device* device, int keycode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001681 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001682 return false;
1683 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001684
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001685 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001686 device->keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes);
1687 const size_t N = scanCodes.size();
1688 for (size_t i=0; i<N && i<=KEY_MAX; i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001689 int32_t sc = scanCodes[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001690 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, device->keyBitmask)) {
1691 return true;
1692 }
1693 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001694
Michael Wrightd02c5b62014-02-10 15:10:22 -08001695 return false;
1696}
1697
1698status_t EventHub::mapLed(Device* device, int32_t led, int32_t* outScanCode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001699 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001700 return NAME_NOT_FOUND;
1701 }
1702
1703 int32_t scanCode;
1704 if(device->keyMap.keyLayoutMap->findScanCodeForLed(led, &scanCode) != NAME_NOT_FOUND) {
1705 if(scanCode >= 0 && scanCode <= LED_MAX && test_bit(scanCode, device->ledBitmask)) {
1706 *outScanCode = scanCode;
1707 return NO_ERROR;
1708 }
1709 }
1710 return NAME_NOT_FOUND;
1711}
1712
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001713void EventHub::closeDeviceByPathLocked(const char *devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001714 Device* device = getDeviceByPathLocked(devicePath);
1715 if (device) {
1716 closeDeviceLocked(device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001717 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001718 }
1719 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001720}
1721
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001722/**
1723 * Find the video device by filename, and close it.
1724 * The video device is closed by path during an inotify event, where we don't have the
1725 * additional context about the video device fd, or the associated input device.
1726 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001727void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001728 // A video device may be owned by an existing input device, or it may be stored in
1729 // the mUnattachedVideoDevices queue. Check both locations.
1730 for (size_t i = 0; i < mDevices.size(); i++) {
1731 Device* device = mDevices.valueAt(i);
1732 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001733 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001734 device->videoDevice = nullptr;
1735 return;
1736 }
1737 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001738 mUnattachedVideoDevices.erase(std::remove_if(mUnattachedVideoDevices.begin(),
1739 mUnattachedVideoDevices.end(), [&devicePath](
1740 const std::unique_ptr<TouchVideoDevice>& videoDevice) {
1741 return videoDevice->getPath() == devicePath; }), mUnattachedVideoDevices.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001742}
1743
1744void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001745 mUnattachedVideoDevices.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001746 while (mDevices.size() > 0) {
1747 closeDeviceLocked(mDevices.valueAt(mDevices.size() - 1));
1748 }
1749}
1750
1751void EventHub::closeDeviceLocked(Device* device) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001752 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=0x%x",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001753 device->path.c_str(), device->identifier.name.c_str(), device->id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001754 device->fd, device->classes);
1755
1756 if (device->id == mBuiltInKeyboardId) {
1757 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001758 device->path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001759 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
1760 }
1761
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001762 unregisterDeviceFromEpollLocked(device);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001763 if (device->videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001764 // This must be done after the video device is removed from epoll
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001765 mUnattachedVideoDevices.push_back(std::move(device->videoDevice));
1766 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001767
1768 releaseControllerNumberLocked(device);
1769
1770 mDevices.removeItem(device->id);
1771 device->close();
1772
1773 // Unlink for opening devices list if it is present.
Yi Kong9b14ac62018-07-17 13:48:38 -07001774 Device* pred = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001775 bool found = false;
Yi Kong9b14ac62018-07-17 13:48:38 -07001776 for (Device* entry = mOpeningDevices; entry != nullptr; ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001777 if (entry == device) {
1778 found = true;
1779 break;
1780 }
1781 pred = entry;
1782 entry = entry->next;
1783 }
1784 if (found) {
1785 // Unlink the device from the opening devices list then delete it.
1786 // We don't need to tell the client that the device was closed because
1787 // it does not even know it was opened in the first place.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001788 ALOGI("Device %s was immediately closed after opening.", device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001789 if (pred) {
1790 pred->next = device->next;
1791 } else {
1792 mOpeningDevices = device->next;
1793 }
1794 delete device;
1795 } else {
1796 // Link into closing devices list.
1797 // The device will be deleted later after we have informed the client.
1798 device->next = mClosingDevices;
1799 mClosingDevices = device;
1800 }
1801}
1802
1803status_t EventHub::readNotifyLocked() {
1804 int res;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001805 char event_buf[512];
1806 int event_size;
1807 int event_pos = 0;
1808 struct inotify_event *event;
1809
1810 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
1811 res = read(mINotifyFd, event_buf, sizeof(event_buf));
1812 if(res < (int)sizeof(*event)) {
1813 if(errno == EINTR)
1814 return 0;
1815 ALOGW("could not get event, %s\n", strerror(errno));
1816 return -1;
1817 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001818
1819 while(res >= (int)sizeof(*event)) {
1820 event = (struct inotify_event *)(event_buf + event_pos);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001821 if(event->len) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001822 if (event->wd == mInputWd) {
1823 std::string filename = StringPrintf("%s/%s", DEVICE_PATH, event->name);
1824 if(event->mask & IN_CREATE) {
1825 openDeviceLocked(filename.c_str());
1826 } else {
1827 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
1828 closeDeviceByPathLocked(filename.c_str());
1829 }
1830 }
1831 else if (event->wd == mVideoWd) {
1832 if (isV4lTouchNode(event->name)) {
1833 std::string filename = StringPrintf("%s/%s", VIDEO_DEVICE_PATH, event->name);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001834 if (event->mask & IN_CREATE) {
1835 openVideoDeviceLocked(filename);
1836 } else {
1837 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
1838 closeVideoDeviceByPathLocked(filename);
1839 }
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001840 }
1841 }
1842 else {
1843 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event->wd);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001844 }
1845 }
1846 event_size = sizeof(*event) + event->len;
1847 res -= event_size;
1848 event_pos += event_size;
1849 }
1850 return 0;
1851}
1852
1853status_t EventHub::scanDirLocked(const char *dirname)
1854{
1855 char devname[PATH_MAX];
1856 char *filename;
1857 DIR *dir;
1858 struct dirent *de;
1859 dir = opendir(dirname);
Yi Kong9b14ac62018-07-17 13:48:38 -07001860 if(dir == nullptr)
Michael Wrightd02c5b62014-02-10 15:10:22 -08001861 return -1;
1862 strcpy(devname, dirname);
1863 filename = devname + strlen(devname);
1864 *filename++ = '/';
1865 while((de = readdir(dir))) {
1866 if(de->d_name[0] == '.' &&
1867 (de->d_name[1] == '\0' ||
1868 (de->d_name[1] == '.' && de->d_name[2] == '\0')))
1869 continue;
1870 strcpy(filename, de->d_name);
1871 openDeviceLocked(devname);
1872 }
1873 closedir(dir);
1874 return 0;
1875}
1876
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001877/**
1878 * Look for all dirname/v4l-touch* devices, and open them.
1879 */
1880status_t EventHub::scanVideoDirLocked(const std::string& dirname)
1881{
1882 DIR* dir;
1883 struct dirent* de;
1884 dir = opendir(dirname.c_str());
1885 if(!dir) {
1886 ALOGE("Could not open video directory %s", dirname.c_str());
1887 return BAD_VALUE;
1888 }
1889
1890 while((de = readdir(dir))) {
1891 const char* name = de->d_name;
1892 if (isV4lTouchNode(name)) {
1893 ALOGI("Found touch video device %s", name);
1894 openVideoDeviceLocked(dirname + "/" + name);
1895 }
1896 }
1897 closedir(dir);
1898 return OK;
1899}
1900
Michael Wrightd02c5b62014-02-10 15:10:22 -08001901void EventHub::requestReopenDevices() {
1902 ALOGV("requestReopenDevices() called");
1903
1904 AutoMutex _l(mLock);
1905 mNeedToReopenDevices = true;
1906}
1907
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001908void EventHub::dump(std::string& dump) {
1909 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001910
1911 { // acquire lock
1912 AutoMutex _l(mLock);
1913
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001914 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001915
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001916 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001917
1918 for (size_t i = 0; i < mDevices.size(); i++) {
1919 const Device* device = mDevices.valueAt(i);
1920 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001921 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001922 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001923 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001924 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001925 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001926 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001927 dump += StringPrintf(INDENT3 "Classes: 0x%08x\n", device->classes);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001928 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001929 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001930 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
1931 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001932 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001933 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001934 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08001935 "product=0x%04x, version=0x%04x\n",
1936 device->identifier.bus, device->identifier.vendor,
1937 device->identifier.product, device->identifier.version);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001938 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001939 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001940 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001941 device->keyMap.keyCharacterMapFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001942 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001943 device->configurationFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001944 dump += StringPrintf(INDENT3 "HaveKeyboardLayoutOverlay: %s\n",
Yi Kong9b14ac62018-07-17 13:48:38 -07001945 toString(device->overlayKeyMap != nullptr));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001946 dump += INDENT3 "VideoDevice: ";
1947 if (device->videoDevice) {
1948 dump += device->videoDevice->dump() + "\n";
1949 } else {
1950 dump += "<none>\n";
1951 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001952 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001953
1954 dump += INDENT "Unattached video devices:\n";
1955 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
1956 dump += INDENT2 + videoDevice->dump() + "\n";
1957 }
1958 if (mUnattachedVideoDevices.empty()) {
1959 dump += INDENT2 "<none>\n";
1960 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001961 } // release lock
1962}
1963
1964void EventHub::monitor() {
1965 // Acquire and release the lock to ensure that the event hub has not deadlocked.
1966 mLock.lock();
1967 mLock.unlock();
1968}
1969
1970
1971}; // namespace android