blob: 4735643934d80b12ce18486b058e0ed230008de3 [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()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800418 Vector<int32_t> scanCodes;
419 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++) {
425 int32_t sc = scanCodes.itemAt(i);
426 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()) {
481 Vector<int32_t> scanCodes;
482 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,
612 Vector<VirtualKeyDefinition>& outVirtualKeys) const {
613 outVirtualKeys.clear();
614
615 AutoMutex _l(mLock);
616 Device* device = getDeviceLocked(deviceId);
617 if (device && device->virtualKeyMap) {
618 outVirtualKeys.appendVector(device->virtualKeyMap->getVirtualKeys());
619 }
620}
621
622sp<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
623 AutoMutex _l(mLock);
624 Device* device = getDeviceLocked(deviceId);
625 if (device) {
626 return device->getKeyCharacterMap();
627 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700628 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800629}
630
631bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId,
632 const sp<KeyCharacterMap>& map) {
633 AutoMutex _l(mLock);
634 Device* device = getDeviceLocked(deviceId);
635 if (device) {
636 if (map != device->overlayKeyMap) {
637 device->overlayKeyMap = map;
638 device->combinedKeyMap = KeyCharacterMap::combine(
639 device->keyMap.keyCharacterMap, map);
640 return true;
641 }
642 }
643 return false;
644}
645
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100646static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
647 std::string rawDescriptor;
648 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800649 identifier.product);
650 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100651 if (!identifier.uniqueId.empty()) {
652 rawDescriptor += "uniqueId:";
653 rawDescriptor += identifier.uniqueId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800654 } else if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100655 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800656 }
657
658 if (identifier.vendor == 0 && identifier.product == 0) {
659 // If we don't know the vendor and product id, then the device is probably
660 // built-in so we need to rely on other information to uniquely identify
661 // the input device. Usually we try to avoid relying on the device name or
662 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100663 if (!identifier.name.empty()) {
664 rawDescriptor += "name:";
665 rawDescriptor += identifier.name;
666 } else if (!identifier.location.empty()) {
667 rawDescriptor += "location:";
668 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800669 }
670 }
671 identifier.descriptor = sha1(rawDescriptor);
672 return rawDescriptor;
673}
674
675void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
676 // Compute a device descriptor that uniquely identifies the device.
677 // The descriptor is assumed to be a stable identifier. Its value should not
678 // change between reboots, reconnections, firmware updates or new releases
679 // of Android. In practice we sometimes get devices that cannot be uniquely
680 // identified. In this case we enforce uniqueness between connected devices.
681 // Ideally, we also want the descriptor to be short and relatively opaque.
682
683 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100684 std::string rawDescriptor = generateDescriptor(identifier);
685 if (identifier.uniqueId.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800686 // If it didn't have a unique id check for conflicts and enforce
687 // uniqueness if necessary.
Yi Kong9b14ac62018-07-17 13:48:38 -0700688 while(getDeviceByDescriptorLocked(identifier.descriptor) != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800689 identifier.nonce++;
690 rawDescriptor = generateDescriptor(identifier);
691 }
692 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100693 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
694 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800695}
696
697void EventHub::vibrate(int32_t deviceId, nsecs_t duration) {
698 AutoMutex _l(mLock);
699 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700700 if (device && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800701 ff_effect effect;
702 memset(&effect, 0, sizeof(effect));
703 effect.type = FF_RUMBLE;
704 effect.id = device->ffEffectId;
705 effect.u.rumble.strong_magnitude = 0xc000;
706 effect.u.rumble.weak_magnitude = 0xc000;
707 effect.replay.length = (duration + 999999LL) / 1000000LL;
708 effect.replay.delay = 0;
709 if (ioctl(device->fd, EVIOCSFF, &effect)) {
710 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100711 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800712 return;
713 }
714 device->ffEffectId = effect.id;
715
716 struct input_event ev;
717 ev.time.tv_sec = 0;
718 ev.time.tv_usec = 0;
719 ev.type = EV_FF;
720 ev.code = device->ffEffectId;
721 ev.value = 1;
722 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
723 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100724 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800725 return;
726 }
727 device->ffEffectPlaying = true;
728 }
729}
730
731void EventHub::cancelVibrate(int32_t deviceId) {
732 AutoMutex _l(mLock);
733 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700734 if (device && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800735 if (device->ffEffectPlaying) {
736 device->ffEffectPlaying = false;
737
738 struct input_event ev;
739 ev.time.tv_sec = 0;
740 ev.time.tv_usec = 0;
741 ev.type = EV_FF;
742 ev.code = device->ffEffectId;
743 ev.value = 0;
744 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
745 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100746 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800747 return;
748 }
749 }
750 }
751}
752
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100753EventHub::Device* EventHub::getDeviceByDescriptorLocked(const std::string& descriptor) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800754 size_t size = mDevices.size();
755 for (size_t i = 0; i < size; i++) {
756 Device* device = mDevices.valueAt(i);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100757 if (descriptor == device->identifier.descriptor) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800758 return device;
759 }
760 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700761 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800762}
763
764EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -0800765 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800766 deviceId = mBuiltInKeyboardId;
767 }
768 ssize_t index = mDevices.indexOfKey(deviceId);
769 return index >= 0 ? mDevices.valueAt(index) : NULL;
770}
771
772EventHub::Device* EventHub::getDeviceByPathLocked(const char* devicePath) const {
773 for (size_t i = 0; i < mDevices.size(); i++) {
774 Device* device = mDevices.valueAt(i);
775 if (device->path == devicePath) {
776 return device;
777 }
778 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700779 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800780}
781
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700782/**
783 * The file descriptor could be either input device, or a video device (associated with a
784 * specific input device). Check both cases here, and return the device that this event
785 * belongs to. Caller can compare the fd's once more to determine event type.
786 * Looks through all input devices, and only attached video devices. Unattached video
787 * devices are ignored.
788 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700789EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
790 for (size_t i = 0; i < mDevices.size(); i++) {
791 Device* device = mDevices.valueAt(i);
792 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700793 // This is an input device event
794 return device;
795 }
796 if (device->videoDevice && device->videoDevice->getFd() == fd) {
797 // This is a video device event
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700798 return device;
799 }
800 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700801 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
802 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700803 return nullptr;
804}
805
Michael Wrightd02c5b62014-02-10 15:10:22 -0800806size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
807 ALOG_ASSERT(bufferSize >= 1);
808
809 AutoMutex _l(mLock);
810
811 struct input_event readBuffer[bufferSize];
812
813 RawEvent* event = buffer;
814 size_t capacity = bufferSize;
815 bool awoken = false;
816 for (;;) {
817 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
818
819 // Reopen input devices if needed.
820 if (mNeedToReopenDevices) {
821 mNeedToReopenDevices = false;
822
823 ALOGI("Reopening all input devices due to a configuration change.");
824
825 closeAllDevicesLocked();
826 mNeedToScanDevices = true;
827 break; // return to the caller before we actually rescan
828 }
829
830 // Report any devices that had last been added/removed.
831 while (mClosingDevices) {
832 Device* device = mClosingDevices;
833 ALOGV("Reporting device closed: id=%d, name=%s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100834 device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800835 mClosingDevices = device->next;
836 event->when = now;
Prabir Pradhancae4b3a2019-02-05 18:51:32 -0800837 event->deviceId = (device->id == mBuiltInKeyboardId) ?
838 ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800839 event->type = DEVICE_REMOVED;
840 event += 1;
841 delete device;
842 mNeedToSendFinishedDeviceScan = true;
843 if (--capacity == 0) {
844 break;
845 }
846 }
847
848 if (mNeedToScanDevices) {
849 mNeedToScanDevices = false;
850 scanDevicesLocked();
851 mNeedToSendFinishedDeviceScan = true;
852 }
853
Yi Kong9b14ac62018-07-17 13:48:38 -0700854 while (mOpeningDevices != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800855 Device* device = mOpeningDevices;
856 ALOGV("Reporting device opened: id=%d, name=%s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100857 device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800858 mOpeningDevices = device->next;
859 event->when = now;
860 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
861 event->type = DEVICE_ADDED;
862 event += 1;
863 mNeedToSendFinishedDeviceScan = true;
864 if (--capacity == 0) {
865 break;
866 }
867 }
868
869 if (mNeedToSendFinishedDeviceScan) {
870 mNeedToSendFinishedDeviceScan = false;
871 event->when = now;
872 event->type = FINISHED_DEVICE_SCAN;
873 event += 1;
874 if (--capacity == 0) {
875 break;
876 }
877 }
878
879 // Grab the next input event.
880 bool deviceChanged = false;
881 while (mPendingEventIndex < mPendingEventCount) {
882 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700883 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800884 if (eventItem.events & EPOLLIN) {
885 mPendingINotify = true;
886 } else {
887 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
888 }
889 continue;
890 }
891
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700892 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800893 if (eventItem.events & EPOLLIN) {
894 ALOGV("awoken after wake()");
895 awoken = true;
896 char buffer[16];
897 ssize_t nRead;
898 do {
899 nRead = read(mWakeReadPipeFd, buffer, sizeof(buffer));
900 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(buffer));
901 } else {
902 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
903 eventItem.events);
904 }
905 continue;
906 }
907
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700908 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700909 if (!device) {
910 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.",
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700911 eventItem.events, eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700912 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800913 continue;
914 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700915 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
916 if (eventItem.events & EPOLLIN) {
917 size_t numFrames = device->videoDevice->readAndQueueFrames();
918 if (numFrames == 0) {
919 ALOGE("Received epoll event for video device %s, but could not read frame",
920 device->videoDevice->getName().c_str());
921 }
922 } else if (eventItem.events & EPOLLHUP) {
923 // TODO(b/121395353) - consider adding EPOLLRDHUP
924 ALOGI("Removing video device %s due to epoll hang-up event.",
925 device->videoDevice->getName().c_str());
926 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
927 device->videoDevice = nullptr;
928 } else {
929 ALOGW("Received unexpected epoll event 0x%08x for device %s.",
930 eventItem.events, device->videoDevice->getName().c_str());
931 ALOG_ASSERT(!DEBUG);
932 }
933 continue;
934 }
935 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -0800936 if (eventItem.events & EPOLLIN) {
937 int32_t readSize = read(device->fd, readBuffer,
938 sizeof(struct input_event) * capacity);
939 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
940 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -0700941 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
942 " bufferSize: %zu capacity: %zu errno: %d)\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800943 device->fd, readSize, bufferSize, capacity, errno);
944 deviceChanged = true;
945 closeDeviceLocked(device);
946 } else if (readSize < 0) {
947 if (errno != EAGAIN && errno != EINTR) {
948 ALOGW("could not get event (errno=%d)", errno);
949 }
950 } else if ((readSize % sizeof(struct input_event)) != 0) {
951 ALOGE("could not get event (wrong size: %d)", readSize);
952 } else {
953 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
954
955 size_t count = size_t(readSize) / sizeof(struct input_event);
956 for (size_t i = 0; i < count; i++) {
957 struct input_event& iev = readBuffer[i];
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800958 event->when = processEventTimestamp(iev);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800959 event->deviceId = deviceId;
960 event->type = iev.type;
961 event->code = iev.code;
962 event->value = iev.value;
963 event += 1;
964 capacity -= 1;
965 }
966 if (capacity == 0) {
967 // The result buffer is full. Reset the pending event index
968 // so we will try to read the device again on the next iteration.
969 mPendingEventIndex -= 1;
970 break;
971 }
972 }
973 } else if (eventItem.events & EPOLLHUP) {
974 ALOGI("Removing device %s due to epoll hang-up event.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100975 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800976 deviceChanged = true;
977 closeDeviceLocked(device);
978 } else {
979 ALOGW("Received unexpected epoll event 0x%08x for device %s.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100980 eventItem.events, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800981 }
982 }
983
984 // readNotify() will modify the list of devices so this must be done after
985 // processing all other events to ensure that we read all remaining events
986 // before closing the devices.
987 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
988 mPendingINotify = false;
989 readNotifyLocked();
990 deviceChanged = true;
991 }
992
993 // Report added or removed devices immediately.
994 if (deviceChanged) {
995 continue;
996 }
997
998 // Return now if we have collected any events or if we were explicitly awoken.
999 if (event != buffer || awoken) {
1000 break;
1001 }
1002
1003 // Poll for events. Mind the wake lock dance!
1004 // We hold a wake lock at all times except during epoll_wait(). This works due to some
1005 // subtle choreography. When a device driver has pending (unread) events, it acquires
1006 // a kernel wake lock. However, once the last pending event has been read, the device
1007 // driver will release the kernel wake lock. To prevent the system from going to sleep
1008 // when this happens, the EventHub holds onto its own user wake lock while the client
1009 // is processing events. Thus the system can only sleep if there are no events
1010 // pending or currently being processed.
1011 //
1012 // The timeout is advisory only. If the device is asleep, it will not wake just to
1013 // service the timeout.
1014 mPendingEventIndex = 0;
1015
1016 mLock.unlock(); // release lock before poll, must be before release_wake_lock
1017 release_wake_lock(WAKE_LOCK_ID);
1018
1019 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1020
1021 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
1022 mLock.lock(); // reacquire lock after poll, must be after acquire_wake_lock
1023
1024 if (pollResult == 0) {
1025 // Timed out.
1026 mPendingEventCount = 0;
1027 break;
1028 }
1029
1030 if (pollResult < 0) {
1031 // An error occurred.
1032 mPendingEventCount = 0;
1033
1034 // Sleep after errors to avoid locking up the system.
1035 // Hopefully the error is transient.
1036 if (errno != EINTR) {
1037 ALOGW("poll failed (errno=%d)\n", errno);
1038 usleep(100000);
1039 }
1040 } else {
1041 // Some events occurred.
1042 mPendingEventCount = size_t(pollResult);
1043 }
1044 }
1045
1046 // All done, return the number of events we read.
1047 return event - buffer;
1048}
1049
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001050std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
1051 AutoMutex _l(mLock);
1052
1053 Device* device = getDeviceLocked(deviceId);
1054 if (!device || !device->videoDevice) {
1055 return {};
1056 }
1057 return device->videoDevice->consumeFrames();
1058}
1059
Michael Wrightd02c5b62014-02-10 15:10:22 -08001060void EventHub::wake() {
1061 ALOGV("wake() called");
1062
1063 ssize_t nWrite;
1064 do {
1065 nWrite = write(mWakeWritePipeFd, "W", 1);
1066 } while (nWrite == -1 && errno == EINTR);
1067
1068 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001069 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001070 }
1071}
1072
1073void EventHub::scanDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001074 status_t result = scanDirLocked(DEVICE_PATH);
1075 if(result < 0) {
1076 ALOGE("scan dir failed for %s", DEVICE_PATH);
1077 }
Philip Quinn39b81682019-01-09 22:20:39 -08001078 if (isV4lScanningEnabled()) {
1079 result = scanVideoDirLocked(VIDEO_DEVICE_PATH);
1080 if (result != OK) {
1081 ALOGE("scan video dir failed for %s", VIDEO_DEVICE_PATH);
1082 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001083 }
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001084 if (mDevices.indexOfKey(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) < 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001085 createVirtualKeyboardLocked();
1086 }
1087}
1088
1089// ----------------------------------------------------------------------------
1090
1091static bool containsNonZeroByte(const uint8_t* array, uint32_t startIndex, uint32_t endIndex) {
1092 const uint8_t* end = array + endIndex;
1093 array += startIndex;
1094 while (array != end) {
1095 if (*(array++) != 0) {
1096 return true;
1097 }
1098 }
1099 return false;
1100}
1101
1102static const int32_t GAMEPAD_KEYCODES[] = {
1103 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C,
1104 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z,
1105 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1,
1106 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2,
1107 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR,
1108 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001109};
1110
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001111status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001112 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001113 struct epoll_event eventItem = {};
1114 eventItem.events = EPOLLIN | EPOLLWAKEUP;
1115 eventItem.data.fd = fd;
1116 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1117 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001118 return -errno;
1119 }
1120 return OK;
1121}
1122
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001123status_t EventHub::unregisterFdFromEpoll(int fd) {
1124 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
1125 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
1126 return -errno;
1127 }
1128 return OK;
1129}
1130
1131status_t EventHub::registerDeviceForEpollLocked(Device* device) {
1132 if (device == nullptr) {
1133 if (DEBUG) {
1134 LOG_ALWAYS_FATAL("Cannot call registerDeviceForEpollLocked with null Device");
1135 }
1136 return BAD_VALUE;
1137 }
1138 status_t result = registerFdForEpoll(device->fd);
1139 if (result != OK) {
1140 ALOGE("Could not add input device fd to epoll for device %" PRId32, device->id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001141 return result;
1142 }
1143 if (device->videoDevice) {
1144 registerVideoDeviceForEpollLocked(*device->videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001145 }
1146 return result;
1147}
1148
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001149void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
1150 status_t result = registerFdForEpoll(videoDevice.getFd());
1151 if (result != OK) {
1152 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
1153 }
1154}
1155
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001156status_t EventHub::unregisterDeviceFromEpollLocked(Device* device) {
1157 if (device->hasValidFd()) {
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001158 status_t result = unregisterFdFromEpoll(device->fd);
1159 if (result != OK) {
1160 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device->id);
1161 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001162 }
1163 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001164 if (device->videoDevice) {
1165 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1166 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001167 return OK;
1168}
1169
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001170void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
1171 if (videoDevice.hasValidFd()) {
1172 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
1173 if (result != OK) {
1174 ALOGW("Could not remove video device fd from epoll for device: %s",
1175 videoDevice.getName().c_str());
1176 }
1177 }
1178}
1179
1180status_t EventHub::openDeviceLocked(const char* devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001181 char buffer[80];
1182
1183 ALOGV("Opening device: %s", devicePath);
1184
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001185 int fd = open(devicePath, O_RDWR | O_CLOEXEC | O_NONBLOCK);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001186 if(fd < 0) {
1187 ALOGE("could not open %s, %s\n", devicePath, strerror(errno));
1188 return -1;
1189 }
1190
1191 InputDeviceIdentifier identifier;
1192
1193 // Get device name.
1194 if(ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001195 ALOGE("Could not get device name for %s: %s", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001196 } else {
1197 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001198 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001199 }
1200
1201 // Check to see if the device is on our excluded list
1202 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001203 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001204 if (identifier.name == item) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001205 ALOGI("ignoring event id %s driver %s\n", devicePath, item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001206 close(fd);
1207 return -1;
1208 }
1209 }
1210
1211 // Get device driver version.
1212 int driverVersion;
1213 if(ioctl(fd, EVIOCGVERSION, &driverVersion)) {
1214 ALOGE("could not get driver version for %s, %s\n", devicePath, strerror(errno));
1215 close(fd);
1216 return -1;
1217 }
1218
1219 // Get device identifier.
1220 struct input_id inputId;
1221 if(ioctl(fd, EVIOCGID, &inputId)) {
1222 ALOGE("could not get device input id for %s, %s\n", devicePath, strerror(errno));
1223 close(fd);
1224 return -1;
1225 }
1226 identifier.bus = inputId.bustype;
1227 identifier.product = inputId.product;
1228 identifier.vendor = inputId.vendor;
1229 identifier.version = inputId.version;
1230
1231 // Get device physical location.
1232 if(ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
1233 //fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
1234 } else {
1235 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001236 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237 }
1238
1239 // Get device unique id.
1240 if(ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
1241 //fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
1242 } else {
1243 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001244 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001245 }
1246
1247 // Fill in the descriptor.
1248 assignDescriptorLocked(identifier);
1249
Michael Wrightd02c5b62014-02-10 15:10:22 -08001250 // Allocate device. (The device object takes ownership of the fd at this point.)
1251 int32_t deviceId = mNextDeviceId++;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001252 Device* device = new Device(fd, deviceId, devicePath, identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001253
1254 ALOGV("add device %d: %s\n", deviceId, devicePath);
1255 ALOGV(" bus: %04x\n"
1256 " vendor %04x\n"
1257 " product %04x\n"
1258 " version %04x\n",
1259 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001260 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
1261 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
1262 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
1263 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001264 ALOGV(" driver: v%d.%d.%d\n",
1265 driverVersion >> 16, (driverVersion >> 8) & 0xff, driverVersion & 0xff);
1266
1267 // Load the configuration file for the device.
1268 loadConfigurationLocked(device);
1269
1270 // Figure out the kinds of events the device reports.
1271 ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(device->keyBitmask)), device->keyBitmask);
1272 ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(device->absBitmask)), device->absBitmask);
1273 ioctl(fd, EVIOCGBIT(EV_REL, sizeof(device->relBitmask)), device->relBitmask);
1274 ioctl(fd, EVIOCGBIT(EV_SW, sizeof(device->swBitmask)), device->swBitmask);
1275 ioctl(fd, EVIOCGBIT(EV_LED, sizeof(device->ledBitmask)), device->ledBitmask);
1276 ioctl(fd, EVIOCGBIT(EV_FF, sizeof(device->ffBitmask)), device->ffBitmask);
1277 ioctl(fd, EVIOCGPROP(sizeof(device->propBitmask)), device->propBitmask);
1278
1279 // See if this is a keyboard. Ignore everything in the button range except for
1280 // joystick and gamepad buttons which are handled like keyboards for the most part.
1281 bool haveKeyboardKeys = containsNonZeroByte(device->keyBitmask, 0, sizeof_bit_array(BTN_MISC))
1282 || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(KEY_OK),
1283 sizeof_bit_array(KEY_MAX + 1));
1284 bool haveGamepadButtons = containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_MISC),
1285 sizeof_bit_array(BTN_MOUSE))
1286 || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_JOYSTICK),
1287 sizeof_bit_array(BTN_DIGI));
1288 if (haveKeyboardKeys || haveGamepadButtons) {
1289 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1290 }
1291
1292 // See if this is a cursor device such as a trackball or mouse.
1293 if (test_bit(BTN_MOUSE, device->keyBitmask)
1294 && test_bit(REL_X, device->relBitmask)
1295 && test_bit(REL_Y, device->relBitmask)) {
1296 device->classes |= INPUT_DEVICE_CLASS_CURSOR;
1297 }
1298
Prashant Malani1941ff52015-08-11 18:29:28 -07001299 // See if this is a rotary encoder type device.
1300 String8 deviceType = String8();
1301 if (device->configuration &&
1302 device->configuration->tryGetProperty(String8("device.type"), deviceType)) {
1303 if (!deviceType.compare(String8("rotaryEncoder"))) {
1304 device->classes |= INPUT_DEVICE_CLASS_ROTARY_ENCODER;
1305 }
1306 }
1307
Michael Wrightd02c5b62014-02-10 15:10:22 -08001308 // See if this is a touch pad.
1309 // Is this a new modern multi-touch driver?
1310 if (test_bit(ABS_MT_POSITION_X, device->absBitmask)
1311 && test_bit(ABS_MT_POSITION_Y, device->absBitmask)) {
1312 // Some joysticks such as the PS3 controller report axes that conflict
1313 // with the ABS_MT range. Try to confirm that the device really is
1314 // a touch screen.
1315 if (test_bit(BTN_TOUCH, device->keyBitmask) || !haveGamepadButtons) {
1316 device->classes |= INPUT_DEVICE_CLASS_TOUCH | INPUT_DEVICE_CLASS_TOUCH_MT;
1317 }
1318 // Is this an old style single-touch driver?
1319 } else if (test_bit(BTN_TOUCH, device->keyBitmask)
1320 && test_bit(ABS_X, device->absBitmask)
1321 && test_bit(ABS_Y, device->absBitmask)) {
1322 device->classes |= INPUT_DEVICE_CLASS_TOUCH;
Michael Wright842500e2015-03-13 17:32:02 -07001323 // Is this a BT stylus?
1324 } else if ((test_bit(ABS_PRESSURE, device->absBitmask) ||
1325 test_bit(BTN_TOUCH, device->keyBitmask))
1326 && !test_bit(ABS_X, device->absBitmask)
1327 && !test_bit(ABS_Y, device->absBitmask)) {
1328 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
1329 // Keyboard will try to claim some of the buttons but we really want to reserve those so we
1330 // can fuse it with the touch screen data, so just take them back. Note this means an
1331 // external stylus cannot also be a keyboard device.
1332 device->classes &= ~INPUT_DEVICE_CLASS_KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001333 }
1334
1335 // See if this device is a joystick.
1336 // Assumes that joysticks always have gamepad buttons in order to distinguish them
1337 // from other devices such as accelerometers that also have absolute axes.
1338 if (haveGamepadButtons) {
1339 uint32_t assumedClasses = device->classes | INPUT_DEVICE_CLASS_JOYSTICK;
1340 for (int i = 0; i <= ABS_MAX; i++) {
1341 if (test_bit(i, device->absBitmask)
1342 && (getAbsAxisUsage(i, assumedClasses) & INPUT_DEVICE_CLASS_JOYSTICK)) {
1343 device->classes = assumedClasses;
1344 break;
1345 }
1346 }
1347 }
1348
1349 // Check whether this device has switches.
1350 for (int i = 0; i <= SW_MAX; i++) {
1351 if (test_bit(i, device->swBitmask)) {
1352 device->classes |= INPUT_DEVICE_CLASS_SWITCH;
1353 break;
1354 }
1355 }
1356
1357 // Check whether this device supports the vibrator.
1358 if (test_bit(FF_RUMBLE, device->ffBitmask)) {
1359 device->classes |= INPUT_DEVICE_CLASS_VIBRATOR;
1360 }
1361
1362 // Configure virtual keys.
1363 if ((device->classes & INPUT_DEVICE_CLASS_TOUCH)) {
1364 // Load the virtual keys for the touch screen, if any.
1365 // We do this now so that we can make sure to load the keymap if necessary.
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001366 bool success = loadVirtualKeyMapLocked(device);
1367 if (success) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001368 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1369 }
1370 }
1371
1372 // Load the key map.
1373 // We need to do this for joysticks too because the key layout may specify axes.
1374 status_t keyMapStatus = NAME_NOT_FOUND;
1375 if (device->classes & (INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_JOYSTICK)) {
1376 // Load the keymap for the device.
1377 keyMapStatus = loadKeyMapLocked(device);
1378 }
1379
1380 // Configure the keyboard, gamepad or virtual keyboard.
1381 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1382 // Register the keyboard as a built-in keyboard if it is eligible.
1383 if (!keyMapStatus
1384 && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD
1385 && isEligibleBuiltInKeyboard(device->identifier,
1386 device->configuration, &device->keyMap)) {
1387 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) &&
1397 hasKeycodeLocked(device, AKEYCODE_DPAD_DOWN) &&
1398 hasKeycodeLocked(device, AKEYCODE_DPAD_LEFT) &&
1399 hasKeycodeLocked(device, AKEYCODE_DPAD_RIGHT) &&
1400 hasKeycodeLocked(device, AKEYCODE_DPAD_CENTER)) {
1401 device->classes |= INPUT_DEVICE_CLASS_DPAD;
1402 }
1403
1404 // See if this device has a gamepad.
1405 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES)/sizeof(GAMEPAD_KEYCODES[0]); i++) {
1406 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) {
1415 ALOGV("Dropping device: id=%d, path='%s', name='%s'",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001416 deviceId, devicePath, 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
Michael Wright42f2c6a2014-03-12 10:33:03 -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 }
1445 mUnattachedVideoDevices.erase(std::remove_if(mUnattachedVideoDevices.begin(),
1446 mUnattachedVideoDevices.end(),
1447 [](const std::unique_ptr<TouchVideoDevice>& videoDevice){
1448 return videoDevice == nullptr; }), mUnattachedVideoDevices.end());
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001449
1450 if (registerDeviceForEpollLocked(device) != OK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001451 delete device;
1452 return -1;
1453 }
1454
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001455 configureFd(device);
1456
1457 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=0x%x, "
1458 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001459 deviceId, fd, devicePath, device->identifier.name.c_str(),
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001460 device->classes,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001461 device->configurationFile.c_str(),
1462 device->keyMap.keyLayoutFile.c_str(),
1463 device->keyMap.keyCharacterMapFile.c_str(),
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001464 toString(mBuiltInKeyboardId == deviceId));
1465
1466 addDeviceLocked(device);
1467 return OK;
1468}
1469
1470void EventHub::configureFd(Device* device) {
1471 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
1472 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1473 // Disable kernel key repeat since we handle it ourselves
1474 unsigned int repeatRate[] = {0, 0};
1475 if (ioctl(device->fd, EVIOCSREP, repeatRate)) {
1476 ALOGW("Unable to disable kernel key repeat for %s: %s",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001477 device->path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001478 }
1479 }
1480
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001481 std::string wakeMechanism = "EPOLLWAKEUP";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001482 if (!mUsingEpollWakeup) {
1483#ifndef EVIOCSSUSPENDBLOCK
1484 // uapi headers don't include EVIOCSSUSPENDBLOCK, and future kernels
1485 // will use an epoll flag instead, so as long as we want to support
1486 // this feature, we need to be prepared to define the ioctl ourselves.
1487#define EVIOCSSUSPENDBLOCK _IOW('E', 0x91, int)
1488#endif
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001489 if (ioctl(device->fd, EVIOCSSUSPENDBLOCK, 1)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001490 wakeMechanism = "<none>";
1491 } else {
1492 wakeMechanism = "EVIOCSSUSPENDBLOCK";
1493 }
1494 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001495 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
1496 // associated with input events. This is important because the input system
1497 // uses the timestamps extensively and assumes they were recorded using the monotonic
1498 // clock.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001499 int clockId = CLOCK_MONOTONIC;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001500 bool usingClockIoctl = !ioctl(device->fd, EVIOCSCLOCKID, &clockId);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001501 ALOGI("wakeMechanism=%s, usingClockIoctl=%s", wakeMechanism.c_str(),
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001502 toString(usingClockIoctl));
1503}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001504
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001505void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
1506 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
1507 if (!videoDevice) {
1508 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
1509 return;
1510 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001511 // Transfer ownership of this video device to a matching input device
1512 for (size_t i = 0; i < mDevices.size(); i++) {
1513 Device* device = mDevices.valueAt(i);
1514 if (videoDevice->getName() == device->identifier.name) {
1515 device->videoDevice = std::move(videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001516 if (device->enabled) {
1517 registerVideoDeviceForEpollLocked(*device->videoDevice);
1518 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001519 return;
1520 }
1521 }
1522
1523 // Couldn't find a matching input device, so just add it to a temporary holding queue.
1524 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001525 ALOGI("Adding video device %s to list of unattached video devices",
1526 videoDevice->getName().c_str());
1527 mUnattachedVideoDevices.push_back(std::move(videoDevice));
1528}
1529
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001530bool EventHub::isDeviceEnabled(int32_t deviceId) {
1531 AutoMutex _l(mLock);
1532 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001533 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001534 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1535 return false;
1536 }
1537 return device->enabled;
1538}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001539
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001540status_t EventHub::enableDevice(int32_t deviceId) {
1541 AutoMutex _l(mLock);
1542 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001543 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001544 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1545 return BAD_VALUE;
1546 }
1547 if (device->enabled) {
1548 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
1549 return OK;
1550 }
1551 status_t result = device->enable();
1552 if (result != OK) {
1553 ALOGE("Failed to enable device %" PRId32, deviceId);
1554 return result;
1555 }
1556
1557 configureFd(device);
1558
1559 return registerDeviceForEpollLocked(device);
1560}
1561
1562status_t EventHub::disableDevice(int32_t deviceId) {
1563 AutoMutex _l(mLock);
1564 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001565 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001566 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1567 return BAD_VALUE;
1568 }
1569 if (!device->enabled) {
1570 ALOGW("Duplicate call to %s, input device already disabled", __func__);
1571 return OK;
1572 }
1573 unregisterDeviceFromEpollLocked(device);
1574 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001575}
1576
1577void EventHub::createVirtualKeyboardLocked() {
1578 InputDeviceIdentifier identifier;
1579 identifier.name = "Virtual";
1580 identifier.uniqueId = "<virtual>";
1581 assignDescriptorLocked(identifier);
1582
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001583 Device* device = new Device(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
1584 identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001585 device->classes = INPUT_DEVICE_CLASS_KEYBOARD
1586 | INPUT_DEVICE_CLASS_ALPHAKEY
1587 | INPUT_DEVICE_CLASS_DPAD
1588 | INPUT_DEVICE_CLASS_VIRTUAL;
1589 loadKeyMapLocked(device);
1590 addDeviceLocked(device);
1591}
1592
1593void EventHub::addDeviceLocked(Device* device) {
1594 mDevices.add(device->id, device);
1595 device->next = mOpeningDevices;
1596 mOpeningDevices = device;
1597}
1598
1599void EventHub::loadConfigurationLocked(Device* device) {
1600 device->configurationFile = getInputDeviceConfigurationFilePathByDeviceIdentifier(
1601 device->identifier, INPUT_DEVICE_CONFIGURATION_FILE_TYPE_CONFIGURATION);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001602 if (device->configurationFile.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001603 ALOGD("No input device configuration file found for device '%s'.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001604 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001605 } else {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001606 status_t status = PropertyMap::load(String8(device->configurationFile.c_str()),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001607 &device->configuration);
1608 if (status) {
1609 ALOGE("Error loading input device configuration file for device '%s'. "
1610 "Using default configuration.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001611 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001612 }
1613 }
1614}
1615
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001616bool EventHub::loadVirtualKeyMapLocked(Device* device) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001617 // The virtual key map is supplied by the kernel as a system board property file.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001618 std::string path;
1619 path += "/sys/board_properties/virtualkeys.";
1620 path += device->identifier.name;
1621 if (access(path.c_str(), R_OK)) {
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001622 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001623 }
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001624 device->virtualKeyMap = VirtualKeyMap::load(path);
1625 return device->virtualKeyMap != nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001626}
1627
1628status_t EventHub::loadKeyMapLocked(Device* device) {
1629 return device->keyMap.load(device->identifier, device->configuration);
1630}
1631
1632bool EventHub::isExternalDeviceLocked(Device* device) {
1633 if (device->configuration) {
1634 bool value;
1635 if (device->configuration->tryGetProperty(String8("device.internal"), value)) {
1636 return !value;
1637 }
1638 }
1639 return device->identifier.bus == BUS_USB || device->identifier.bus == BUS_BLUETOOTH;
1640}
1641
Tim Kilbourn063ff532015-04-08 10:26:18 -07001642bool EventHub::deviceHasMicLocked(Device* device) {
1643 if (device->configuration) {
1644 bool value;
1645 if (device->configuration->tryGetProperty(String8("audio.mic"), value)) {
1646 return value;
1647 }
1648 }
1649 return false;
1650}
1651
Michael Wrightd02c5b62014-02-10 15:10:22 -08001652int32_t EventHub::getNextControllerNumberLocked(Device* device) {
1653 if (mControllerNumbers.isFull()) {
1654 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001655 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001656 return 0;
1657 }
1658 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
1659 // one
1660 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
1661}
1662
1663void EventHub::releaseControllerNumberLocked(Device* device) {
1664 int32_t num = device->controllerNumber;
1665 device->controllerNumber= 0;
1666 if (num == 0) {
1667 return;
1668 }
1669 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
1670}
1671
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001672void EventHub::setLedForControllerLocked(Device* device) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001673 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
1674 setLedStateLocked(device, ALED_CONTROLLER_1 + i, device->controllerNumber == i + 1);
1675 }
1676}
1677
1678bool EventHub::hasKeycodeLocked(Device* device, int keycode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001679 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001680 return false;
1681 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001682
Michael Wrightd02c5b62014-02-10 15:10:22 -08001683 Vector<int32_t> scanCodes;
1684 device->keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes);
1685 const size_t N = scanCodes.size();
1686 for (size_t i=0; i<N && i<=KEY_MAX; i++) {
1687 int32_t sc = scanCodes.itemAt(i);
1688 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, device->keyBitmask)) {
1689 return true;
1690 }
1691 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001692
Michael Wrightd02c5b62014-02-10 15:10:22 -08001693 return false;
1694}
1695
1696status_t EventHub::mapLed(Device* device, int32_t led, int32_t* outScanCode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001697 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001698 return NAME_NOT_FOUND;
1699 }
1700
1701 int32_t scanCode;
1702 if(device->keyMap.keyLayoutMap->findScanCodeForLed(led, &scanCode) != NAME_NOT_FOUND) {
1703 if(scanCode >= 0 && scanCode <= LED_MAX && test_bit(scanCode, device->ledBitmask)) {
1704 *outScanCode = scanCode;
1705 return NO_ERROR;
1706 }
1707 }
1708 return NAME_NOT_FOUND;
1709}
1710
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001711void EventHub::closeDeviceByPathLocked(const char *devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001712 Device* device = getDeviceByPathLocked(devicePath);
1713 if (device) {
1714 closeDeviceLocked(device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001715 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001716 }
1717 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001718}
1719
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001720/**
1721 * Find the video device by filename, and close it.
1722 * The video device is closed by path during an inotify event, where we don't have the
1723 * additional context about the video device fd, or the associated input device.
1724 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001725void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001726 // A video device may be owned by an existing input device, or it may be stored in
1727 // the mUnattachedVideoDevices queue. Check both locations.
1728 for (size_t i = 0; i < mDevices.size(); i++) {
1729 Device* device = mDevices.valueAt(i);
1730 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001731 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001732 device->videoDevice = nullptr;
1733 return;
1734 }
1735 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001736 mUnattachedVideoDevices.erase(std::remove_if(mUnattachedVideoDevices.begin(),
1737 mUnattachedVideoDevices.end(), [&devicePath](
1738 const std::unique_ptr<TouchVideoDevice>& videoDevice) {
1739 return videoDevice->getPath() == devicePath; }), mUnattachedVideoDevices.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001740}
1741
1742void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001743 mUnattachedVideoDevices.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001744 while (mDevices.size() > 0) {
1745 closeDeviceLocked(mDevices.valueAt(mDevices.size() - 1));
1746 }
1747}
1748
1749void EventHub::closeDeviceLocked(Device* device) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001750 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=0x%x",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001751 device->path.c_str(), device->identifier.name.c_str(), device->id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001752 device->fd, device->classes);
1753
1754 if (device->id == mBuiltInKeyboardId) {
1755 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001756 device->path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001757 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
1758 }
1759
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001760 unregisterDeviceFromEpollLocked(device);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001761 if (device->videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001762 // This must be done after the video device is removed from epoll
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001763 mUnattachedVideoDevices.push_back(std::move(device->videoDevice));
1764 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001765
1766 releaseControllerNumberLocked(device);
1767
1768 mDevices.removeItem(device->id);
1769 device->close();
1770
1771 // Unlink for opening devices list if it is present.
Yi Kong9b14ac62018-07-17 13:48:38 -07001772 Device* pred = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001773 bool found = false;
Yi Kong9b14ac62018-07-17 13:48:38 -07001774 for (Device* entry = mOpeningDevices; entry != nullptr; ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001775 if (entry == device) {
1776 found = true;
1777 break;
1778 }
1779 pred = entry;
1780 entry = entry->next;
1781 }
1782 if (found) {
1783 // Unlink the device from the opening devices list then delete it.
1784 // We don't need to tell the client that the device was closed because
1785 // it does not even know it was opened in the first place.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001786 ALOGI("Device %s was immediately closed after opening.", device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001787 if (pred) {
1788 pred->next = device->next;
1789 } else {
1790 mOpeningDevices = device->next;
1791 }
1792 delete device;
1793 } else {
1794 // Link into closing devices list.
1795 // The device will be deleted later after we have informed the client.
1796 device->next = mClosingDevices;
1797 mClosingDevices = device;
1798 }
1799}
1800
1801status_t EventHub::readNotifyLocked() {
1802 int res;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001803 char event_buf[512];
1804 int event_size;
1805 int event_pos = 0;
1806 struct inotify_event *event;
1807
1808 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
1809 res = read(mINotifyFd, event_buf, sizeof(event_buf));
1810 if(res < (int)sizeof(*event)) {
1811 if(errno == EINTR)
1812 return 0;
1813 ALOGW("could not get event, %s\n", strerror(errno));
1814 return -1;
1815 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001816
1817 while(res >= (int)sizeof(*event)) {
1818 event = (struct inotify_event *)(event_buf + event_pos);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001819 if(event->len) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001820 if (event->wd == mInputWd) {
1821 std::string filename = StringPrintf("%s/%s", DEVICE_PATH, event->name);
1822 if(event->mask & IN_CREATE) {
1823 openDeviceLocked(filename.c_str());
1824 } else {
1825 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
1826 closeDeviceByPathLocked(filename.c_str());
1827 }
1828 }
1829 else if (event->wd == mVideoWd) {
1830 if (isV4lTouchNode(event->name)) {
1831 std::string filename = StringPrintf("%s/%s", VIDEO_DEVICE_PATH, event->name);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001832 if (event->mask & IN_CREATE) {
1833 openVideoDeviceLocked(filename);
1834 } else {
1835 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
1836 closeVideoDeviceByPathLocked(filename);
1837 }
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001838 }
1839 }
1840 else {
1841 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event->wd);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001842 }
1843 }
1844 event_size = sizeof(*event) + event->len;
1845 res -= event_size;
1846 event_pos += event_size;
1847 }
1848 return 0;
1849}
1850
1851status_t EventHub::scanDirLocked(const char *dirname)
1852{
1853 char devname[PATH_MAX];
1854 char *filename;
1855 DIR *dir;
1856 struct dirent *de;
1857 dir = opendir(dirname);
Yi Kong9b14ac62018-07-17 13:48:38 -07001858 if(dir == nullptr)
Michael Wrightd02c5b62014-02-10 15:10:22 -08001859 return -1;
1860 strcpy(devname, dirname);
1861 filename = devname + strlen(devname);
1862 *filename++ = '/';
1863 while((de = readdir(dir))) {
1864 if(de->d_name[0] == '.' &&
1865 (de->d_name[1] == '\0' ||
1866 (de->d_name[1] == '.' && de->d_name[2] == '\0')))
1867 continue;
1868 strcpy(filename, de->d_name);
1869 openDeviceLocked(devname);
1870 }
1871 closedir(dir);
1872 return 0;
1873}
1874
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001875/**
1876 * Look for all dirname/v4l-touch* devices, and open them.
1877 */
1878status_t EventHub::scanVideoDirLocked(const std::string& dirname)
1879{
1880 DIR* dir;
1881 struct dirent* de;
1882 dir = opendir(dirname.c_str());
1883 if(!dir) {
1884 ALOGE("Could not open video directory %s", dirname.c_str());
1885 return BAD_VALUE;
1886 }
1887
1888 while((de = readdir(dir))) {
1889 const char* name = de->d_name;
1890 if (isV4lTouchNode(name)) {
1891 ALOGI("Found touch video device %s", name);
1892 openVideoDeviceLocked(dirname + "/" + name);
1893 }
1894 }
1895 closedir(dir);
1896 return OK;
1897}
1898
Michael Wrightd02c5b62014-02-10 15:10:22 -08001899void EventHub::requestReopenDevices() {
1900 ALOGV("requestReopenDevices() called");
1901
1902 AutoMutex _l(mLock);
1903 mNeedToReopenDevices = true;
1904}
1905
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001906void EventHub::dump(std::string& dump) {
1907 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001908
1909 { // acquire lock
1910 AutoMutex _l(mLock);
1911
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001912 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001913
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001914 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001915
1916 for (size_t i = 0; i < mDevices.size(); i++) {
1917 const Device* device = mDevices.valueAt(i);
1918 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001919 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001920 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001921 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001922 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001923 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001924 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001925 dump += StringPrintf(INDENT3 "Classes: 0x%08x\n", device->classes);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001926 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001927 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001928 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
1929 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001930 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001931 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001932 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08001933 "product=0x%04x, version=0x%04x\n",
1934 device->identifier.bus, device->identifier.vendor,
1935 device->identifier.product, device->identifier.version);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001936 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001937 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001938 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001939 device->keyMap.keyCharacterMapFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001940 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001941 device->configurationFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001942 dump += StringPrintf(INDENT3 "HaveKeyboardLayoutOverlay: %s\n",
Yi Kong9b14ac62018-07-17 13:48:38 -07001943 toString(device->overlayKeyMap != nullptr));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001944 dump += INDENT3 "VideoDevice: ";
1945 if (device->videoDevice) {
1946 dump += device->videoDevice->dump() + "\n";
1947 } else {
1948 dump += "<none>\n";
1949 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001950 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001951
1952 dump += INDENT "Unattached video devices:\n";
1953 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
1954 dump += INDENT2 + videoDevice->dump() + "\n";
1955 }
1956 if (mUnattachedVideoDevices.empty()) {
1957 dump += INDENT2 "<none>\n";
1958 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001959 } // release lock
1960}
1961
1962void EventHub::monitor() {
1963 // Acquire and release the lock to ensure that the event hub has not deadlocked.
1964 mLock.lock();
1965 mLock.unlock();
1966}
1967
1968
1969}; // namespace android