blob: c13bac6a12355789d1ea8c1aa0a4a62398839a6b [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;
205 delete virtualKeyMap;
206}
207
208void EventHub::Device::close() {
209 if (fd >= 0) {
210 ::close(fd);
211 fd = -1;
212 }
213}
214
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700215status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100216 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700217 if(fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100218 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700219 return -errno;
220 }
221 enabled = true;
222 return OK;
223}
224
225status_t EventHub::Device::disable() {
226 close();
227 enabled = false;
228 return OK;
229}
230
231bool EventHub::Device::hasValidFd() {
232 return !isVirtual && enabled;
233}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800234
235// --- EventHub ---
236
Michael Wrightd02c5b62014-02-10 15:10:22 -0800237const int EventHub::EPOLL_MAX_EVENTS;
238
239EventHub::EventHub(void) :
240 mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD), mNextDeviceId(1), mControllerNumbers(),
Yi Kong9b14ac62018-07-17 13:48:38 -0700241 mOpeningDevices(nullptr), mClosingDevices(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800242 mNeedToSendFinishedDeviceScan(false),
243 mNeedToReopenDevices(false), mNeedToScanDevices(true),
244 mPendingEventCount(0), mPendingEventIndex(0), mPendingINotify(false) {
245 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
246
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800247 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800248 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800249
250 mINotifyFd = inotify_init();
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800251 mInputWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
252 LOG_ALWAYS_FATAL_IF(mInputWd < 0, "Could not register INotify for %s: %s",
253 DEVICE_PATH, strerror(errno));
Philip Quinn39b81682019-01-09 22:20:39 -0800254 if (isV4lScanningEnabled()) {
255 mVideoWd = inotify_add_watch(mINotifyFd, VIDEO_DEVICE_PATH, IN_DELETE | IN_CREATE);
256 LOG_ALWAYS_FATAL_IF(mVideoWd < 0, "Could not register INotify for %s: %s",
257 VIDEO_DEVICE_PATH, strerror(errno));
258 } else {
259 mVideoWd = -1;
260 ALOGI("Video device scanning disabled");
261 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800262
263 struct epoll_event eventItem;
264 memset(&eventItem, 0, sizeof(eventItem));
265 eventItem.events = EPOLLIN;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700266 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800267 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800268 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
269
270 int wakeFds[2];
271 result = pipe(wakeFds);
272 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
273
274 mWakeReadPipeFd = wakeFds[0];
275 mWakeWritePipeFd = wakeFds[1];
276
277 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
278 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
279 errno);
280
281 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
282 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
283 errno);
284
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700285 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800286 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
287 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
288 errno);
289
290 int major, minor;
291 getLinuxRelease(&major, &minor);
292 // EPOLLWAKEUP was introduced in kernel 3.5
293 mUsingEpollWakeup = major > 3 || (major == 3 && minor >= 5);
294}
295
296EventHub::~EventHub(void) {
297 closeAllDevicesLocked();
298
299 while (mClosingDevices) {
300 Device* device = mClosingDevices;
301 mClosingDevices = device->next;
302 delete device;
303 }
304
305 ::close(mEpollFd);
306 ::close(mINotifyFd);
307 ::close(mWakeReadPipeFd);
308 ::close(mWakeWritePipeFd);
309
310 release_wake_lock(WAKE_LOCK_ID);
311}
312
313InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
314 AutoMutex _l(mLock);
315 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700316 if (device == nullptr) return InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800317 return device->identifier;
318}
319
320uint32_t EventHub::getDeviceClasses(int32_t deviceId) const {
321 AutoMutex _l(mLock);
322 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700323 if (device == nullptr) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800324 return device->classes;
325}
326
327int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
328 AutoMutex _l(mLock);
329 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700330 if (device == nullptr) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800331 return device->controllerNumber;
332}
333
334void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
335 AutoMutex _l(mLock);
336 Device* device = getDeviceLocked(deviceId);
337 if (device && device->configuration) {
338 *outConfiguration = *device->configuration;
339 } else {
340 outConfiguration->clear();
341 }
342}
343
344status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
345 RawAbsoluteAxisInfo* outAxisInfo) const {
346 outAxisInfo->clear();
347
348 if (axis >= 0 && axis <= ABS_MAX) {
349 AutoMutex _l(mLock);
350
351 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700352 if (device && device->hasValidFd() && test_bit(axis, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800353 struct input_absinfo info;
354 if(ioctl(device->fd, EVIOCGABS(axis), &info)) {
355 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100356 axis, device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800357 return -errno;
358 }
359
360 if (info.minimum != info.maximum) {
361 outAxisInfo->valid = true;
362 outAxisInfo->minValue = info.minimum;
363 outAxisInfo->maxValue = info.maximum;
364 outAxisInfo->flat = info.flat;
365 outAxisInfo->fuzz = info.fuzz;
366 outAxisInfo->resolution = info.resolution;
367 }
368 return OK;
369 }
370 }
371 return -1;
372}
373
374bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
375 if (axis >= 0 && axis <= REL_MAX) {
376 AutoMutex _l(mLock);
377
378 Device* device = getDeviceLocked(deviceId);
379 if (device) {
380 return test_bit(axis, device->relBitmask);
381 }
382 }
383 return false;
384}
385
386bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
387 if (property >= 0 && property <= INPUT_PROP_MAX) {
388 AutoMutex _l(mLock);
389
390 Device* device = getDeviceLocked(deviceId);
391 if (device) {
392 return test_bit(property, device->propBitmask);
393 }
394 }
395 return false;
396}
397
398int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
399 if (scanCode >= 0 && scanCode <= KEY_MAX) {
400 AutoMutex _l(mLock);
401
402 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700403 if (device && device->hasValidFd() && test_bit(scanCode, device->keyBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800404 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
405 memset(keyState, 0, sizeof(keyState));
406 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
407 return test_bit(scanCode, keyState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
408 }
409 }
410 }
411 return AKEY_STATE_UNKNOWN;
412}
413
414int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
415 AutoMutex _l(mLock);
416
417 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700418 if (device && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800419 Vector<int32_t> scanCodes;
420 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode, &scanCodes);
421 if (scanCodes.size() != 0) {
422 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
423 memset(keyState, 0, sizeof(keyState));
424 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
425 for (size_t i = 0; i < scanCodes.size(); i++) {
426 int32_t sc = scanCodes.itemAt(i);
427 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, keyState)) {
428 return AKEY_STATE_DOWN;
429 }
430 }
431 return AKEY_STATE_UP;
432 }
433 }
434 }
435 return AKEY_STATE_UNKNOWN;
436}
437
438int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
439 if (sw >= 0 && sw <= SW_MAX) {
440 AutoMutex _l(mLock);
441
442 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700443 if (device && device->hasValidFd() && test_bit(sw, device->swBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800444 uint8_t swState[sizeof_bit_array(SW_MAX + 1)];
445 memset(swState, 0, sizeof(swState));
446 if (ioctl(device->fd, EVIOCGSW(sizeof(swState)), swState) >= 0) {
447 return test_bit(sw, swState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
448 }
449 }
450 }
451 return AKEY_STATE_UNKNOWN;
452}
453
454status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
455 *outValue = 0;
456
457 if (axis >= 0 && axis <= ABS_MAX) {
458 AutoMutex _l(mLock);
459
460 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700461 if (device && device->hasValidFd() && test_bit(axis, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800462 struct input_absinfo info;
463 if(ioctl(device->fd, EVIOCGABS(axis), &info)) {
464 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100465 axis, device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800466 return -errno;
467 }
468
469 *outValue = info.value;
470 return OK;
471 }
472 }
473 return -1;
474}
475
476bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes,
477 const int32_t* keyCodes, uint8_t* outFlags) const {
478 AutoMutex _l(mLock);
479
480 Device* device = getDeviceLocked(deviceId);
481 if (device && device->keyMap.haveKeyLayout()) {
482 Vector<int32_t> scanCodes;
483 for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) {
484 scanCodes.clear();
485
486 status_t err = device->keyMap.keyLayoutMap->findScanCodesForKey(
487 keyCodes[codeIndex], &scanCodes);
488 if (! err) {
489 // check the possible scan codes identified by the layout map against the
490 // map of codes actually emitted by the driver
491 for (size_t sc = 0; sc < scanCodes.size(); sc++) {
492 if (test_bit(scanCodes[sc], device->keyBitmask)) {
493 outFlags[codeIndex] = 1;
494 break;
495 }
496 }
497 }
498 }
499 return true;
500 }
501 return false;
502}
503
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700504status_t EventHub::mapKey(int32_t deviceId,
505 int32_t scanCode, int32_t usageCode, int32_t metaState,
506 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800507 AutoMutex _l(mLock);
508 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700509 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800510
511 if (device) {
512 // Check the key character map first.
513 sp<KeyCharacterMap> kcm = device->getKeyCharacterMap();
Yi Kong9b14ac62018-07-17 13:48:38 -0700514 if (kcm != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800515 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
516 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700517 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800518 }
519 }
520
521 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700522 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800523 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700524 status = NO_ERROR;
525 }
526 }
527
528 if (status == NO_ERROR) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700529 if (kcm != nullptr) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700530 kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState);
531 } else {
532 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800533 }
534 }
535 }
536
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700537 if (status != NO_ERROR) {
538 *outKeycode = 0;
539 *outFlags = 0;
540 *outMetaState = metaState;
541 }
542
543 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800544}
545
546status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
547 AutoMutex _l(mLock);
548 Device* device = getDeviceLocked(deviceId);
549
550 if (device && device->keyMap.haveKeyLayout()) {
551 status_t err = device->keyMap.keyLayoutMap->mapAxis(scanCode, outAxisInfo);
552 if (err == NO_ERROR) {
553 return NO_ERROR;
554 }
555 }
556
557 return NAME_NOT_FOUND;
558}
559
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100560void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800561 AutoMutex _l(mLock);
562
563 mExcludedDevices = devices;
564}
565
566bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
567 AutoMutex _l(mLock);
568 Device* device = getDeviceLocked(deviceId);
569 if (device && scanCode >= 0 && scanCode <= KEY_MAX) {
570 if (test_bit(scanCode, device->keyBitmask)) {
571 return true;
572 }
573 }
574 return false;
575}
576
577bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
578 AutoMutex _l(mLock);
579 Device* device = getDeviceLocked(deviceId);
580 int32_t sc;
581 if (device && mapLed(device, led, &sc) == NO_ERROR) {
582 if (test_bit(sc, device->ledBitmask)) {
583 return true;
584 }
585 }
586 return false;
587}
588
589void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
590 AutoMutex _l(mLock);
591 Device* device = getDeviceLocked(deviceId);
592 setLedStateLocked(device, led, on);
593}
594
595void EventHub::setLedStateLocked(Device* device, int32_t led, bool on) {
596 int32_t sc;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700597 if (device && device->hasValidFd() && mapLed(device, led, &sc) != NAME_NOT_FOUND) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800598 struct input_event ev;
599 ev.time.tv_sec = 0;
600 ev.time.tv_usec = 0;
601 ev.type = EV_LED;
602 ev.code = sc;
603 ev.value = on ? 1 : 0;
604
605 ssize_t nWrite;
606 do {
607 nWrite = write(device->fd, &ev, sizeof(struct input_event));
608 } while (nWrite == -1 && errno == EINTR);
609 }
610}
611
612void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
613 Vector<VirtualKeyDefinition>& outVirtualKeys) const {
614 outVirtualKeys.clear();
615
616 AutoMutex _l(mLock);
617 Device* device = getDeviceLocked(deviceId);
618 if (device && device->virtualKeyMap) {
619 outVirtualKeys.appendVector(device->virtualKeyMap->getVirtualKeys());
620 }
621}
622
623sp<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
624 AutoMutex _l(mLock);
625 Device* device = getDeviceLocked(deviceId);
626 if (device) {
627 return device->getKeyCharacterMap();
628 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700629 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800630}
631
632bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId,
633 const sp<KeyCharacterMap>& map) {
634 AutoMutex _l(mLock);
635 Device* device = getDeviceLocked(deviceId);
636 if (device) {
637 if (map != device->overlayKeyMap) {
638 device->overlayKeyMap = map;
639 device->combinedKeyMap = KeyCharacterMap::combine(
640 device->keyMap.keyCharacterMap, map);
641 return true;
642 }
643 }
644 return false;
645}
646
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100647static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
648 std::string rawDescriptor;
649 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800650 identifier.product);
651 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100652 if (!identifier.uniqueId.empty()) {
653 rawDescriptor += "uniqueId:";
654 rawDescriptor += identifier.uniqueId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800655 } else if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100656 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800657 }
658
659 if (identifier.vendor == 0 && identifier.product == 0) {
660 // If we don't know the vendor and product id, then the device is probably
661 // built-in so we need to rely on other information to uniquely identify
662 // the input device. Usually we try to avoid relying on the device name or
663 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100664 if (!identifier.name.empty()) {
665 rawDescriptor += "name:";
666 rawDescriptor += identifier.name;
667 } else if (!identifier.location.empty()) {
668 rawDescriptor += "location:";
669 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800670 }
671 }
672 identifier.descriptor = sha1(rawDescriptor);
673 return rawDescriptor;
674}
675
676void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
677 // Compute a device descriptor that uniquely identifies the device.
678 // The descriptor is assumed to be a stable identifier. Its value should not
679 // change between reboots, reconnections, firmware updates or new releases
680 // of Android. In practice we sometimes get devices that cannot be uniquely
681 // identified. In this case we enforce uniqueness between connected devices.
682 // Ideally, we also want the descriptor to be short and relatively opaque.
683
684 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100685 std::string rawDescriptor = generateDescriptor(identifier);
686 if (identifier.uniqueId.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800687 // If it didn't have a unique id check for conflicts and enforce
688 // uniqueness if necessary.
Yi Kong9b14ac62018-07-17 13:48:38 -0700689 while(getDeviceByDescriptorLocked(identifier.descriptor) != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800690 identifier.nonce++;
691 rawDescriptor = generateDescriptor(identifier);
692 }
693 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100694 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
695 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800696}
697
698void EventHub::vibrate(int32_t deviceId, nsecs_t duration) {
699 AutoMutex _l(mLock);
700 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700701 if (device && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800702 ff_effect effect;
703 memset(&effect, 0, sizeof(effect));
704 effect.type = FF_RUMBLE;
705 effect.id = device->ffEffectId;
706 effect.u.rumble.strong_magnitude = 0xc000;
707 effect.u.rumble.weak_magnitude = 0xc000;
708 effect.replay.length = (duration + 999999LL) / 1000000LL;
709 effect.replay.delay = 0;
710 if (ioctl(device->fd, EVIOCSFF, &effect)) {
711 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100712 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800713 return;
714 }
715 device->ffEffectId = effect.id;
716
717 struct input_event ev;
718 ev.time.tv_sec = 0;
719 ev.time.tv_usec = 0;
720 ev.type = EV_FF;
721 ev.code = device->ffEffectId;
722 ev.value = 1;
723 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
724 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100725 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800726 return;
727 }
728 device->ffEffectPlaying = true;
729 }
730}
731
732void EventHub::cancelVibrate(int32_t deviceId) {
733 AutoMutex _l(mLock);
734 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700735 if (device && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800736 if (device->ffEffectPlaying) {
737 device->ffEffectPlaying = false;
738
739 struct input_event ev;
740 ev.time.tv_sec = 0;
741 ev.time.tv_usec = 0;
742 ev.type = EV_FF;
743 ev.code = device->ffEffectId;
744 ev.value = 0;
745 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
746 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100747 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800748 return;
749 }
750 }
751 }
752}
753
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100754EventHub::Device* EventHub::getDeviceByDescriptorLocked(const std::string& descriptor) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800755 size_t size = mDevices.size();
756 for (size_t i = 0; i < size; i++) {
757 Device* device = mDevices.valueAt(i);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100758 if (descriptor == device->identifier.descriptor) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800759 return device;
760 }
761 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700762 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800763}
764
765EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -0800766 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800767 deviceId = mBuiltInKeyboardId;
768 }
769 ssize_t index = mDevices.indexOfKey(deviceId);
770 return index >= 0 ? mDevices.valueAt(index) : NULL;
771}
772
773EventHub::Device* EventHub::getDeviceByPathLocked(const char* devicePath) const {
774 for (size_t i = 0; i < mDevices.size(); i++) {
775 Device* device = mDevices.valueAt(i);
776 if (device->path == devicePath) {
777 return device;
778 }
779 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700780 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800781}
782
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700783/**
784 * The file descriptor could be either input device, or a video device (associated with a
785 * specific input device). Check both cases here, and return the device that this event
786 * belongs to. Caller can compare the fd's once more to determine event type.
787 * Looks through all input devices, and only attached video devices. Unattached video
788 * devices are ignored.
789 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700790EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
791 for (size_t i = 0; i < mDevices.size(); i++) {
792 Device* device = mDevices.valueAt(i);
793 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700794 // This is an input device event
795 return device;
796 }
797 if (device->videoDevice && device->videoDevice->getFd() == fd) {
798 // This is a video device event
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700799 return device;
800 }
801 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700802 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
803 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700804 return nullptr;
805}
806
Michael Wrightd02c5b62014-02-10 15:10:22 -0800807size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
808 ALOG_ASSERT(bufferSize >= 1);
809
810 AutoMutex _l(mLock);
811
812 struct input_event readBuffer[bufferSize];
813
814 RawEvent* event = buffer;
815 size_t capacity = bufferSize;
816 bool awoken = false;
817 for (;;) {
818 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
819
820 // Reopen input devices if needed.
821 if (mNeedToReopenDevices) {
822 mNeedToReopenDevices = false;
823
824 ALOGI("Reopening all input devices due to a configuration change.");
825
826 closeAllDevicesLocked();
827 mNeedToScanDevices = true;
828 break; // return to the caller before we actually rescan
829 }
830
831 // Report any devices that had last been added/removed.
832 while (mClosingDevices) {
833 Device* device = mClosingDevices;
834 ALOGV("Reporting device closed: id=%d, name=%s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100835 device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800836 mClosingDevices = device->next;
837 event->when = now;
Prabir Pradhancae4b3a2019-02-05 18:51:32 -0800838 event->deviceId = (device->id == mBuiltInKeyboardId) ?
839 ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800840 event->type = DEVICE_REMOVED;
841 event += 1;
842 delete device;
843 mNeedToSendFinishedDeviceScan = true;
844 if (--capacity == 0) {
845 break;
846 }
847 }
848
849 if (mNeedToScanDevices) {
850 mNeedToScanDevices = false;
851 scanDevicesLocked();
852 mNeedToSendFinishedDeviceScan = true;
853 }
854
Yi Kong9b14ac62018-07-17 13:48:38 -0700855 while (mOpeningDevices != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800856 Device* device = mOpeningDevices;
857 ALOGV("Reporting device opened: id=%d, name=%s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100858 device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800859 mOpeningDevices = device->next;
860 event->when = now;
861 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
862 event->type = DEVICE_ADDED;
863 event += 1;
864 mNeedToSendFinishedDeviceScan = true;
865 if (--capacity == 0) {
866 break;
867 }
868 }
869
870 if (mNeedToSendFinishedDeviceScan) {
871 mNeedToSendFinishedDeviceScan = false;
872 event->when = now;
873 event->type = FINISHED_DEVICE_SCAN;
874 event += 1;
875 if (--capacity == 0) {
876 break;
877 }
878 }
879
880 // Grab the next input event.
881 bool deviceChanged = false;
882 while (mPendingEventIndex < mPendingEventCount) {
883 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700884 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800885 if (eventItem.events & EPOLLIN) {
886 mPendingINotify = true;
887 } else {
888 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
889 }
890 continue;
891 }
892
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700893 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800894 if (eventItem.events & EPOLLIN) {
895 ALOGV("awoken after wake()");
896 awoken = true;
897 char buffer[16];
898 ssize_t nRead;
899 do {
900 nRead = read(mWakeReadPipeFd, buffer, sizeof(buffer));
901 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(buffer));
902 } else {
903 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
904 eventItem.events);
905 }
906 continue;
907 }
908
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700909 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700910 if (!device) {
911 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.",
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700912 eventItem.events, eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700913 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800914 continue;
915 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700916 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
917 if (eventItem.events & EPOLLIN) {
918 size_t numFrames = device->videoDevice->readAndQueueFrames();
919 if (numFrames == 0) {
920 ALOGE("Received epoll event for video device %s, but could not read frame",
921 device->videoDevice->getName().c_str());
922 }
923 } else if (eventItem.events & EPOLLHUP) {
924 // TODO(b/121395353) - consider adding EPOLLRDHUP
925 ALOGI("Removing video device %s due to epoll hang-up event.",
926 device->videoDevice->getName().c_str());
927 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
928 device->videoDevice = nullptr;
929 } else {
930 ALOGW("Received unexpected epoll event 0x%08x for device %s.",
931 eventItem.events, device->videoDevice->getName().c_str());
932 ALOG_ASSERT(!DEBUG);
933 }
934 continue;
935 }
936 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -0800937 if (eventItem.events & EPOLLIN) {
938 int32_t readSize = read(device->fd, readBuffer,
939 sizeof(struct input_event) * capacity);
940 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
941 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -0700942 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
943 " bufferSize: %zu capacity: %zu errno: %d)\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800944 device->fd, readSize, bufferSize, capacity, errno);
945 deviceChanged = true;
946 closeDeviceLocked(device);
947 } else if (readSize < 0) {
948 if (errno != EAGAIN && errno != EINTR) {
949 ALOGW("could not get event (errno=%d)", errno);
950 }
951 } else if ((readSize % sizeof(struct input_event)) != 0) {
952 ALOGE("could not get event (wrong size: %d)", readSize);
953 } else {
954 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
955
956 size_t count = size_t(readSize) / sizeof(struct input_event);
957 for (size_t i = 0; i < count; i++) {
958 struct input_event& iev = readBuffer[i];
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800959 event->when = processEventTimestamp(iev);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800960 event->deviceId = deviceId;
961 event->type = iev.type;
962 event->code = iev.code;
963 event->value = iev.value;
964 event += 1;
965 capacity -= 1;
966 }
967 if (capacity == 0) {
968 // The result buffer is full. Reset the pending event index
969 // so we will try to read the device again on the next iteration.
970 mPendingEventIndex -= 1;
971 break;
972 }
973 }
974 } else if (eventItem.events & EPOLLHUP) {
975 ALOGI("Removing device %s due to epoll hang-up event.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100976 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800977 deviceChanged = true;
978 closeDeviceLocked(device);
979 } else {
980 ALOGW("Received unexpected epoll event 0x%08x for device %s.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100981 eventItem.events, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800982 }
983 }
984
985 // readNotify() will modify the list of devices so this must be done after
986 // processing all other events to ensure that we read all remaining events
987 // before closing the devices.
988 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
989 mPendingINotify = false;
990 readNotifyLocked();
991 deviceChanged = true;
992 }
993
994 // Report added or removed devices immediately.
995 if (deviceChanged) {
996 continue;
997 }
998
999 // Return now if we have collected any events or if we were explicitly awoken.
1000 if (event != buffer || awoken) {
1001 break;
1002 }
1003
1004 // Poll for events. Mind the wake lock dance!
1005 // We hold a wake lock at all times except during epoll_wait(). This works due to some
1006 // subtle choreography. When a device driver has pending (unread) events, it acquires
1007 // a kernel wake lock. However, once the last pending event has been read, the device
1008 // driver will release the kernel wake lock. To prevent the system from going to sleep
1009 // when this happens, the EventHub holds onto its own user wake lock while the client
1010 // is processing events. Thus the system can only sleep if there are no events
1011 // pending or currently being processed.
1012 //
1013 // The timeout is advisory only. If the device is asleep, it will not wake just to
1014 // service the timeout.
1015 mPendingEventIndex = 0;
1016
1017 mLock.unlock(); // release lock before poll, must be before release_wake_lock
1018 release_wake_lock(WAKE_LOCK_ID);
1019
1020 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1021
1022 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
1023 mLock.lock(); // reacquire lock after poll, must be after acquire_wake_lock
1024
1025 if (pollResult == 0) {
1026 // Timed out.
1027 mPendingEventCount = 0;
1028 break;
1029 }
1030
1031 if (pollResult < 0) {
1032 // An error occurred.
1033 mPendingEventCount = 0;
1034
1035 // Sleep after errors to avoid locking up the system.
1036 // Hopefully the error is transient.
1037 if (errno != EINTR) {
1038 ALOGW("poll failed (errno=%d)\n", errno);
1039 usleep(100000);
1040 }
1041 } else {
1042 // Some events occurred.
1043 mPendingEventCount = size_t(pollResult);
1044 }
1045 }
1046
1047 // All done, return the number of events we read.
1048 return event - buffer;
1049}
1050
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001051std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
1052 AutoMutex _l(mLock);
1053
1054 Device* device = getDeviceLocked(deviceId);
1055 if (!device || !device->videoDevice) {
1056 return {};
1057 }
1058 return device->videoDevice->consumeFrames();
1059}
1060
Michael Wrightd02c5b62014-02-10 15:10:22 -08001061void EventHub::wake() {
1062 ALOGV("wake() called");
1063
1064 ssize_t nWrite;
1065 do {
1066 nWrite = write(mWakeWritePipeFd, "W", 1);
1067 } while (nWrite == -1 && errno == EINTR);
1068
1069 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001070 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001071 }
1072}
1073
1074void EventHub::scanDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001075 status_t result = scanDirLocked(DEVICE_PATH);
1076 if(result < 0) {
1077 ALOGE("scan dir failed for %s", DEVICE_PATH);
1078 }
Philip Quinn39b81682019-01-09 22:20:39 -08001079 if (isV4lScanningEnabled()) {
1080 result = scanVideoDirLocked(VIDEO_DEVICE_PATH);
1081 if (result != OK) {
1082 ALOGE("scan video dir failed for %s", VIDEO_DEVICE_PATH);
1083 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001084 }
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001085 if (mDevices.indexOfKey(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) < 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001086 createVirtualKeyboardLocked();
1087 }
1088}
1089
1090// ----------------------------------------------------------------------------
1091
1092static bool containsNonZeroByte(const uint8_t* array, uint32_t startIndex, uint32_t endIndex) {
1093 const uint8_t* end = array + endIndex;
1094 array += startIndex;
1095 while (array != end) {
1096 if (*(array++) != 0) {
1097 return true;
1098 }
1099 }
1100 return false;
1101}
1102
1103static const int32_t GAMEPAD_KEYCODES[] = {
1104 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C,
1105 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z,
1106 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1,
1107 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2,
1108 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR,
1109 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001110};
1111
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001112status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001113 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001114 struct epoll_event eventItem = {};
1115 eventItem.events = EPOLLIN | EPOLLWAKEUP;
1116 eventItem.data.fd = fd;
1117 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1118 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001119 return -errno;
1120 }
1121 return OK;
1122}
1123
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001124status_t EventHub::unregisterFdFromEpoll(int fd) {
1125 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
1126 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
1127 return -errno;
1128 }
1129 return OK;
1130}
1131
1132status_t EventHub::registerDeviceForEpollLocked(Device* device) {
1133 if (device == nullptr) {
1134 if (DEBUG) {
1135 LOG_ALWAYS_FATAL("Cannot call registerDeviceForEpollLocked with null Device");
1136 }
1137 return BAD_VALUE;
1138 }
1139 status_t result = registerFdForEpoll(device->fd);
1140 if (result != OK) {
1141 ALOGE("Could not add input device fd to epoll for device %" PRId32, device->id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001142 return result;
1143 }
1144 if (device->videoDevice) {
1145 registerVideoDeviceForEpollLocked(*device->videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001146 }
1147 return result;
1148}
1149
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001150void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
1151 status_t result = registerFdForEpoll(videoDevice.getFd());
1152 if (result != OK) {
1153 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
1154 }
1155}
1156
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001157status_t EventHub::unregisterDeviceFromEpollLocked(Device* device) {
1158 if (device->hasValidFd()) {
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001159 status_t result = unregisterFdFromEpoll(device->fd);
1160 if (result != OK) {
1161 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device->id);
1162 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001163 }
1164 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001165 if (device->videoDevice) {
1166 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1167 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001168 return OK;
1169}
1170
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001171void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
1172 if (videoDevice.hasValidFd()) {
1173 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
1174 if (result != OK) {
1175 ALOGW("Could not remove video device fd from epoll for device: %s",
1176 videoDevice.getName().c_str());
1177 }
1178 }
1179}
1180
1181status_t EventHub::openDeviceLocked(const char* devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001182 char buffer[80];
1183
1184 ALOGV("Opening device: %s", devicePath);
1185
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001186 int fd = open(devicePath, O_RDWR | O_CLOEXEC | O_NONBLOCK);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001187 if(fd < 0) {
1188 ALOGE("could not open %s, %s\n", devicePath, strerror(errno));
1189 return -1;
1190 }
1191
1192 InputDeviceIdentifier identifier;
1193
1194 // Get device name.
1195 if(ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001196 ALOGE("Could not get device name for %s: %s", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001197 } else {
1198 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001199 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001200 }
1201
1202 // Check to see if the device is on our excluded list
1203 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001204 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001205 if (identifier.name == item) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001206 ALOGI("ignoring event id %s driver %s\n", devicePath, item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001207 close(fd);
1208 return -1;
1209 }
1210 }
1211
1212 // Get device driver version.
1213 int driverVersion;
1214 if(ioctl(fd, EVIOCGVERSION, &driverVersion)) {
1215 ALOGE("could not get driver version for %s, %s\n", devicePath, strerror(errno));
1216 close(fd);
1217 return -1;
1218 }
1219
1220 // Get device identifier.
1221 struct input_id inputId;
1222 if(ioctl(fd, EVIOCGID, &inputId)) {
1223 ALOGE("could not get device input id for %s, %s\n", devicePath, strerror(errno));
1224 close(fd);
1225 return -1;
1226 }
1227 identifier.bus = inputId.bustype;
1228 identifier.product = inputId.product;
1229 identifier.vendor = inputId.vendor;
1230 identifier.version = inputId.version;
1231
1232 // Get device physical location.
1233 if(ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
1234 //fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
1235 } else {
1236 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001237 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001238 }
1239
1240 // Get device unique id.
1241 if(ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
1242 //fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
1243 } else {
1244 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001245 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001246 }
1247
1248 // Fill in the descriptor.
1249 assignDescriptorLocked(identifier);
1250
Michael Wrightd02c5b62014-02-10 15:10:22 -08001251 // Allocate device. (The device object takes ownership of the fd at this point.)
1252 int32_t deviceId = mNextDeviceId++;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001253 Device* device = new Device(fd, deviceId, devicePath, identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001254
1255 ALOGV("add device %d: %s\n", deviceId, devicePath);
1256 ALOGV(" bus: %04x\n"
1257 " vendor %04x\n"
1258 " product %04x\n"
1259 " version %04x\n",
1260 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001261 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
1262 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
1263 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
1264 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001265 ALOGV(" driver: v%d.%d.%d\n",
1266 driverVersion >> 16, (driverVersion >> 8) & 0xff, driverVersion & 0xff);
1267
1268 // Load the configuration file for the device.
1269 loadConfigurationLocked(device);
1270
1271 // Figure out the kinds of events the device reports.
1272 ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(device->keyBitmask)), device->keyBitmask);
1273 ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(device->absBitmask)), device->absBitmask);
1274 ioctl(fd, EVIOCGBIT(EV_REL, sizeof(device->relBitmask)), device->relBitmask);
1275 ioctl(fd, EVIOCGBIT(EV_SW, sizeof(device->swBitmask)), device->swBitmask);
1276 ioctl(fd, EVIOCGBIT(EV_LED, sizeof(device->ledBitmask)), device->ledBitmask);
1277 ioctl(fd, EVIOCGBIT(EV_FF, sizeof(device->ffBitmask)), device->ffBitmask);
1278 ioctl(fd, EVIOCGPROP(sizeof(device->propBitmask)), device->propBitmask);
1279
1280 // See if this is a keyboard. Ignore everything in the button range except for
1281 // joystick and gamepad buttons which are handled like keyboards for the most part.
1282 bool haveKeyboardKeys = containsNonZeroByte(device->keyBitmask, 0, sizeof_bit_array(BTN_MISC))
1283 || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(KEY_OK),
1284 sizeof_bit_array(KEY_MAX + 1));
1285 bool haveGamepadButtons = containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_MISC),
1286 sizeof_bit_array(BTN_MOUSE))
1287 || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_JOYSTICK),
1288 sizeof_bit_array(BTN_DIGI));
1289 if (haveKeyboardKeys || haveGamepadButtons) {
1290 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1291 }
1292
1293 // See if this is a cursor device such as a trackball or mouse.
1294 if (test_bit(BTN_MOUSE, device->keyBitmask)
1295 && test_bit(REL_X, device->relBitmask)
1296 && test_bit(REL_Y, device->relBitmask)) {
1297 device->classes |= INPUT_DEVICE_CLASS_CURSOR;
1298 }
1299
Prashant Malani1941ff52015-08-11 18:29:28 -07001300 // See if this is a rotary encoder type device.
1301 String8 deviceType = String8();
1302 if (device->configuration &&
1303 device->configuration->tryGetProperty(String8("device.type"), deviceType)) {
1304 if (!deviceType.compare(String8("rotaryEncoder"))) {
1305 device->classes |= INPUT_DEVICE_CLASS_ROTARY_ENCODER;
1306 }
1307 }
1308
Michael Wrightd02c5b62014-02-10 15:10:22 -08001309 // See if this is a touch pad.
1310 // Is this a new modern multi-touch driver?
1311 if (test_bit(ABS_MT_POSITION_X, device->absBitmask)
1312 && test_bit(ABS_MT_POSITION_Y, device->absBitmask)) {
1313 // Some joysticks such as the PS3 controller report axes that conflict
1314 // with the ABS_MT range. Try to confirm that the device really is
1315 // a touch screen.
1316 if (test_bit(BTN_TOUCH, device->keyBitmask) || !haveGamepadButtons) {
1317 device->classes |= INPUT_DEVICE_CLASS_TOUCH | INPUT_DEVICE_CLASS_TOUCH_MT;
1318 }
1319 // Is this an old style single-touch driver?
1320 } else if (test_bit(BTN_TOUCH, device->keyBitmask)
1321 && test_bit(ABS_X, device->absBitmask)
1322 && test_bit(ABS_Y, device->absBitmask)) {
1323 device->classes |= INPUT_DEVICE_CLASS_TOUCH;
Michael Wright842500e2015-03-13 17:32:02 -07001324 // Is this a BT stylus?
1325 } else if ((test_bit(ABS_PRESSURE, device->absBitmask) ||
1326 test_bit(BTN_TOUCH, device->keyBitmask))
1327 && !test_bit(ABS_X, device->absBitmask)
1328 && !test_bit(ABS_Y, device->absBitmask)) {
1329 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
1330 // Keyboard will try to claim some of the buttons but we really want to reserve those so we
1331 // can fuse it with the touch screen data, so just take them back. Note this means an
1332 // external stylus cannot also be a keyboard device.
1333 device->classes &= ~INPUT_DEVICE_CLASS_KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001334 }
1335
1336 // See if this device is a joystick.
1337 // Assumes that joysticks always have gamepad buttons in order to distinguish them
1338 // from other devices such as accelerometers that also have absolute axes.
1339 if (haveGamepadButtons) {
1340 uint32_t assumedClasses = device->classes | INPUT_DEVICE_CLASS_JOYSTICK;
1341 for (int i = 0; i <= ABS_MAX; i++) {
1342 if (test_bit(i, device->absBitmask)
1343 && (getAbsAxisUsage(i, assumedClasses) & INPUT_DEVICE_CLASS_JOYSTICK)) {
1344 device->classes = assumedClasses;
1345 break;
1346 }
1347 }
1348 }
1349
1350 // Check whether this device has switches.
1351 for (int i = 0; i <= SW_MAX; i++) {
1352 if (test_bit(i, device->swBitmask)) {
1353 device->classes |= INPUT_DEVICE_CLASS_SWITCH;
1354 break;
1355 }
1356 }
1357
1358 // Check whether this device supports the vibrator.
1359 if (test_bit(FF_RUMBLE, device->ffBitmask)) {
1360 device->classes |= INPUT_DEVICE_CLASS_VIBRATOR;
1361 }
1362
1363 // Configure virtual keys.
1364 if ((device->classes & INPUT_DEVICE_CLASS_TOUCH)) {
1365 // Load the virtual keys for the touch screen, if any.
1366 // We do this now so that we can make sure to load the keymap if necessary.
1367 status_t status = loadVirtualKeyMapLocked(device);
1368 if (!status) {
1369 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1370 }
1371 }
1372
1373 // Load the key map.
1374 // We need to do this for joysticks too because the key layout may specify axes.
1375 status_t keyMapStatus = NAME_NOT_FOUND;
1376 if (device->classes & (INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_JOYSTICK)) {
1377 // Load the keymap for the device.
1378 keyMapStatus = loadKeyMapLocked(device);
1379 }
1380
1381 // Configure the keyboard, gamepad or virtual keyboard.
1382 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1383 // Register the keyboard as a built-in keyboard if it is eligible.
1384 if (!keyMapStatus
1385 && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD
1386 && isEligibleBuiltInKeyboard(device->identifier,
1387 device->configuration, &device->keyMap)) {
1388 mBuiltInKeyboardId = device->id;
1389 }
1390
1391 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
1392 if (hasKeycodeLocked(device, AKEYCODE_Q)) {
1393 device->classes |= INPUT_DEVICE_CLASS_ALPHAKEY;
1394 }
1395
1396 // See if this device has a DPAD.
1397 if (hasKeycodeLocked(device, AKEYCODE_DPAD_UP) &&
1398 hasKeycodeLocked(device, AKEYCODE_DPAD_DOWN) &&
1399 hasKeycodeLocked(device, AKEYCODE_DPAD_LEFT) &&
1400 hasKeycodeLocked(device, AKEYCODE_DPAD_RIGHT) &&
1401 hasKeycodeLocked(device, AKEYCODE_DPAD_CENTER)) {
1402 device->classes |= INPUT_DEVICE_CLASS_DPAD;
1403 }
1404
1405 // See if this device has a gamepad.
1406 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES)/sizeof(GAMEPAD_KEYCODES[0]); i++) {
1407 if (hasKeycodeLocked(device, GAMEPAD_KEYCODES[i])) {
1408 device->classes |= INPUT_DEVICE_CLASS_GAMEPAD;
1409 break;
1410 }
1411 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001412 }
1413
1414 // If the device isn't recognized as something we handle, don't monitor it.
1415 if (device->classes == 0) {
1416 ALOGV("Dropping device: id=%d, path='%s', name='%s'",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001417 deviceId, devicePath, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001418 delete device;
1419 return -1;
1420 }
1421
Tim Kilbourn063ff532015-04-08 10:26:18 -07001422 // Determine whether the device has a mic.
1423 if (deviceHasMicLocked(device)) {
1424 device->classes |= INPUT_DEVICE_CLASS_MIC;
1425 }
1426
Michael Wrightd02c5b62014-02-10 15:10:22 -08001427 // Determine whether the device is external or internal.
1428 if (isExternalDeviceLocked(device)) {
1429 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL;
1430 }
1431
Michael Wright42f2c6a2014-03-12 10:33:03 -07001432 if (device->classes & (INPUT_DEVICE_CLASS_JOYSTICK | INPUT_DEVICE_CLASS_DPAD)
1433 && device->classes & INPUT_DEVICE_CLASS_GAMEPAD) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001434 device->controllerNumber = getNextControllerNumberLocked(device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001435 setLedForControllerLocked(device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001436 }
1437
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001438 // Find a matching video device by comparing device names
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001439 // This should be done before registerDeviceForEpollLocked, so that both fds are added to epoll
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001440 for (std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
1441 if (device->identifier.name == videoDevice->getName()) {
1442 device->videoDevice = std::move(videoDevice);
1443 break;
1444 }
1445 }
1446 mUnattachedVideoDevices.erase(std::remove_if(mUnattachedVideoDevices.begin(),
1447 mUnattachedVideoDevices.end(),
1448 [](const std::unique_ptr<TouchVideoDevice>& videoDevice){
1449 return videoDevice == nullptr; }), mUnattachedVideoDevices.end());
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001450
1451 if (registerDeviceForEpollLocked(device) != OK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001452 delete device;
1453 return -1;
1454 }
1455
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001456 configureFd(device);
1457
1458 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=0x%x, "
1459 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001460 deviceId, fd, devicePath, device->identifier.name.c_str(),
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001461 device->classes,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001462 device->configurationFile.c_str(),
1463 device->keyMap.keyLayoutFile.c_str(),
1464 device->keyMap.keyCharacterMapFile.c_str(),
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001465 toString(mBuiltInKeyboardId == deviceId));
1466
1467 addDeviceLocked(device);
1468 return OK;
1469}
1470
1471void EventHub::configureFd(Device* device) {
1472 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
1473 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1474 // Disable kernel key repeat since we handle it ourselves
1475 unsigned int repeatRate[] = {0, 0};
1476 if (ioctl(device->fd, EVIOCSREP, repeatRate)) {
1477 ALOGW("Unable to disable kernel key repeat for %s: %s",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001478 device->path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001479 }
1480 }
1481
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001482 std::string wakeMechanism = "EPOLLWAKEUP";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001483 if (!mUsingEpollWakeup) {
1484#ifndef EVIOCSSUSPENDBLOCK
1485 // uapi headers don't include EVIOCSSUSPENDBLOCK, and future kernels
1486 // will use an epoll flag instead, so as long as we want to support
1487 // this feature, we need to be prepared to define the ioctl ourselves.
1488#define EVIOCSSUSPENDBLOCK _IOW('E', 0x91, int)
1489#endif
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001490 if (ioctl(device->fd, EVIOCSSUSPENDBLOCK, 1)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001491 wakeMechanism = "<none>";
1492 } else {
1493 wakeMechanism = "EVIOCSSUSPENDBLOCK";
1494 }
1495 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001496 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
1497 // associated with input events. This is important because the input system
1498 // uses the timestamps extensively and assumes they were recorded using the monotonic
1499 // clock.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001500 int clockId = CLOCK_MONOTONIC;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001501 bool usingClockIoctl = !ioctl(device->fd, EVIOCSCLOCKID, &clockId);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001502 ALOGI("wakeMechanism=%s, usingClockIoctl=%s", wakeMechanism.c_str(),
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001503 toString(usingClockIoctl));
1504}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001505
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001506void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
1507 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
1508 if (!videoDevice) {
1509 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
1510 return;
1511 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001512 // Transfer ownership of this video device to a matching input device
1513 for (size_t i = 0; i < mDevices.size(); i++) {
1514 Device* device = mDevices.valueAt(i);
1515 if (videoDevice->getName() == device->identifier.name) {
1516 device->videoDevice = std::move(videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001517 if (device->enabled) {
1518 registerVideoDeviceForEpollLocked(*device->videoDevice);
1519 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001520 return;
1521 }
1522 }
1523
1524 // Couldn't find a matching input device, so just add it to a temporary holding queue.
1525 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001526 ALOGI("Adding video device %s to list of unattached video devices",
1527 videoDevice->getName().c_str());
1528 mUnattachedVideoDevices.push_back(std::move(videoDevice));
1529}
1530
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001531bool EventHub::isDeviceEnabled(int32_t deviceId) {
1532 AutoMutex _l(mLock);
1533 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001534 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001535 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1536 return false;
1537 }
1538 return device->enabled;
1539}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001540
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001541status_t EventHub::enableDevice(int32_t deviceId) {
1542 AutoMutex _l(mLock);
1543 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001544 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001545 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1546 return BAD_VALUE;
1547 }
1548 if (device->enabled) {
1549 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
1550 return OK;
1551 }
1552 status_t result = device->enable();
1553 if (result != OK) {
1554 ALOGE("Failed to enable device %" PRId32, deviceId);
1555 return result;
1556 }
1557
1558 configureFd(device);
1559
1560 return registerDeviceForEpollLocked(device);
1561}
1562
1563status_t EventHub::disableDevice(int32_t deviceId) {
1564 AutoMutex _l(mLock);
1565 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001566 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001567 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1568 return BAD_VALUE;
1569 }
1570 if (!device->enabled) {
1571 ALOGW("Duplicate call to %s, input device already disabled", __func__);
1572 return OK;
1573 }
1574 unregisterDeviceFromEpollLocked(device);
1575 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001576}
1577
1578void EventHub::createVirtualKeyboardLocked() {
1579 InputDeviceIdentifier identifier;
1580 identifier.name = "Virtual";
1581 identifier.uniqueId = "<virtual>";
1582 assignDescriptorLocked(identifier);
1583
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001584 Device* device = new Device(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
1585 identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001586 device->classes = INPUT_DEVICE_CLASS_KEYBOARD
1587 | INPUT_DEVICE_CLASS_ALPHAKEY
1588 | INPUT_DEVICE_CLASS_DPAD
1589 | INPUT_DEVICE_CLASS_VIRTUAL;
1590 loadKeyMapLocked(device);
1591 addDeviceLocked(device);
1592}
1593
1594void EventHub::addDeviceLocked(Device* device) {
1595 mDevices.add(device->id, device);
1596 device->next = mOpeningDevices;
1597 mOpeningDevices = device;
1598}
1599
1600void EventHub::loadConfigurationLocked(Device* device) {
1601 device->configurationFile = getInputDeviceConfigurationFilePathByDeviceIdentifier(
1602 device->identifier, INPUT_DEVICE_CONFIGURATION_FILE_TYPE_CONFIGURATION);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001603 if (device->configurationFile.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001604 ALOGD("No input device configuration file found for device '%s'.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001605 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001606 } else {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001607 status_t status = PropertyMap::load(String8(device->configurationFile.c_str()),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001608 &device->configuration);
1609 if (status) {
1610 ALOGE("Error loading input device configuration file for device '%s'. "
1611 "Using default configuration.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001612 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001613 }
1614 }
1615}
1616
1617status_t EventHub::loadVirtualKeyMapLocked(Device* device) {
1618 // The virtual key map is supplied by the kernel as a system board property file.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001619 std::string path;
1620 path += "/sys/board_properties/virtualkeys.";
1621 path += device->identifier.name;
1622 if (access(path.c_str(), R_OK)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001623 return NAME_NOT_FOUND;
1624 }
1625 return VirtualKeyMap::load(path, &device->virtualKeyMap);
1626}
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