blob: a5e5415dd7b73867cfe2c6eb50e6b1962ee9e6ef [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2005 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070017#include <assert.h>
18#include <dirent.h>
19#include <errno.h>
20#include <fcntl.h>
21#include <inttypes.h>
22#include <memory.h>
23#include <stdint.h>
24#include <stdio.h>
25#include <stdlib.h>
26#include <string.h>
27#include <sys/epoll.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070028#include <sys/inotify.h>
29#include <sys/ioctl.h>
Prabir Pradhan2b281812019-08-29 14:12:42 -070030#include <sys/limits.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>
Prabir Pradhan2b281812019-08-29 14:12:42 -070045#include <utils/Errors.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080046#include <utils/Log.h>
47#include <utils/Timers.h>
48#include <utils/threads.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080049
Michael Wrightd02c5b62014-02-10 15:10:22 -080050#include <input/KeyCharacterMap.h>
Prabir Pradhan2b281812019-08-29 14:12:42 -070051#include <input/KeyLayoutMap.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080052#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 */
Prabir Pradhan2b281812019-08-29 14:12:42 -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 */
Prabir Pradhan2b281812019-08-29 14:12:42 -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
Prabir Pradhan2b281812019-08-29 14:12:42 -070074static 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
Prabir Pradhan2b281812019-08-29 14:12:42 -070077static 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
Siarhei Vishniakou29f88492019-04-05 14:11:43 -0700118 * them.
119 *
120 * Setting this to "false" would prevent any video devices from being discovered and
121 * associated with input devices.
122 *
123 * This property can be used as follows:
124 * 1. To turn off features that are dependent on video device presence.
125 * 2. During testing and development, to allow other clients to read video devices
126 * directly from /dev.
Philip Quinn39b81682019-01-09 22:20:39 -0800127 */
128static bool isV4lScanningEnabled() {
Prabir Pradhan2b281812019-08-29 14:12:42 -0700129 return property_get_bool("ro.input.video_enabled", true /* default_value */);
Philip Quinn39b81682019-01-09 22:20:39 -0800130}
131
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800132static nsecs_t processEventTimestamp(const struct input_event& event) {
133 // Use the time specified in the event instead of the current time
134 // so that downstream code can get more accurate estimates of
135 // event dispatch latency from the time the event is enqueued onto
136 // the evdev client buffer.
137 //
138 // The event's timestamp fortuitously uses the same monotonic clock
139 // time base as the rest of Android. The kernel event device driver
140 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
141 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
142 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
143 // system call that also queries ktime_get_ts().
144
145 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.time.tv_sec) +
146 microseconds_to_nanoseconds(event.time.tv_usec);
147 return inputEventTime;
148}
149
Michael Wrightd02c5b62014-02-10 15:10:22 -0800150// --- Global Functions ---
151
152uint32_t getAbsAxisUsage(int32_t axis, uint32_t deviceClasses) {
153 // Touch devices get dibs on touch-related axes.
154 if (deviceClasses & INPUT_DEVICE_CLASS_TOUCH) {
155 switch (axis) {
Prabir Pradhan2b281812019-08-29 14:12:42 -0700156 case ABS_X:
157 case ABS_Y:
158 case ABS_PRESSURE:
159 case ABS_TOOL_WIDTH:
160 case ABS_DISTANCE:
161 case ABS_TILT_X:
162 case ABS_TILT_Y:
163 case ABS_MT_SLOT:
164 case ABS_MT_TOUCH_MAJOR:
165 case ABS_MT_TOUCH_MINOR:
166 case ABS_MT_WIDTH_MAJOR:
167 case ABS_MT_WIDTH_MINOR:
168 case ABS_MT_ORIENTATION:
169 case ABS_MT_POSITION_X:
170 case ABS_MT_POSITION_Y:
171 case ABS_MT_TOOL_TYPE:
172 case ABS_MT_BLOB_ID:
173 case ABS_MT_TRACKING_ID:
174 case ABS_MT_PRESSURE:
175 case ABS_MT_DISTANCE:
176 return INPUT_DEVICE_CLASS_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800177 }
178 }
179
Michael Wright842500e2015-03-13 17:32:02 -0700180 // External stylus gets the pressure axis
181 if (deviceClasses & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
182 if (axis == ABS_PRESSURE) {
183 return INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
184 }
185 }
186
Michael Wrightd02c5b62014-02-10 15:10:22 -0800187 // Joystick devices get the rest.
188 return deviceClasses & INPUT_DEVICE_CLASS_JOYSTICK;
189}
190
191// --- EventHub::Device ---
192
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100193EventHub::Device::Device(int fd, int32_t id, const std::string& path,
Prabir Pradhan2b281812019-08-29 14:12:42 -0700194 const InputDeviceIdentifier& identifier)
195 : next(nullptr),
196 fd(fd),
197 id(id),
198 path(path),
199 identifier(identifier),
200 classes(0),
201 configuration(nullptr),
202 virtualKeyMap(nullptr),
203 ffEffectPlaying(false),
204 ffEffectId(-1),
205 controllerNumber(0),
206 enabled(true),
207 isVirtual(fd < 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800208 memset(keyBitmask, 0, sizeof(keyBitmask));
209 memset(absBitmask, 0, sizeof(absBitmask));
210 memset(relBitmask, 0, sizeof(relBitmask));
211 memset(swBitmask, 0, sizeof(swBitmask));
212 memset(ledBitmask, 0, sizeof(ledBitmask));
213 memset(ffBitmask, 0, sizeof(ffBitmask));
214 memset(propBitmask, 0, sizeof(propBitmask));
215}
216
217EventHub::Device::~Device() {
218 close();
219 delete configuration;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800220}
221
222void EventHub::Device::close() {
223 if (fd >= 0) {
224 ::close(fd);
225 fd = -1;
226 }
227}
228
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700229status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100230 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhan2b281812019-08-29 14:12:42 -0700231 if (fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100232 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700233 return -errno;
234 }
235 enabled = true;
236 return OK;
237}
238
239status_t EventHub::Device::disable() {
240 close();
241 enabled = false;
242 return OK;
243}
244
245bool EventHub::Device::hasValidFd() {
246 return !isVirtual && enabled;
247}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800248
249// --- EventHub ---
250
Michael Wrightd02c5b62014-02-10 15:10:22 -0800251const int EventHub::EPOLL_MAX_EVENTS;
252
Prabir Pradhan2b281812019-08-29 14:12:42 -0700253EventHub::EventHub(void)
254 : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
255 mNextDeviceId(1),
256 mControllerNumbers(),
257 mOpeningDevices(nullptr),
258 mClosingDevices(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800259 mNeedToSendFinishedDeviceScan(false),
Prabir Pradhan2b281812019-08-29 14:12:42 -0700260 mNeedToReopenDevices(false),
261 mNeedToScanDevices(true),
262 mPendingEventCount(0),
263 mPendingEventIndex(0),
264 mPendingINotify(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800265 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
266
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800267 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800268 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800269
270 mINotifyFd = inotify_init();
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800271 mInputWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
Prabir Pradhan2b281812019-08-29 14:12:42 -0700272 LOG_ALWAYS_FATAL_IF(mInputWd < 0, "Could not register INotify for %s: %s", DEVICE_PATH,
273 strerror(errno));
Philip Quinn39b81682019-01-09 22:20:39 -0800274 if (isV4lScanningEnabled()) {
275 mVideoWd = inotify_add_watch(mINotifyFd, VIDEO_DEVICE_PATH, IN_DELETE | IN_CREATE);
276 LOG_ALWAYS_FATAL_IF(mVideoWd < 0, "Could not register INotify for %s: %s",
Prabir Pradhan2b281812019-08-29 14:12:42 -0700277 VIDEO_DEVICE_PATH, strerror(errno));
Philip Quinn39b81682019-01-09 22:20:39 -0800278 } else {
279 mVideoWd = -1;
280 ALOGI("Video device scanning disabled");
281 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800282
283 struct epoll_event eventItem;
284 memset(&eventItem, 0, sizeof(eventItem));
285 eventItem.events = EPOLLIN;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700286 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800287 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800288 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
289
290 int wakeFds[2];
291 result = pipe(wakeFds);
292 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
293
294 mWakeReadPipeFd = wakeFds[0];
295 mWakeWritePipeFd = wakeFds[1];
296
297 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
298 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
Prabir Pradhan2b281812019-08-29 14:12:42 -0700299 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800300
301 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
302 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
Prabir Pradhan2b281812019-08-29 14:12:42 -0700303 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800304
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700305 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800306 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
307 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
Prabir Pradhan2b281812019-08-29 14:12:42 -0700308 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800309
310 int major, minor;
311 getLinuxRelease(&major, &minor);
312 // EPOLLWAKEUP was introduced in kernel 3.5
313 mUsingEpollWakeup = major > 3 || (major == 3 && minor >= 5);
314}
315
316EventHub::~EventHub(void) {
317 closeAllDevicesLocked();
318
319 while (mClosingDevices) {
320 Device* device = mClosingDevices;
321 mClosingDevices = device->next;
322 delete device;
323 }
324
325 ::close(mEpollFd);
326 ::close(mINotifyFd);
327 ::close(mWakeReadPipeFd);
328 ::close(mWakeWritePipeFd);
329
330 release_wake_lock(WAKE_LOCK_ID);
331}
332
333InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
334 AutoMutex _l(mLock);
335 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700336 if (device == nullptr) return InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800337 return device->identifier;
338}
339
340uint32_t EventHub::getDeviceClasses(int32_t deviceId) const {
341 AutoMutex _l(mLock);
342 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700343 if (device == nullptr) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800344 return device->classes;
345}
346
347int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
348 AutoMutex _l(mLock);
349 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700350 if (device == nullptr) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800351 return device->controllerNumber;
352}
353
354void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
355 AutoMutex _l(mLock);
356 Device* device = getDeviceLocked(deviceId);
357 if (device && device->configuration) {
358 *outConfiguration = *device->configuration;
359 } else {
360 outConfiguration->clear();
361 }
362}
363
364status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
Prabir Pradhan2b281812019-08-29 14:12:42 -0700365 RawAbsoluteAxisInfo* outAxisInfo) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800366 outAxisInfo->clear();
367
368 if (axis >= 0 && axis <= ABS_MAX) {
369 AutoMutex _l(mLock);
370
371 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700372 if (device && device->hasValidFd() && test_bit(axis, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800373 struct input_absinfo info;
Prabir Pradhan2b281812019-08-29 14:12:42 -0700374 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
375 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
376 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800377 return -errno;
378 }
379
380 if (info.minimum != info.maximum) {
381 outAxisInfo->valid = true;
382 outAxisInfo->minValue = info.minimum;
383 outAxisInfo->maxValue = info.maximum;
384 outAxisInfo->flat = info.flat;
385 outAxisInfo->fuzz = info.fuzz;
386 outAxisInfo->resolution = info.resolution;
387 }
388 return OK;
389 }
390 }
391 return -1;
392}
393
394bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
395 if (axis >= 0 && axis <= REL_MAX) {
396 AutoMutex _l(mLock);
397
398 Device* device = getDeviceLocked(deviceId);
399 if (device) {
400 return test_bit(axis, device->relBitmask);
401 }
402 }
403 return false;
404}
405
406bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
407 if (property >= 0 && property <= INPUT_PROP_MAX) {
408 AutoMutex _l(mLock);
409
410 Device* device = getDeviceLocked(deviceId);
411 if (device) {
412 return test_bit(property, device->propBitmask);
413 }
414 }
415 return false;
416}
417
418int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
419 if (scanCode >= 0 && scanCode <= KEY_MAX) {
420 AutoMutex _l(mLock);
421
422 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700423 if (device && device->hasValidFd() && test_bit(scanCode, device->keyBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800424 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
425 memset(keyState, 0, sizeof(keyState));
426 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
427 return test_bit(scanCode, keyState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
428 }
429 }
430 }
431 return AKEY_STATE_UNKNOWN;
432}
433
434int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
435 AutoMutex _l(mLock);
436
437 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700438 if (device && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800439 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800440 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode, &scanCodes);
441 if (scanCodes.size() != 0) {
442 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
443 memset(keyState, 0, sizeof(keyState));
444 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
445 for (size_t i = 0; i < scanCodes.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800446 int32_t sc = scanCodes[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -0800447 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, keyState)) {
448 return AKEY_STATE_DOWN;
449 }
450 }
451 return AKEY_STATE_UP;
452 }
453 }
454 }
455 return AKEY_STATE_UNKNOWN;
456}
457
458int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
459 if (sw >= 0 && sw <= SW_MAX) {
460 AutoMutex _l(mLock);
461
462 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700463 if (device && device->hasValidFd() && test_bit(sw, device->swBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800464 uint8_t swState[sizeof_bit_array(SW_MAX + 1)];
465 memset(swState, 0, sizeof(swState));
466 if (ioctl(device->fd, EVIOCGSW(sizeof(swState)), swState) >= 0) {
467 return test_bit(sw, swState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
468 }
469 }
470 }
471 return AKEY_STATE_UNKNOWN;
472}
473
474status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
475 *outValue = 0;
476
477 if (axis >= 0 && axis <= ABS_MAX) {
478 AutoMutex _l(mLock);
479
480 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700481 if (device && device->hasValidFd() && test_bit(axis, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800482 struct input_absinfo info;
Prabir Pradhan2b281812019-08-29 14:12:42 -0700483 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
484 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
485 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800486 return -errno;
487 }
488
489 *outValue = info.value;
490 return OK;
491 }
492 }
493 return -1;
494}
495
Prabir Pradhan2b281812019-08-29 14:12:42 -0700496bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes, const int32_t* keyCodes,
497 uint8_t* outFlags) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800498 AutoMutex _l(mLock);
499
500 Device* device = getDeviceLocked(deviceId);
501 if (device && device->keyMap.haveKeyLayout()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800502 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800503 for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) {
504 scanCodes.clear();
505
Prabir Pradhan2b281812019-08-29 14:12:42 -0700506 status_t err = device->keyMap.keyLayoutMap->findScanCodesForKey(keyCodes[codeIndex],
507 &scanCodes);
508 if (!err) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800509 // check the possible scan codes identified by the layout map against the
510 // map of codes actually emitted by the driver
511 for (size_t sc = 0; sc < scanCodes.size(); sc++) {
512 if (test_bit(scanCodes[sc], device->keyBitmask)) {
513 outFlags[codeIndex] = 1;
514 break;
515 }
516 }
517 }
518 }
519 return true;
520 }
521 return false;
522}
523
Prabir Pradhan2b281812019-08-29 14:12:42 -0700524status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
525 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800526 AutoMutex _l(mLock);
527 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700528 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800529
530 if (device) {
531 // Check the key character map first.
532 sp<KeyCharacterMap> kcm = device->getKeyCharacterMap();
Yi Kong9b14ac62018-07-17 13:48:38 -0700533 if (kcm != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800534 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
535 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700536 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800537 }
538 }
539
540 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700541 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800542 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700543 status = NO_ERROR;
544 }
545 }
546
547 if (status == NO_ERROR) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700548 if (kcm != nullptr) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700549 kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState);
550 } else {
551 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800552 }
553 }
554 }
555
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700556 if (status != NO_ERROR) {
557 *outKeycode = 0;
558 *outFlags = 0;
559 *outMetaState = metaState;
560 }
561
562 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800563}
564
565status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
566 AutoMutex _l(mLock);
567 Device* device = getDeviceLocked(deviceId);
568
569 if (device && device->keyMap.haveKeyLayout()) {
570 status_t err = device->keyMap.keyLayoutMap->mapAxis(scanCode, outAxisInfo);
571 if (err == NO_ERROR) {
572 return NO_ERROR;
573 }
574 }
575
576 return NAME_NOT_FOUND;
577}
578
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100579void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800580 AutoMutex _l(mLock);
581
582 mExcludedDevices = devices;
583}
584
585bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
586 AutoMutex _l(mLock);
587 Device* device = getDeviceLocked(deviceId);
588 if (device && scanCode >= 0 && scanCode <= KEY_MAX) {
589 if (test_bit(scanCode, device->keyBitmask)) {
590 return true;
591 }
592 }
593 return false;
594}
595
596bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
597 AutoMutex _l(mLock);
598 Device* device = getDeviceLocked(deviceId);
599 int32_t sc;
600 if (device && mapLed(device, led, &sc) == NO_ERROR) {
601 if (test_bit(sc, device->ledBitmask)) {
602 return true;
603 }
604 }
605 return false;
606}
607
608void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
609 AutoMutex _l(mLock);
610 Device* device = getDeviceLocked(deviceId);
611 setLedStateLocked(device, led, on);
612}
613
614void EventHub::setLedStateLocked(Device* device, int32_t led, bool on) {
615 int32_t sc;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700616 if (device && device->hasValidFd() && mapLed(device, led, &sc) != NAME_NOT_FOUND) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800617 struct input_event ev;
618 ev.time.tv_sec = 0;
619 ev.time.tv_usec = 0;
620 ev.type = EV_LED;
621 ev.code = sc;
622 ev.value = on ? 1 : 0;
623
624 ssize_t nWrite;
625 do {
626 nWrite = write(device->fd, &ev, sizeof(struct input_event));
627 } while (nWrite == -1 && errno == EINTR);
628 }
629}
630
631void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Prabir Pradhan2b281812019-08-29 14:12:42 -0700632 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800633 outVirtualKeys.clear();
634
635 AutoMutex _l(mLock);
636 Device* device = getDeviceLocked(deviceId);
637 if (device && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800638 const std::vector<VirtualKeyDefinition> virtualKeys =
639 device->virtualKeyMap->getVirtualKeys();
640 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800641 }
642}
643
644sp<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
645 AutoMutex _l(mLock);
646 Device* device = getDeviceLocked(deviceId);
647 if (device) {
648 return device->getKeyCharacterMap();
649 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700650 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800651}
652
Prabir Pradhan2b281812019-08-29 14:12:42 -0700653bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, const sp<KeyCharacterMap>& map) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800654 AutoMutex _l(mLock);
655 Device* device = getDeviceLocked(deviceId);
656 if (device) {
657 if (map != device->overlayKeyMap) {
658 device->overlayKeyMap = map;
Prabir Pradhan2b281812019-08-29 14:12:42 -0700659 device->combinedKeyMap = KeyCharacterMap::combine(device->keyMap.keyCharacterMap, map);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800660 return true;
661 }
662 }
663 return false;
664}
665
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100666static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
667 std::string rawDescriptor;
Prabir Pradhan2b281812019-08-29 14:12:42 -0700668 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800669 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100670 if (!identifier.uniqueId.empty()) {
671 rawDescriptor += "uniqueId:";
672 rawDescriptor += identifier.uniqueId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800673 } else if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100674 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800675 }
676
677 if (identifier.vendor == 0 && identifier.product == 0) {
678 // If we don't know the vendor and product id, then the device is probably
679 // built-in so we need to rely on other information to uniquely identify
680 // the input device. Usually we try to avoid relying on the device name or
681 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100682 if (!identifier.name.empty()) {
683 rawDescriptor += "name:";
684 rawDescriptor += identifier.name;
685 } else if (!identifier.location.empty()) {
686 rawDescriptor += "location:";
687 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800688 }
689 }
690 identifier.descriptor = sha1(rawDescriptor);
691 return rawDescriptor;
692}
693
694void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
695 // Compute a device descriptor that uniquely identifies the device.
696 // The descriptor is assumed to be a stable identifier. Its value should not
697 // change between reboots, reconnections, firmware updates or new releases
698 // of Android. In practice we sometimes get devices that cannot be uniquely
699 // identified. In this case we enforce uniqueness between connected devices.
700 // Ideally, we also want the descriptor to be short and relatively opaque.
701
702 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100703 std::string rawDescriptor = generateDescriptor(identifier);
704 if (identifier.uniqueId.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800705 // If it didn't have a unique id check for conflicts and enforce
706 // uniqueness if necessary.
Prabir Pradhan2b281812019-08-29 14:12:42 -0700707 while (getDeviceByDescriptorLocked(identifier.descriptor) != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800708 identifier.nonce++;
709 rawDescriptor = generateDescriptor(identifier);
710 }
711 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100712 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
Prabir Pradhan2b281812019-08-29 14:12:42 -0700713 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800714}
715
716void EventHub::vibrate(int32_t deviceId, nsecs_t duration) {
717 AutoMutex _l(mLock);
718 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700719 if (device && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800720 ff_effect effect;
721 memset(&effect, 0, sizeof(effect));
722 effect.type = FF_RUMBLE;
723 effect.id = device->ffEffectId;
724 effect.u.rumble.strong_magnitude = 0xc000;
725 effect.u.rumble.weak_magnitude = 0xc000;
726 effect.replay.length = (duration + 999999LL) / 1000000LL;
727 effect.replay.delay = 0;
728 if (ioctl(device->fd, EVIOCSFF, &effect)) {
729 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhan2b281812019-08-29 14:12:42 -0700730 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800731 return;
732 }
733 device->ffEffectId = effect.id;
734
735 struct input_event ev;
736 ev.time.tv_sec = 0;
737 ev.time.tv_usec = 0;
738 ev.type = EV_FF;
739 ev.code = device->ffEffectId;
740 ev.value = 1;
741 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
742 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Prabir Pradhan2b281812019-08-29 14:12:42 -0700743 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800744 return;
745 }
746 device->ffEffectPlaying = true;
747 }
748}
749
750void EventHub::cancelVibrate(int32_t deviceId) {
751 AutoMutex _l(mLock);
752 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700753 if (device && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800754 if (device->ffEffectPlaying) {
755 device->ffEffectPlaying = false;
756
757 struct input_event ev;
758 ev.time.tv_sec = 0;
759 ev.time.tv_usec = 0;
760 ev.type = EV_FF;
761 ev.code = device->ffEffectId;
762 ev.value = 0;
763 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
764 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhan2b281812019-08-29 14:12:42 -0700765 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800766 return;
767 }
768 }
769 }
770}
771
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100772EventHub::Device* EventHub::getDeviceByDescriptorLocked(const std::string& descriptor) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800773 size_t size = mDevices.size();
774 for (size_t i = 0; i < size; i++) {
775 Device* device = mDevices.valueAt(i);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100776 if (descriptor == device->identifier.descriptor) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800777 return device;
778 }
779 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700780 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800781}
782
783EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -0800784 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800785 deviceId = mBuiltInKeyboardId;
786 }
787 ssize_t index = mDevices.indexOfKey(deviceId);
788 return index >= 0 ? mDevices.valueAt(index) : NULL;
789}
790
791EventHub::Device* EventHub::getDeviceByPathLocked(const char* devicePath) const {
792 for (size_t i = 0; i < mDevices.size(); i++) {
793 Device* device = mDevices.valueAt(i);
794 if (device->path == devicePath) {
795 return device;
796 }
797 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700798 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800799}
800
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700801/**
802 * The file descriptor could be either input device, or a video device (associated with a
803 * specific input device). Check both cases here, and return the device that this event
804 * belongs to. Caller can compare the fd's once more to determine event type.
805 * Looks through all input devices, and only attached video devices. Unattached video
806 * devices are ignored.
807 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700808EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
809 for (size_t i = 0; i < mDevices.size(); i++) {
810 Device* device = mDevices.valueAt(i);
811 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700812 // This is an input device event
813 return device;
814 }
815 if (device->videoDevice && device->videoDevice->getFd() == fd) {
816 // This is a video device event
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700817 return device;
818 }
819 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700820 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
821 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700822 return nullptr;
823}
824
Michael Wrightd02c5b62014-02-10 15:10:22 -0800825size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
826 ALOG_ASSERT(bufferSize >= 1);
827
828 AutoMutex _l(mLock);
829
830 struct input_event readBuffer[bufferSize];
831
832 RawEvent* event = buffer;
833 size_t capacity = bufferSize;
834 bool awoken = false;
835 for (;;) {
836 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
837
838 // Reopen input devices if needed.
839 if (mNeedToReopenDevices) {
840 mNeedToReopenDevices = false;
841
842 ALOGI("Reopening all input devices due to a configuration change.");
843
844 closeAllDevicesLocked();
845 mNeedToScanDevices = true;
846 break; // return to the caller before we actually rescan
847 }
848
849 // Report any devices that had last been added/removed.
850 while (mClosingDevices) {
851 Device* device = mClosingDevices;
Prabir Pradhan2b281812019-08-29 14:12:42 -0700852 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800853 mClosingDevices = device->next;
854 event->when = now;
Prabir Pradhan2b281812019-08-29 14:12:42 -0700855 event->deviceId = (device->id == mBuiltInKeyboardId)
856 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
857 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800858 event->type = DEVICE_REMOVED;
859 event += 1;
860 delete device;
861 mNeedToSendFinishedDeviceScan = true;
862 if (--capacity == 0) {
863 break;
864 }
865 }
866
867 if (mNeedToScanDevices) {
868 mNeedToScanDevices = false;
869 scanDevicesLocked();
870 mNeedToSendFinishedDeviceScan = true;
871 }
872
Yi Kong9b14ac62018-07-17 13:48:38 -0700873 while (mOpeningDevices != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874 Device* device = mOpeningDevices;
Prabir Pradhan2b281812019-08-29 14:12:42 -0700875 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800876 mOpeningDevices = device->next;
877 event->when = now;
878 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
879 event->type = DEVICE_ADDED;
880 event += 1;
881 mNeedToSendFinishedDeviceScan = true;
882 if (--capacity == 0) {
883 break;
884 }
885 }
886
887 if (mNeedToSendFinishedDeviceScan) {
888 mNeedToSendFinishedDeviceScan = false;
889 event->when = now;
890 event->type = FINISHED_DEVICE_SCAN;
891 event += 1;
892 if (--capacity == 0) {
893 break;
894 }
895 }
896
897 // Grab the next input event.
898 bool deviceChanged = false;
899 while (mPendingEventIndex < mPendingEventCount) {
900 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700901 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800902 if (eventItem.events & EPOLLIN) {
903 mPendingINotify = true;
904 } else {
905 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
906 }
907 continue;
908 }
909
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700910 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800911 if (eventItem.events & EPOLLIN) {
912 ALOGV("awoken after wake()");
913 awoken = true;
914 char buffer[16];
915 ssize_t nRead;
916 do {
917 nRead = read(mWakeReadPipeFd, buffer, sizeof(buffer));
918 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(buffer));
919 } else {
920 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhan2b281812019-08-29 14:12:42 -0700921 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800922 }
923 continue;
924 }
925
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700926 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700927 if (!device) {
Prabir Pradhan2b281812019-08-29 14:12:42 -0700928 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
929 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700930 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800931 continue;
932 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700933 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
934 if (eventItem.events & EPOLLIN) {
935 size_t numFrames = device->videoDevice->readAndQueueFrames();
936 if (numFrames == 0) {
937 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhan2b281812019-08-29 14:12:42 -0700938 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700939 }
940 } else if (eventItem.events & EPOLLHUP) {
941 // TODO(b/121395353) - consider adding EPOLLRDHUP
942 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhan2b281812019-08-29 14:12:42 -0700943 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700944 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
945 device->videoDevice = nullptr;
946 } else {
Prabir Pradhan2b281812019-08-29 14:12:42 -0700947 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
948 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700949 ALOG_ASSERT(!DEBUG);
950 }
951 continue;
952 }
953 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -0800954 if (eventItem.events & EPOLLIN) {
Prabir Pradhan2b281812019-08-29 14:12:42 -0700955 int32_t readSize =
956 read(device->fd, readBuffer, sizeof(struct input_event) * capacity);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800957 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
958 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -0700959 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Prabir Pradhan2b281812019-08-29 14:12:42 -0700960 " bufferSize: %zu capacity: %zu errno: %d)\n",
961 device->fd, readSize, bufferSize, capacity, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800962 deviceChanged = true;
963 closeDeviceLocked(device);
964 } else if (readSize < 0) {
965 if (errno != EAGAIN && errno != EINTR) {
966 ALOGW("could not get event (errno=%d)", errno);
967 }
968 } else if ((readSize % sizeof(struct input_event)) != 0) {
969 ALOGE("could not get event (wrong size: %d)", readSize);
970 } else {
971 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
972
973 size_t count = size_t(readSize) / sizeof(struct input_event);
974 for (size_t i = 0; i < count; i++) {
975 struct input_event& iev = readBuffer[i];
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800976 event->when = processEventTimestamp(iev);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800977 event->deviceId = deviceId;
978 event->type = iev.type;
979 event->code = iev.code;
980 event->value = iev.value;
981 event += 1;
982 capacity -= 1;
983 }
984 if (capacity == 0) {
985 // The result buffer is full. Reset the pending event index
986 // so we will try to read the device again on the next iteration.
987 mPendingEventIndex -= 1;
988 break;
989 }
990 }
991 } else if (eventItem.events & EPOLLHUP) {
992 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhan2b281812019-08-29 14:12:42 -0700993 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800994 deviceChanged = true;
995 closeDeviceLocked(device);
996 } else {
Prabir Pradhan2b281812019-08-29 14:12:42 -0700997 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
998 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800999 }
1000 }
1001
1002 // readNotify() will modify the list of devices so this must be done after
1003 // processing all other events to ensure that we read all remaining events
1004 // before closing the devices.
1005 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
1006 mPendingINotify = false;
1007 readNotifyLocked();
1008 deviceChanged = true;
1009 }
1010
1011 // Report added or removed devices immediately.
1012 if (deviceChanged) {
1013 continue;
1014 }
1015
1016 // Return now if we have collected any events or if we were explicitly awoken.
1017 if (event != buffer || awoken) {
1018 break;
1019 }
1020
1021 // Poll for events. Mind the wake lock dance!
1022 // We hold a wake lock at all times except during epoll_wait(). This works due to some
1023 // subtle choreography. When a device driver has pending (unread) events, it acquires
1024 // a kernel wake lock. However, once the last pending event has been read, the device
1025 // driver will release the kernel wake lock. To prevent the system from going to sleep
1026 // when this happens, the EventHub holds onto its own user wake lock while the client
1027 // is processing events. Thus the system can only sleep if there are no events
1028 // pending or currently being processed.
1029 //
1030 // The timeout is advisory only. If the device is asleep, it will not wake just to
1031 // service the timeout.
1032 mPendingEventIndex = 0;
1033
1034 mLock.unlock(); // release lock before poll, must be before release_wake_lock
1035 release_wake_lock(WAKE_LOCK_ID);
1036
1037 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1038
1039 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
1040 mLock.lock(); // reacquire lock after poll, must be after acquire_wake_lock
1041
1042 if (pollResult == 0) {
1043 // Timed out.
1044 mPendingEventCount = 0;
1045 break;
1046 }
1047
1048 if (pollResult < 0) {
1049 // An error occurred.
1050 mPendingEventCount = 0;
1051
1052 // Sleep after errors to avoid locking up the system.
1053 // Hopefully the error is transient.
1054 if (errno != EINTR) {
1055 ALOGW("poll failed (errno=%d)\n", errno);
1056 usleep(100000);
1057 }
1058 } else {
1059 // Some events occurred.
1060 mPendingEventCount = size_t(pollResult);
1061 }
1062 }
1063
1064 // All done, return the number of events we read.
1065 return event - buffer;
1066}
1067
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001068std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
1069 AutoMutex _l(mLock);
1070
1071 Device* device = getDeviceLocked(deviceId);
1072 if (!device || !device->videoDevice) {
1073 return {};
1074 }
1075 return device->videoDevice->consumeFrames();
1076}
1077
Michael Wrightd02c5b62014-02-10 15:10:22 -08001078void EventHub::wake() {
1079 ALOGV("wake() called");
1080
1081 ssize_t nWrite;
1082 do {
1083 nWrite = write(mWakeWritePipeFd, "W", 1);
1084 } while (nWrite == -1 && errno == EINTR);
1085
1086 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001087 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001088 }
1089}
1090
1091void EventHub::scanDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001092 status_t result = scanDirLocked(DEVICE_PATH);
Prabir Pradhan2b281812019-08-29 14:12:42 -07001093 if (result < 0) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001094 ALOGE("scan dir failed for %s", DEVICE_PATH);
1095 }
Philip Quinn39b81682019-01-09 22:20:39 -08001096 if (isV4lScanningEnabled()) {
1097 result = scanVideoDirLocked(VIDEO_DEVICE_PATH);
1098 if (result != OK) {
1099 ALOGE("scan video dir failed for %s", VIDEO_DEVICE_PATH);
1100 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001101 }
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001102 if (mDevices.indexOfKey(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) < 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001103 createVirtualKeyboardLocked();
1104 }
1105}
1106
1107// ----------------------------------------------------------------------------
1108
1109static bool containsNonZeroByte(const uint8_t* array, uint32_t startIndex, uint32_t endIndex) {
1110 const uint8_t* end = array + endIndex;
1111 array += startIndex;
1112 while (array != end) {
1113 if (*(array++) != 0) {
1114 return true;
1115 }
1116 }
1117 return false;
1118}
1119
1120static const int32_t GAMEPAD_KEYCODES[] = {
Prabir Pradhan2b281812019-08-29 14:12:42 -07001121 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C, //
1122 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z, //
1123 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1, //
1124 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2, //
1125 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR, //
1126 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE, //
Michael Wrightd02c5b62014-02-10 15:10:22 -08001127};
1128
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001129status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001130 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001131 struct epoll_event eventItem = {};
1132 eventItem.events = EPOLLIN | EPOLLWAKEUP;
1133 eventItem.data.fd = fd;
1134 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1135 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001136 return -errno;
1137 }
1138 return OK;
1139}
1140
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001141status_t EventHub::unregisterFdFromEpoll(int fd) {
1142 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
1143 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
1144 return -errno;
1145 }
1146 return OK;
1147}
1148
1149status_t EventHub::registerDeviceForEpollLocked(Device* device) {
1150 if (device == nullptr) {
1151 if (DEBUG) {
1152 LOG_ALWAYS_FATAL("Cannot call registerDeviceForEpollLocked with null Device");
1153 }
1154 return BAD_VALUE;
1155 }
1156 status_t result = registerFdForEpoll(device->fd);
1157 if (result != OK) {
1158 ALOGE("Could not add input device fd to epoll for device %" PRId32, device->id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001159 return result;
1160 }
1161 if (device->videoDevice) {
1162 registerVideoDeviceForEpollLocked(*device->videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001163 }
1164 return result;
1165}
1166
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001167void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
1168 status_t result = registerFdForEpoll(videoDevice.getFd());
1169 if (result != OK) {
1170 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
1171 }
1172}
1173
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001174status_t EventHub::unregisterDeviceFromEpollLocked(Device* device) {
1175 if (device->hasValidFd()) {
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001176 status_t result = unregisterFdFromEpoll(device->fd);
1177 if (result != OK) {
1178 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device->id);
1179 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001180 }
1181 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001182 if (device->videoDevice) {
1183 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1184 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001185 return OK;
1186}
1187
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001188void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
1189 if (videoDevice.hasValidFd()) {
1190 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
1191 if (result != OK) {
1192 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhan2b281812019-08-29 14:12:42 -07001193 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001194 }
1195 }
1196}
1197
1198status_t EventHub::openDeviceLocked(const char* devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001199 char buffer[80];
1200
1201 ALOGV("Opening device: %s", devicePath);
1202
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001203 int fd = open(devicePath, O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhan2b281812019-08-29 14:12:42 -07001204 if (fd < 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001205 ALOGE("could not open %s, %s\n", devicePath, strerror(errno));
1206 return -1;
1207 }
1208
1209 InputDeviceIdentifier identifier;
1210
1211 // Get device name.
Prabir Pradhan2b281812019-08-29 14:12:42 -07001212 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001213 ALOGE("Could not get device name for %s: %s", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001214 } else {
1215 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001216 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001217 }
1218
1219 // Check to see if the device is on our excluded list
1220 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001221 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001222 if (identifier.name == item) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001223 ALOGI("ignoring event id %s driver %s\n", devicePath, item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001224 close(fd);
1225 return -1;
1226 }
1227 }
1228
1229 // Get device driver version.
1230 int driverVersion;
Prabir Pradhan2b281812019-08-29 14:12:42 -07001231 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001232 ALOGE("could not get driver version for %s, %s\n", devicePath, strerror(errno));
1233 close(fd);
1234 return -1;
1235 }
1236
1237 // Get device identifier.
1238 struct input_id inputId;
Prabir Pradhan2b281812019-08-29 14:12:42 -07001239 if (ioctl(fd, EVIOCGID, &inputId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001240 ALOGE("could not get device input id for %s, %s\n", devicePath, strerror(errno));
1241 close(fd);
1242 return -1;
1243 }
1244 identifier.bus = inputId.bustype;
1245 identifier.product = inputId.product;
1246 identifier.vendor = inputId.vendor;
1247 identifier.version = inputId.version;
1248
1249 // Get device physical location.
Prabir Pradhan2b281812019-08-29 14:12:42 -07001250 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
1251 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001252 } else {
1253 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001254 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001255 }
1256
1257 // Get device unique id.
Prabir Pradhan2b281812019-08-29 14:12:42 -07001258 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
1259 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001260 } else {
1261 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001262 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001263 }
1264
1265 // Fill in the descriptor.
1266 assignDescriptorLocked(identifier);
1267
Michael Wrightd02c5b62014-02-10 15:10:22 -08001268 // Allocate device. (The device object takes ownership of the fd at this point.)
1269 int32_t deviceId = mNextDeviceId++;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001270 Device* device = new Device(fd, deviceId, devicePath, identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001271
1272 ALOGV("add device %d: %s\n", deviceId, devicePath);
1273 ALOGV(" bus: %04x\n"
Prabir Pradhan2b281812019-08-29 14:12:42 -07001274 " vendor %04x\n"
1275 " product %04x\n"
1276 " version %04x\n",
1277 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001278 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
1279 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
1280 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
1281 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhan2b281812019-08-29 14:12:42 -07001282 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
1283 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001284
1285 // Load the configuration file for the device.
1286 loadConfigurationLocked(device);
1287
1288 // Figure out the kinds of events the device reports.
1289 ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(device->keyBitmask)), device->keyBitmask);
1290 ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(device->absBitmask)), device->absBitmask);
1291 ioctl(fd, EVIOCGBIT(EV_REL, sizeof(device->relBitmask)), device->relBitmask);
1292 ioctl(fd, EVIOCGBIT(EV_SW, sizeof(device->swBitmask)), device->swBitmask);
1293 ioctl(fd, EVIOCGBIT(EV_LED, sizeof(device->ledBitmask)), device->ledBitmask);
1294 ioctl(fd, EVIOCGBIT(EV_FF, sizeof(device->ffBitmask)), device->ffBitmask);
1295 ioctl(fd, EVIOCGPROP(sizeof(device->propBitmask)), device->propBitmask);
1296
1297 // See if this is a keyboard. Ignore everything in the button range except for
1298 // joystick and gamepad buttons which are handled like keyboards for the most part.
Prabir Pradhan2b281812019-08-29 14:12:42 -07001299 bool haveKeyboardKeys =
1300 containsNonZeroByte(device->keyBitmask, 0, sizeof_bit_array(BTN_MISC)) ||
1301 containsNonZeroByte(device->keyBitmask, sizeof_bit_array(KEY_OK),
1302 sizeof_bit_array(KEY_MAX + 1));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001303 bool haveGamepadButtons = containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_MISC),
Prabir Pradhan2b281812019-08-29 14:12:42 -07001304 sizeof_bit_array(BTN_MOUSE)) ||
1305 containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_JOYSTICK),
1306 sizeof_bit_array(BTN_DIGI));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001307 if (haveKeyboardKeys || haveGamepadButtons) {
1308 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1309 }
1310
1311 // See if this is a cursor device such as a trackball or mouse.
Prabir Pradhan2b281812019-08-29 14:12:42 -07001312 if (test_bit(BTN_MOUSE, device->keyBitmask) && test_bit(REL_X, device->relBitmask) &&
1313 test_bit(REL_Y, device->relBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001314 device->classes |= INPUT_DEVICE_CLASS_CURSOR;
1315 }
1316
Prashant Malani1941ff52015-08-11 18:29:28 -07001317 // See if this is a rotary encoder type device.
1318 String8 deviceType = String8();
1319 if (device->configuration &&
1320 device->configuration->tryGetProperty(String8("device.type"), deviceType)) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07001321 if (!deviceType.compare(String8("rotaryEncoder"))) {
1322 device->classes |= INPUT_DEVICE_CLASS_ROTARY_ENCODER;
1323 }
Prashant Malani1941ff52015-08-11 18:29:28 -07001324 }
1325
Michael Wrightd02c5b62014-02-10 15:10:22 -08001326 // See if this is a touch pad.
1327 // Is this a new modern multi-touch driver?
Prabir Pradhan2b281812019-08-29 14:12:42 -07001328 if (test_bit(ABS_MT_POSITION_X, device->absBitmask) &&
1329 test_bit(ABS_MT_POSITION_Y, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001330 // Some joysticks such as the PS3 controller report axes that conflict
1331 // with the ABS_MT range. Try to confirm that the device really is
1332 // a touch screen.
1333 if (test_bit(BTN_TOUCH, device->keyBitmask) || !haveGamepadButtons) {
1334 device->classes |= INPUT_DEVICE_CLASS_TOUCH | INPUT_DEVICE_CLASS_TOUCH_MT;
1335 }
Prabir Pradhan2b281812019-08-29 14:12:42 -07001336 // Is this an old style single-touch driver?
1337 } else if (test_bit(BTN_TOUCH, device->keyBitmask) && test_bit(ABS_X, device->absBitmask) &&
1338 test_bit(ABS_Y, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001339 device->classes |= INPUT_DEVICE_CLASS_TOUCH;
Prabir Pradhan2b281812019-08-29 14:12:42 -07001340 // Is this a BT stylus?
Michael Wright842500e2015-03-13 17:32:02 -07001341 } else if ((test_bit(ABS_PRESSURE, device->absBitmask) ||
Prabir Pradhan2b281812019-08-29 14:12:42 -07001342 test_bit(BTN_TOUCH, device->keyBitmask)) &&
1343 !test_bit(ABS_X, device->absBitmask) && !test_bit(ABS_Y, device->absBitmask)) {
Michael Wright842500e2015-03-13 17:32:02 -07001344 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
1345 // Keyboard will try to claim some of the buttons but we really want to reserve those so we
1346 // can fuse it with the touch screen data, so just take them back. Note this means an
1347 // external stylus cannot also be a keyboard device.
1348 device->classes &= ~INPUT_DEVICE_CLASS_KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001349 }
1350
1351 // See if this device is a joystick.
1352 // Assumes that joysticks always have gamepad buttons in order to distinguish them
1353 // from other devices such as accelerometers that also have absolute axes.
1354 if (haveGamepadButtons) {
1355 uint32_t assumedClasses = device->classes | INPUT_DEVICE_CLASS_JOYSTICK;
1356 for (int i = 0; i <= ABS_MAX; i++) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07001357 if (test_bit(i, device->absBitmask) &&
1358 (getAbsAxisUsage(i, assumedClasses) & INPUT_DEVICE_CLASS_JOYSTICK)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001359 device->classes = assumedClasses;
1360 break;
1361 }
1362 }
1363 }
1364
1365 // Check whether this device has switches.
1366 for (int i = 0; i <= SW_MAX; i++) {
1367 if (test_bit(i, device->swBitmask)) {
1368 device->classes |= INPUT_DEVICE_CLASS_SWITCH;
1369 break;
1370 }
1371 }
1372
1373 // Check whether this device supports the vibrator.
1374 if (test_bit(FF_RUMBLE, device->ffBitmask)) {
1375 device->classes |= INPUT_DEVICE_CLASS_VIBRATOR;
1376 }
1377
1378 // Configure virtual keys.
1379 if ((device->classes & INPUT_DEVICE_CLASS_TOUCH)) {
1380 // Load the virtual keys for the touch screen, if any.
1381 // We do this now so that we can make sure to load the keymap if necessary.
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001382 bool success = loadVirtualKeyMapLocked(device);
1383 if (success) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001384 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1385 }
1386 }
1387
1388 // Load the key map.
1389 // We need to do this for joysticks too because the key layout may specify axes.
1390 status_t keyMapStatus = NAME_NOT_FOUND;
1391 if (device->classes & (INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_JOYSTICK)) {
1392 // Load the keymap for the device.
1393 keyMapStatus = loadKeyMapLocked(device);
1394 }
1395
1396 // Configure the keyboard, gamepad or virtual keyboard.
1397 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1398 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhan2b281812019-08-29 14:12:42 -07001399 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
1400 isEligibleBuiltInKeyboard(device->identifier, device->configuration, &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001401 mBuiltInKeyboardId = device->id;
1402 }
1403
1404 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
1405 if (hasKeycodeLocked(device, AKEYCODE_Q)) {
1406 device->classes |= INPUT_DEVICE_CLASS_ALPHAKEY;
1407 }
1408
1409 // See if this device has a DPAD.
1410 if (hasKeycodeLocked(device, AKEYCODE_DPAD_UP) &&
Prabir Pradhan2b281812019-08-29 14:12:42 -07001411 hasKeycodeLocked(device, AKEYCODE_DPAD_DOWN) &&
1412 hasKeycodeLocked(device, AKEYCODE_DPAD_LEFT) &&
1413 hasKeycodeLocked(device, AKEYCODE_DPAD_RIGHT) &&
1414 hasKeycodeLocked(device, AKEYCODE_DPAD_CENTER)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001415 device->classes |= INPUT_DEVICE_CLASS_DPAD;
1416 }
1417
1418 // See if this device has a gamepad.
Prabir Pradhan2b281812019-08-29 14:12:42 -07001419 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES) / sizeof(GAMEPAD_KEYCODES[0]); i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001420 if (hasKeycodeLocked(device, GAMEPAD_KEYCODES[i])) {
1421 device->classes |= INPUT_DEVICE_CLASS_GAMEPAD;
1422 break;
1423 }
1424 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001425 }
1426
1427 // If the device isn't recognized as something we handle, don't monitor it.
1428 if (device->classes == 0) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07001429 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath,
1430 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001431 delete device;
1432 return -1;
1433 }
1434
Tim Kilbourn063ff532015-04-08 10:26:18 -07001435 // Determine whether the device has a mic.
1436 if (deviceHasMicLocked(device)) {
1437 device->classes |= INPUT_DEVICE_CLASS_MIC;
1438 }
1439
Michael Wrightd02c5b62014-02-10 15:10:22 -08001440 // Determine whether the device is external or internal.
1441 if (isExternalDeviceLocked(device)) {
1442 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL;
1443 }
1444
Prabir Pradhan2b281812019-08-29 14:12:42 -07001445 if (device->classes & (INPUT_DEVICE_CLASS_JOYSTICK | INPUT_DEVICE_CLASS_DPAD) &&
1446 device->classes & INPUT_DEVICE_CLASS_GAMEPAD) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001447 device->controllerNumber = getNextControllerNumberLocked(device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001448 setLedForControllerLocked(device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001449 }
1450
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001451 // Find a matching video device by comparing device names
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001452 // This should be done before registerDeviceForEpollLocked, so that both fds are added to epoll
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001453 for (std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
1454 if (device->identifier.name == videoDevice->getName()) {
1455 device->videoDevice = std::move(videoDevice);
1456 break;
1457 }
1458 }
Prabir Pradhan2b281812019-08-29 14:12:42 -07001459 mUnattachedVideoDevices
1460 .erase(std::remove_if(mUnattachedVideoDevices.begin(), mUnattachedVideoDevices.end(),
1461 [](const std::unique_ptr<TouchVideoDevice>& videoDevice) {
1462 return videoDevice == nullptr;
1463 }),
1464 mUnattachedVideoDevices.end());
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001465
1466 if (registerDeviceForEpollLocked(device) != OK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001467 delete device;
1468 return -1;
1469 }
1470
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001471 configureFd(device);
1472
1473 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=0x%x, "
Prabir Pradhan2b281812019-08-29 14:12:42 -07001474 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
1475 deviceId, fd, devicePath, device->identifier.name.c_str(), device->classes,
1476 device->configurationFile.c_str(), device->keyMap.keyLayoutFile.c_str(),
1477 device->keyMap.keyCharacterMapFile.c_str(), toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001478
1479 addDeviceLocked(device);
1480 return OK;
1481}
1482
1483void EventHub::configureFd(Device* device) {
1484 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
1485 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1486 // Disable kernel key repeat since we handle it ourselves
1487 unsigned int repeatRate[] = {0, 0};
1488 if (ioctl(device->fd, EVIOCSREP, repeatRate)) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07001489 ALOGW("Unable to disable kernel key repeat for %s: %s", device->path.c_str(),
1490 strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001491 }
1492 }
1493
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001494 std::string wakeMechanism = "EPOLLWAKEUP";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001495 if (!mUsingEpollWakeup) {
1496#ifndef EVIOCSSUSPENDBLOCK
1497 // uapi headers don't include EVIOCSSUSPENDBLOCK, and future kernels
1498 // will use an epoll flag instead, so as long as we want to support
1499 // this feature, we need to be prepared to define the ioctl ourselves.
1500#define EVIOCSSUSPENDBLOCK _IOW('E', 0x91, int)
1501#endif
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001502 if (ioctl(device->fd, EVIOCSSUSPENDBLOCK, 1)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001503 wakeMechanism = "<none>";
1504 } else {
1505 wakeMechanism = "EVIOCSSUSPENDBLOCK";
1506 }
1507 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001508 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
1509 // associated with input events. This is important because the input system
1510 // uses the timestamps extensively and assumes they were recorded using the monotonic
1511 // clock.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001512 int clockId = CLOCK_MONOTONIC;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001513 bool usingClockIoctl = !ioctl(device->fd, EVIOCSCLOCKID, &clockId);
Prabir Pradhan2b281812019-08-29 14:12:42 -07001514 ALOGI("wakeMechanism=%s, usingClockIoctl=%s", wakeMechanism.c_str(), toString(usingClockIoctl));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001515}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001516
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001517void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
1518 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
1519 if (!videoDevice) {
1520 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
1521 return;
1522 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001523 // Transfer ownership of this video device to a matching input device
1524 for (size_t i = 0; i < mDevices.size(); i++) {
1525 Device* device = mDevices.valueAt(i);
1526 if (videoDevice->getName() == device->identifier.name) {
1527 device->videoDevice = std::move(videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001528 if (device->enabled) {
1529 registerVideoDeviceForEpollLocked(*device->videoDevice);
1530 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001531 return;
1532 }
1533 }
1534
1535 // Couldn't find a matching input device, so just add it to a temporary holding queue.
1536 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001537 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhan2b281812019-08-29 14:12:42 -07001538 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001539 mUnattachedVideoDevices.push_back(std::move(videoDevice));
1540}
1541
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001542bool EventHub::isDeviceEnabled(int32_t deviceId) {
1543 AutoMutex _l(mLock);
1544 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001545 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001546 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1547 return false;
1548 }
1549 return device->enabled;
1550}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001551
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001552status_t EventHub::enableDevice(int32_t deviceId) {
1553 AutoMutex _l(mLock);
1554 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001555 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001556 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1557 return BAD_VALUE;
1558 }
1559 if (device->enabled) {
1560 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
1561 return OK;
1562 }
1563 status_t result = device->enable();
1564 if (result != OK) {
1565 ALOGE("Failed to enable device %" PRId32, deviceId);
1566 return result;
1567 }
1568
1569 configureFd(device);
1570
1571 return registerDeviceForEpollLocked(device);
1572}
1573
1574status_t EventHub::disableDevice(int32_t deviceId) {
1575 AutoMutex _l(mLock);
1576 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001577 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001578 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1579 return BAD_VALUE;
1580 }
1581 if (!device->enabled) {
1582 ALOGW("Duplicate call to %s, input device already disabled", __func__);
1583 return OK;
1584 }
1585 unregisterDeviceFromEpollLocked(device);
1586 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001587}
1588
1589void EventHub::createVirtualKeyboardLocked() {
1590 InputDeviceIdentifier identifier;
1591 identifier.name = "Virtual";
1592 identifier.uniqueId = "<virtual>";
1593 assignDescriptorLocked(identifier);
1594
Prabir Pradhan2b281812019-08-29 14:12:42 -07001595 Device* device =
1596 new Device(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>", identifier);
1597 device->classes = INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_ALPHAKEY |
1598 INPUT_DEVICE_CLASS_DPAD | INPUT_DEVICE_CLASS_VIRTUAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001599 loadKeyMapLocked(device);
1600 addDeviceLocked(device);
1601}
1602
1603void EventHub::addDeviceLocked(Device* device) {
1604 mDevices.add(device->id, device);
1605 device->next = mOpeningDevices;
1606 mOpeningDevices = device;
1607}
1608
1609void EventHub::loadConfigurationLocked(Device* device) {
1610 device->configurationFile = getInputDeviceConfigurationFilePathByDeviceIdentifier(
1611 device->identifier, INPUT_DEVICE_CONFIGURATION_FILE_TYPE_CONFIGURATION);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001612 if (device->configurationFile.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001613 ALOGD("No input device configuration file found for device '%s'.",
Prabir Pradhan2b281812019-08-29 14:12:42 -07001614 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001615 } else {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001616 status_t status = PropertyMap::load(String8(device->configurationFile.c_str()),
Prabir Pradhan2b281812019-08-29 14:12:42 -07001617 &device->configuration);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001618 if (status) {
1619 ALOGE("Error loading input device configuration file for device '%s'. "
Prabir Pradhan2b281812019-08-29 14:12:42 -07001620 "Using default configuration.",
1621 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001622 }
1623 }
1624}
1625
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001626bool EventHub::loadVirtualKeyMapLocked(Device* device) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001627 // The virtual key map is supplied by the kernel as a system board property file.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001628 std::string path;
1629 path += "/sys/board_properties/virtualkeys.";
Siarhei Vishniakoub45635c2019-02-20 19:22:09 -06001630 path += device->identifier.getCanonicalName();
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001631 if (access(path.c_str(), R_OK)) {
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001632 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001633 }
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001634 device->virtualKeyMap = VirtualKeyMap::load(path);
1635 return device->virtualKeyMap != nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001636}
1637
1638status_t EventHub::loadKeyMapLocked(Device* device) {
1639 return device->keyMap.load(device->identifier, device->configuration);
1640}
1641
1642bool EventHub::isExternalDeviceLocked(Device* device) {
1643 if (device->configuration) {
1644 bool value;
1645 if (device->configuration->tryGetProperty(String8("device.internal"), value)) {
1646 return !value;
1647 }
1648 }
1649 return device->identifier.bus == BUS_USB || device->identifier.bus == BUS_BLUETOOTH;
1650}
1651
Tim Kilbourn063ff532015-04-08 10:26:18 -07001652bool EventHub::deviceHasMicLocked(Device* device) {
1653 if (device->configuration) {
1654 bool value;
1655 if (device->configuration->tryGetProperty(String8("audio.mic"), value)) {
1656 return value;
1657 }
1658 }
1659 return false;
1660}
1661
Michael Wrightd02c5b62014-02-10 15:10:22 -08001662int32_t EventHub::getNextControllerNumberLocked(Device* device) {
1663 if (mControllerNumbers.isFull()) {
1664 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Prabir Pradhan2b281812019-08-29 14:12:42 -07001665 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001666 return 0;
1667 }
1668 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
1669 // one
1670 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
1671}
1672
1673void EventHub::releaseControllerNumberLocked(Device* device) {
1674 int32_t num = device->controllerNumber;
Prabir Pradhan2b281812019-08-29 14:12:42 -07001675 device->controllerNumber = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001676 if (num == 0) {
1677 return;
1678 }
1679 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
1680}
1681
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001682void EventHub::setLedForControllerLocked(Device* device) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001683 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
1684 setLedStateLocked(device, ALED_CONTROLLER_1 + i, device->controllerNumber == i + 1);
1685 }
1686}
1687
1688bool EventHub::hasKeycodeLocked(Device* device, int keycode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001689 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001690 return false;
1691 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001692
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001693 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001694 device->keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes);
1695 const size_t N = scanCodes.size();
Prabir Pradhan2b281812019-08-29 14:12:42 -07001696 for (size_t i = 0; i < N && i <= KEY_MAX; i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001697 int32_t sc = scanCodes[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001698 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, device->keyBitmask)) {
1699 return true;
1700 }
1701 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001702
Michael Wrightd02c5b62014-02-10 15:10:22 -08001703 return false;
1704}
1705
1706status_t EventHub::mapLed(Device* device, int32_t led, int32_t* outScanCode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001707 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001708 return NAME_NOT_FOUND;
1709 }
1710
1711 int32_t scanCode;
Prabir Pradhan2b281812019-08-29 14:12:42 -07001712 if (device->keyMap.keyLayoutMap->findScanCodeForLed(led, &scanCode) != NAME_NOT_FOUND) {
1713 if (scanCode >= 0 && scanCode <= LED_MAX && test_bit(scanCode, device->ledBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001714 *outScanCode = scanCode;
1715 return NO_ERROR;
1716 }
1717 }
1718 return NAME_NOT_FOUND;
1719}
1720
Prabir Pradhan2b281812019-08-29 14:12:42 -07001721void EventHub::closeDeviceByPathLocked(const char* devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001722 Device* device = getDeviceByPathLocked(devicePath);
1723 if (device) {
1724 closeDeviceLocked(device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001725 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001726 }
1727 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001728}
1729
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001730/**
1731 * Find the video device by filename, and close it.
1732 * The video device is closed by path during an inotify event, where we don't have the
1733 * additional context about the video device fd, or the associated input device.
1734 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001735void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001736 // A video device may be owned by an existing input device, or it may be stored in
1737 // the mUnattachedVideoDevices queue. Check both locations.
1738 for (size_t i = 0; i < mDevices.size(); i++) {
1739 Device* device = mDevices.valueAt(i);
1740 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001741 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001742 device->videoDevice = nullptr;
1743 return;
1744 }
1745 }
Prabir Pradhan2b281812019-08-29 14:12:42 -07001746 mUnattachedVideoDevices
1747 .erase(std::remove_if(mUnattachedVideoDevices.begin(), mUnattachedVideoDevices.end(),
1748 [&devicePath](
1749 const std::unique_ptr<TouchVideoDevice>& videoDevice) {
1750 return videoDevice->getPath() == devicePath;
1751 }),
1752 mUnattachedVideoDevices.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001753}
1754
1755void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001756 mUnattachedVideoDevices.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001757 while (mDevices.size() > 0) {
1758 closeDeviceLocked(mDevices.valueAt(mDevices.size() - 1));
1759 }
1760}
1761
1762void EventHub::closeDeviceLocked(Device* device) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07001763 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=0x%x", device->path.c_str(),
1764 device->identifier.name.c_str(), device->id, device->fd, device->classes);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001765
1766 if (device->id == mBuiltInKeyboardId) {
1767 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Prabir Pradhan2b281812019-08-29 14:12:42 -07001768 device->path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001769 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
1770 }
1771
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001772 unregisterDeviceFromEpollLocked(device);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001773 if (device->videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001774 // This must be done after the video device is removed from epoll
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001775 mUnattachedVideoDevices.push_back(std::move(device->videoDevice));
1776 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001777
1778 releaseControllerNumberLocked(device);
1779
1780 mDevices.removeItem(device->id);
1781 device->close();
1782
1783 // Unlink for opening devices list if it is present.
Yi Kong9b14ac62018-07-17 13:48:38 -07001784 Device* pred = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001785 bool found = false;
Prabir Pradhan2b281812019-08-29 14:12:42 -07001786 for (Device* entry = mOpeningDevices; entry != nullptr;) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001787 if (entry == device) {
1788 found = true;
1789 break;
1790 }
1791 pred = entry;
1792 entry = entry->next;
1793 }
1794 if (found) {
1795 // Unlink the device from the opening devices list then delete it.
1796 // We don't need to tell the client that the device was closed because
1797 // it does not even know it was opened in the first place.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001798 ALOGI("Device %s was immediately closed after opening.", device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799 if (pred) {
1800 pred->next = device->next;
1801 } else {
1802 mOpeningDevices = device->next;
1803 }
1804 delete device;
1805 } else {
1806 // Link into closing devices list.
1807 // The device will be deleted later after we have informed the client.
1808 device->next = mClosingDevices;
1809 mClosingDevices = device;
1810 }
1811}
1812
1813status_t EventHub::readNotifyLocked() {
1814 int res;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001815 char event_buf[512];
1816 int event_size;
1817 int event_pos = 0;
Prabir Pradhan2b281812019-08-29 14:12:42 -07001818 struct inotify_event* event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001819
1820 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
1821 res = read(mINotifyFd, event_buf, sizeof(event_buf));
Prabir Pradhan2b281812019-08-29 14:12:42 -07001822 if (res < (int)sizeof(*event)) {
1823 if (errno == EINTR) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001824 ALOGW("could not get event, %s\n", strerror(errno));
1825 return -1;
1826 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001827
Prabir Pradhan2b281812019-08-29 14:12:42 -07001828 while (res >= (int)sizeof(*event)) {
1829 event = (struct inotify_event*)(event_buf + event_pos);
1830 if (event->len) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001831 if (event->wd == mInputWd) {
1832 std::string filename = StringPrintf("%s/%s", DEVICE_PATH, event->name);
Prabir Pradhan2b281812019-08-29 14:12:42 -07001833 if (event->mask & IN_CREATE) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001834 openDeviceLocked(filename.c_str());
1835 } else {
1836 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
1837 closeDeviceByPathLocked(filename.c_str());
1838 }
Prabir Pradhan2b281812019-08-29 14:12:42 -07001839 } else if (event->wd == mVideoWd) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001840 if (isV4lTouchNode(event->name)) {
1841 std::string filename = StringPrintf("%s/%s", VIDEO_DEVICE_PATH, event->name);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001842 if (event->mask & IN_CREATE) {
1843 openVideoDeviceLocked(filename);
1844 } else {
1845 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
1846 closeVideoDeviceByPathLocked(filename);
1847 }
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001848 }
Prabir Pradhan2b281812019-08-29 14:12:42 -07001849 } else {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001850 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event->wd);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001851 }
1852 }
1853 event_size = sizeof(*event) + event->len;
1854 res -= event_size;
1855 event_pos += event_size;
1856 }
1857 return 0;
1858}
1859
Prabir Pradhan2b281812019-08-29 14:12:42 -07001860status_t EventHub::scanDirLocked(const char* dirname) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001861 char devname[PATH_MAX];
Prabir Pradhan2b281812019-08-29 14:12:42 -07001862 char* filename;
1863 DIR* dir;
1864 struct dirent* de;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001865 dir = opendir(dirname);
Prabir Pradhan2b281812019-08-29 14:12:42 -07001866 if (dir == nullptr) return -1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001867 strcpy(devname, dirname);
1868 filename = devname + strlen(devname);
1869 *filename++ = '/';
Prabir Pradhan2b281812019-08-29 14:12:42 -07001870 while ((de = readdir(dir))) {
1871 if (de->d_name[0] == '.' &&
1872 (de->d_name[1] == '\0' || (de->d_name[1] == '.' && de->d_name[2] == '\0')))
Michael Wrightd02c5b62014-02-10 15:10:22 -08001873 continue;
1874 strcpy(filename, de->d_name);
1875 openDeviceLocked(devname);
1876 }
1877 closedir(dir);
1878 return 0;
1879}
1880
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001881/**
1882 * Look for all dirname/v4l-touch* devices, and open them.
1883 */
Prabir Pradhan2b281812019-08-29 14:12:42 -07001884status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001885 DIR* dir;
1886 struct dirent* de;
1887 dir = opendir(dirname.c_str());
Prabir Pradhan2b281812019-08-29 14:12:42 -07001888 if (!dir) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001889 ALOGE("Could not open video directory %s", dirname.c_str());
1890 return BAD_VALUE;
1891 }
1892
Prabir Pradhan2b281812019-08-29 14:12:42 -07001893 while ((de = readdir(dir))) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001894 const char* name = de->d_name;
1895 if (isV4lTouchNode(name)) {
1896 ALOGI("Found touch video device %s", name);
1897 openVideoDeviceLocked(dirname + "/" + name);
1898 }
1899 }
1900 closedir(dir);
1901 return OK;
1902}
1903
Michael Wrightd02c5b62014-02-10 15:10:22 -08001904void EventHub::requestReopenDevices() {
1905 ALOGV("requestReopenDevices() called");
1906
1907 AutoMutex _l(mLock);
1908 mNeedToReopenDevices = true;
1909}
1910
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001911void EventHub::dump(std::string& dump) {
1912 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001913
1914 { // acquire lock
1915 AutoMutex _l(mLock);
1916
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001917 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001918
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001919 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001920
1921 for (size_t i = 0; i < mDevices.size(); i++) {
1922 const Device* device = mDevices.valueAt(i);
1923 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001924 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhan2b281812019-08-29 14:12:42 -07001925 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001926 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001927 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhan2b281812019-08-29 14:12:42 -07001928 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001929 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001930 dump += StringPrintf(INDENT3 "Classes: 0x%08x\n", device->classes);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001931 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001932 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001933 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
1934 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001935 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001936 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001937 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhan2b281812019-08-29 14:12:42 -07001938 "product=0x%04x, version=0x%04x\n",
1939 device->identifier.bus, device->identifier.vendor,
1940 device->identifier.product, device->identifier.version);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001941 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhan2b281812019-08-29 14:12:42 -07001942 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001943 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhan2b281812019-08-29 14:12:42 -07001944 device->keyMap.keyCharacterMapFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001945 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhan2b281812019-08-29 14:12:42 -07001946 device->configurationFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001947 dump += StringPrintf(INDENT3 "HaveKeyboardLayoutOverlay: %s\n",
Prabir Pradhan2b281812019-08-29 14:12:42 -07001948 toString(device->overlayKeyMap != nullptr));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001949 dump += INDENT3 "VideoDevice: ";
1950 if (device->videoDevice) {
1951 dump += device->videoDevice->dump() + "\n";
1952 } else {
1953 dump += "<none>\n";
1954 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001955 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001956
1957 dump += INDENT "Unattached video devices:\n";
1958 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
1959 dump += INDENT2 + videoDevice->dump() + "\n";
1960 }
1961 if (mUnattachedVideoDevices.empty()) {
1962 dump += INDENT2 "<none>\n";
1963 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001964 } // release lock
1965}
1966
1967void EventHub::monitor() {
1968 // Acquire and release the lock to ensure that the event hub has not deadlocked.
1969 mLock.lock();
1970 mLock.unlock();
1971}
1972
Michael Wrightd02c5b62014-02-10 15:10:22 -08001973}; // namespace android