blob: 99fe0f5d5514032c562199ee095bfda7af16837d [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
42#include <cutils/properties.h>
Dan Albert677d87e2014-06-16 17:31:28 -070043#include <openssl/sha.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080044#include <utils/Log.h>
45#include <utils/Timers.h>
46#include <utils/threads.h>
47#include <utils/Errors.h>
48
Michael Wrightd02c5b62014-02-10 15:10:22 -080049#include <input/KeyLayoutMap.h>
50#include <input/KeyCharacterMap.h>
51#include <input/VirtualKeyMap.h>
52
Michael Wrightd02c5b62014-02-10 15:10:22 -080053/* this macro is used to tell if "bit" is set in "array"
54 * it selects a byte from the array, and does a boolean AND
55 * operation with a byte that only has the relevant bit set.
56 * eg. to check for the 12th bit, we do (array[1] & 1<<4)
57 */
Chih-Hung Hsieh4a186d42016-05-20 11:33:26 -070058#define test_bit(bit, array) ((array)[(bit)/8] & (1<<((bit)%8)))
Michael Wrightd02c5b62014-02-10 15:10:22 -080059
60/* this macro computes the number of bytes needed to represent a bit array of the specified size */
Chih-Hung Hsieh4a186d42016-05-20 11:33:26 -070061#define sizeof_bit_array(bits) (((bits) + 7) / 8)
Michael Wrightd02c5b62014-02-10 15:10:22 -080062
63#define INDENT " "
64#define INDENT2 " "
65#define INDENT3 " "
66
67namespace android {
68
69static const char *WAKE_LOCK_ID = "KeyEvents";
70static const char *DEVICE_PATH = "/dev/input";
71
Michael Wrightd02c5b62014-02-10 15:10:22 -080072static inline const char* toString(bool value) {
73 return value ? "true" : "false";
74}
75
76static String8 sha1(const String8& in) {
Dan Albert677d87e2014-06-16 17:31:28 -070077 SHA_CTX ctx;
78 SHA1_Init(&ctx);
79 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.string()), in.size());
80 u_char digest[SHA_DIGEST_LENGTH];
81 SHA1_Final(digest, &ctx);
Michael Wrightd02c5b62014-02-10 15:10:22 -080082
83 String8 out;
Dan Albert677d87e2014-06-16 17:31:28 -070084 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -080085 out.appendFormat("%02x", digest[i]);
86 }
87 return out;
88}
89
90static void getLinuxRelease(int* major, int* minor) {
91 struct utsname info;
92 if (uname(&info) || sscanf(info.release, "%d.%d", major, minor) <= 0) {
93 *major = 0, *minor = 0;
94 ALOGE("Could not get linux version: %s", strerror(errno));
95 }
96}
97
98// --- Global Functions ---
99
100uint32_t getAbsAxisUsage(int32_t axis, uint32_t deviceClasses) {
101 // Touch devices get dibs on touch-related axes.
102 if (deviceClasses & INPUT_DEVICE_CLASS_TOUCH) {
103 switch (axis) {
104 case ABS_X:
105 case ABS_Y:
106 case ABS_PRESSURE:
107 case ABS_TOOL_WIDTH:
108 case ABS_DISTANCE:
109 case ABS_TILT_X:
110 case ABS_TILT_Y:
111 case ABS_MT_SLOT:
112 case ABS_MT_TOUCH_MAJOR:
113 case ABS_MT_TOUCH_MINOR:
114 case ABS_MT_WIDTH_MAJOR:
115 case ABS_MT_WIDTH_MINOR:
116 case ABS_MT_ORIENTATION:
117 case ABS_MT_POSITION_X:
118 case ABS_MT_POSITION_Y:
119 case ABS_MT_TOOL_TYPE:
120 case ABS_MT_BLOB_ID:
121 case ABS_MT_TRACKING_ID:
122 case ABS_MT_PRESSURE:
123 case ABS_MT_DISTANCE:
124 return INPUT_DEVICE_CLASS_TOUCH;
125 }
126 }
127
Michael Wright842500e2015-03-13 17:32:02 -0700128 // External stylus gets the pressure axis
129 if (deviceClasses & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
130 if (axis == ABS_PRESSURE) {
131 return INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
132 }
133 }
134
Michael Wrightd02c5b62014-02-10 15:10:22 -0800135 // Joystick devices get the rest.
136 return deviceClasses & INPUT_DEVICE_CLASS_JOYSTICK;
137}
138
139// --- EventHub::Device ---
140
141EventHub::Device::Device(int fd, int32_t id, const String8& path,
142 const InputDeviceIdentifier& identifier) :
143 next(NULL),
144 fd(fd), id(id), path(path), identifier(identifier),
145 classes(0), configuration(NULL), virtualKeyMap(NULL),
146 ffEffectPlaying(false), ffEffectId(-1), controllerNumber(0),
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700147 timestampOverrideSec(0), timestampOverrideUsec(0), enabled(true),
148 isVirtual(fd < 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800149 memset(keyBitmask, 0, sizeof(keyBitmask));
150 memset(absBitmask, 0, sizeof(absBitmask));
151 memset(relBitmask, 0, sizeof(relBitmask));
152 memset(swBitmask, 0, sizeof(swBitmask));
153 memset(ledBitmask, 0, sizeof(ledBitmask));
154 memset(ffBitmask, 0, sizeof(ffBitmask));
155 memset(propBitmask, 0, sizeof(propBitmask));
156}
157
158EventHub::Device::~Device() {
159 close();
160 delete configuration;
161 delete virtualKeyMap;
162}
163
164void EventHub::Device::close() {
165 if (fd >= 0) {
166 ::close(fd);
167 fd = -1;
168 }
169}
170
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700171status_t EventHub::Device::enable() {
172 fd = open(path, O_RDWR | O_CLOEXEC | O_NONBLOCK);
173 if(fd < 0) {
174 ALOGE("could not open %s, %s\n", path.string(), strerror(errno));
175 return -errno;
176 }
177 enabled = true;
178 return OK;
179}
180
181status_t EventHub::Device::disable() {
182 close();
183 enabled = false;
184 return OK;
185}
186
187bool EventHub::Device::hasValidFd() {
188 return !isVirtual && enabled;
189}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800190
191// --- EventHub ---
192
193const uint32_t EventHub::EPOLL_ID_INOTIFY;
194const uint32_t EventHub::EPOLL_ID_WAKE;
195const int EventHub::EPOLL_SIZE_HINT;
196const int EventHub::EPOLL_MAX_EVENTS;
197
198EventHub::EventHub(void) :
199 mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD), mNextDeviceId(1), mControllerNumbers(),
200 mOpeningDevices(0), mClosingDevices(0),
201 mNeedToSendFinishedDeviceScan(false),
202 mNeedToReopenDevices(false), mNeedToScanDevices(true),
203 mPendingEventCount(0), mPendingEventIndex(0), mPendingINotify(false) {
204 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
205
206 mEpollFd = epoll_create(EPOLL_SIZE_HINT);
207 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance. errno=%d", errno);
208
209 mINotifyFd = inotify_init();
210 int result = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
211 LOG_ALWAYS_FATAL_IF(result < 0, "Could not register INotify for %s. errno=%d",
212 DEVICE_PATH, errno);
213
214 struct epoll_event eventItem;
215 memset(&eventItem, 0, sizeof(eventItem));
216 eventItem.events = EPOLLIN;
217 eventItem.data.u32 = EPOLL_ID_INOTIFY;
218 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
219 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
220
221 int wakeFds[2];
222 result = pipe(wakeFds);
223 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
224
225 mWakeReadPipeFd = wakeFds[0];
226 mWakeWritePipeFd = wakeFds[1];
227
228 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
229 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
230 errno);
231
232 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
233 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
234 errno);
235
236 eventItem.data.u32 = EPOLL_ID_WAKE;
237 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
238 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
239 errno);
240
241 int major, minor;
242 getLinuxRelease(&major, &minor);
243 // EPOLLWAKEUP was introduced in kernel 3.5
244 mUsingEpollWakeup = major > 3 || (major == 3 && minor >= 5);
245}
246
247EventHub::~EventHub(void) {
248 closeAllDevicesLocked();
249
250 while (mClosingDevices) {
251 Device* device = mClosingDevices;
252 mClosingDevices = device->next;
253 delete device;
254 }
255
256 ::close(mEpollFd);
257 ::close(mINotifyFd);
258 ::close(mWakeReadPipeFd);
259 ::close(mWakeWritePipeFd);
260
261 release_wake_lock(WAKE_LOCK_ID);
262}
263
264InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
265 AutoMutex _l(mLock);
266 Device* device = getDeviceLocked(deviceId);
267 if (device == NULL) return InputDeviceIdentifier();
268 return device->identifier;
269}
270
271uint32_t EventHub::getDeviceClasses(int32_t deviceId) const {
272 AutoMutex _l(mLock);
273 Device* device = getDeviceLocked(deviceId);
274 if (device == NULL) return 0;
275 return device->classes;
276}
277
278int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
279 AutoMutex _l(mLock);
280 Device* device = getDeviceLocked(deviceId);
281 if (device == NULL) return 0;
282 return device->controllerNumber;
283}
284
285void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
286 AutoMutex _l(mLock);
287 Device* device = getDeviceLocked(deviceId);
288 if (device && device->configuration) {
289 *outConfiguration = *device->configuration;
290 } else {
291 outConfiguration->clear();
292 }
293}
294
295status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
296 RawAbsoluteAxisInfo* outAxisInfo) const {
297 outAxisInfo->clear();
298
299 if (axis >= 0 && axis <= ABS_MAX) {
300 AutoMutex _l(mLock);
301
302 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700303 if (device && device->hasValidFd() && test_bit(axis, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800304 struct input_absinfo info;
305 if(ioctl(device->fd, EVIOCGABS(axis), &info)) {
306 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d",
307 axis, device->identifier.name.string(), device->fd, errno);
308 return -errno;
309 }
310
311 if (info.minimum != info.maximum) {
312 outAxisInfo->valid = true;
313 outAxisInfo->minValue = info.minimum;
314 outAxisInfo->maxValue = info.maximum;
315 outAxisInfo->flat = info.flat;
316 outAxisInfo->fuzz = info.fuzz;
317 outAxisInfo->resolution = info.resolution;
318 }
319 return OK;
320 }
321 }
322 return -1;
323}
324
325bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
326 if (axis >= 0 && axis <= REL_MAX) {
327 AutoMutex _l(mLock);
328
329 Device* device = getDeviceLocked(deviceId);
330 if (device) {
331 return test_bit(axis, device->relBitmask);
332 }
333 }
334 return false;
335}
336
337bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
338 if (property >= 0 && property <= INPUT_PROP_MAX) {
339 AutoMutex _l(mLock);
340
341 Device* device = getDeviceLocked(deviceId);
342 if (device) {
343 return test_bit(property, device->propBitmask);
344 }
345 }
346 return false;
347}
348
349int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
350 if (scanCode >= 0 && scanCode <= KEY_MAX) {
351 AutoMutex _l(mLock);
352
353 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700354 if (device && device->hasValidFd() && test_bit(scanCode, device->keyBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800355 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
356 memset(keyState, 0, sizeof(keyState));
357 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
358 return test_bit(scanCode, keyState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
359 }
360 }
361 }
362 return AKEY_STATE_UNKNOWN;
363}
364
365int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
366 AutoMutex _l(mLock);
367
368 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700369 if (device && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800370 Vector<int32_t> scanCodes;
371 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode, &scanCodes);
372 if (scanCodes.size() != 0) {
373 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
374 memset(keyState, 0, sizeof(keyState));
375 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
376 for (size_t i = 0; i < scanCodes.size(); i++) {
377 int32_t sc = scanCodes.itemAt(i);
378 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, keyState)) {
379 return AKEY_STATE_DOWN;
380 }
381 }
382 return AKEY_STATE_UP;
383 }
384 }
385 }
386 return AKEY_STATE_UNKNOWN;
387}
388
389int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
390 if (sw >= 0 && sw <= SW_MAX) {
391 AutoMutex _l(mLock);
392
393 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700394 if (device && device->hasValidFd() && test_bit(sw, device->swBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800395 uint8_t swState[sizeof_bit_array(SW_MAX + 1)];
396 memset(swState, 0, sizeof(swState));
397 if (ioctl(device->fd, EVIOCGSW(sizeof(swState)), swState) >= 0) {
398 return test_bit(sw, swState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
399 }
400 }
401 }
402 return AKEY_STATE_UNKNOWN;
403}
404
405status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
406 *outValue = 0;
407
408 if (axis >= 0 && axis <= ABS_MAX) {
409 AutoMutex _l(mLock);
410
411 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700412 if (device && device->hasValidFd() && test_bit(axis, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800413 struct input_absinfo info;
414 if(ioctl(device->fd, EVIOCGABS(axis), &info)) {
415 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d",
416 axis, device->identifier.name.string(), device->fd, errno);
417 return -errno;
418 }
419
420 *outValue = info.value;
421 return OK;
422 }
423 }
424 return -1;
425}
426
427bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes,
428 const int32_t* keyCodes, uint8_t* outFlags) const {
429 AutoMutex _l(mLock);
430
431 Device* device = getDeviceLocked(deviceId);
432 if (device && device->keyMap.haveKeyLayout()) {
433 Vector<int32_t> scanCodes;
434 for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) {
435 scanCodes.clear();
436
437 status_t err = device->keyMap.keyLayoutMap->findScanCodesForKey(
438 keyCodes[codeIndex], &scanCodes);
439 if (! err) {
440 // check the possible scan codes identified by the layout map against the
441 // map of codes actually emitted by the driver
442 for (size_t sc = 0; sc < scanCodes.size(); sc++) {
443 if (test_bit(scanCodes[sc], device->keyBitmask)) {
444 outFlags[codeIndex] = 1;
445 break;
446 }
447 }
448 }
449 }
450 return true;
451 }
452 return false;
453}
454
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700455status_t EventHub::mapKey(int32_t deviceId,
456 int32_t scanCode, int32_t usageCode, int32_t metaState,
457 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800458 AutoMutex _l(mLock);
459 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700460 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800461
462 if (device) {
463 // Check the key character map first.
464 sp<KeyCharacterMap> kcm = device->getKeyCharacterMap();
465 if (kcm != NULL) {
466 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
467 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700468 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800469 }
470 }
471
472 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700473 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800474 if (!device->keyMap.keyLayoutMap->mapKey(
475 scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700476 status = NO_ERROR;
477 }
478 }
479
480 if (status == NO_ERROR) {
481 if (kcm != NULL) {
482 kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState);
483 } else {
484 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800485 }
486 }
487 }
488
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700489 if (status != NO_ERROR) {
490 *outKeycode = 0;
491 *outFlags = 0;
492 *outMetaState = metaState;
493 }
494
495 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800496}
497
498status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
499 AutoMutex _l(mLock);
500 Device* device = getDeviceLocked(deviceId);
501
502 if (device && device->keyMap.haveKeyLayout()) {
503 status_t err = device->keyMap.keyLayoutMap->mapAxis(scanCode, outAxisInfo);
504 if (err == NO_ERROR) {
505 return NO_ERROR;
506 }
507 }
508
509 return NAME_NOT_FOUND;
510}
511
512void EventHub::setExcludedDevices(const Vector<String8>& devices) {
513 AutoMutex _l(mLock);
514
515 mExcludedDevices = devices;
516}
517
518bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
519 AutoMutex _l(mLock);
520 Device* device = getDeviceLocked(deviceId);
521 if (device && scanCode >= 0 && scanCode <= KEY_MAX) {
522 if (test_bit(scanCode, device->keyBitmask)) {
523 return true;
524 }
525 }
526 return false;
527}
528
529bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
530 AutoMutex _l(mLock);
531 Device* device = getDeviceLocked(deviceId);
532 int32_t sc;
533 if (device && mapLed(device, led, &sc) == NO_ERROR) {
534 if (test_bit(sc, device->ledBitmask)) {
535 return true;
536 }
537 }
538 return false;
539}
540
541void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
542 AutoMutex _l(mLock);
543 Device* device = getDeviceLocked(deviceId);
544 setLedStateLocked(device, led, on);
545}
546
547void EventHub::setLedStateLocked(Device* device, int32_t led, bool on) {
548 int32_t sc;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700549 if (device && device->hasValidFd() && mapLed(device, led, &sc) != NAME_NOT_FOUND) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800550 struct input_event ev;
551 ev.time.tv_sec = 0;
552 ev.time.tv_usec = 0;
553 ev.type = EV_LED;
554 ev.code = sc;
555 ev.value = on ? 1 : 0;
556
557 ssize_t nWrite;
558 do {
559 nWrite = write(device->fd, &ev, sizeof(struct input_event));
560 } while (nWrite == -1 && errno == EINTR);
561 }
562}
563
564void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
565 Vector<VirtualKeyDefinition>& outVirtualKeys) const {
566 outVirtualKeys.clear();
567
568 AutoMutex _l(mLock);
569 Device* device = getDeviceLocked(deviceId);
570 if (device && device->virtualKeyMap) {
571 outVirtualKeys.appendVector(device->virtualKeyMap->getVirtualKeys());
572 }
573}
574
575sp<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
576 AutoMutex _l(mLock);
577 Device* device = getDeviceLocked(deviceId);
578 if (device) {
579 return device->getKeyCharacterMap();
580 }
581 return NULL;
582}
583
584bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId,
585 const sp<KeyCharacterMap>& map) {
586 AutoMutex _l(mLock);
587 Device* device = getDeviceLocked(deviceId);
588 if (device) {
589 if (map != device->overlayKeyMap) {
590 device->overlayKeyMap = map;
591 device->combinedKeyMap = KeyCharacterMap::combine(
592 device->keyMap.keyCharacterMap, map);
593 return true;
594 }
595 }
596 return false;
597}
598
599static String8 generateDescriptor(InputDeviceIdentifier& identifier) {
600 String8 rawDescriptor;
601 rawDescriptor.appendFormat(":%04x:%04x:", identifier.vendor,
602 identifier.product);
603 // TODO add handling for USB devices to not uniqueify kbs that show up twice
604 if (!identifier.uniqueId.isEmpty()) {
605 rawDescriptor.append("uniqueId:");
606 rawDescriptor.append(identifier.uniqueId);
607 } else if (identifier.nonce != 0) {
608 rawDescriptor.appendFormat("nonce:%04x", identifier.nonce);
609 }
610
611 if (identifier.vendor == 0 && identifier.product == 0) {
612 // If we don't know the vendor and product id, then the device is probably
613 // built-in so we need to rely on other information to uniquely identify
614 // the input device. Usually we try to avoid relying on the device name or
615 // location but for built-in input device, they are unlikely to ever change.
616 if (!identifier.name.isEmpty()) {
617 rawDescriptor.append("name:");
618 rawDescriptor.append(identifier.name);
619 } else if (!identifier.location.isEmpty()) {
620 rawDescriptor.append("location:");
621 rawDescriptor.append(identifier.location);
622 }
623 }
624 identifier.descriptor = sha1(rawDescriptor);
625 return rawDescriptor;
626}
627
628void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
629 // Compute a device descriptor that uniquely identifies the device.
630 // The descriptor is assumed to be a stable identifier. Its value should not
631 // change between reboots, reconnections, firmware updates or new releases
632 // of Android. In practice we sometimes get devices that cannot be uniquely
633 // identified. In this case we enforce uniqueness between connected devices.
634 // Ideally, we also want the descriptor to be short and relatively opaque.
635
636 identifier.nonce = 0;
637 String8 rawDescriptor = generateDescriptor(identifier);
638 if (identifier.uniqueId.isEmpty()) {
639 // If it didn't have a unique id check for conflicts and enforce
640 // uniqueness if necessary.
641 while(getDeviceByDescriptorLocked(identifier.descriptor) != NULL) {
642 identifier.nonce++;
643 rawDescriptor = generateDescriptor(identifier);
644 }
645 }
646 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.string(),
647 identifier.descriptor.string());
648}
649
650void EventHub::vibrate(int32_t deviceId, nsecs_t duration) {
651 AutoMutex _l(mLock);
652 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700653 if (device && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800654 ff_effect effect;
655 memset(&effect, 0, sizeof(effect));
656 effect.type = FF_RUMBLE;
657 effect.id = device->ffEffectId;
658 effect.u.rumble.strong_magnitude = 0xc000;
659 effect.u.rumble.weak_magnitude = 0xc000;
660 effect.replay.length = (duration + 999999LL) / 1000000LL;
661 effect.replay.delay = 0;
662 if (ioctl(device->fd, EVIOCSFF, &effect)) {
663 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
664 device->identifier.name.string(), errno);
665 return;
666 }
667 device->ffEffectId = effect.id;
668
669 struct input_event ev;
670 ev.time.tv_sec = 0;
671 ev.time.tv_usec = 0;
672 ev.type = EV_FF;
673 ev.code = device->ffEffectId;
674 ev.value = 1;
675 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
676 ALOGW("Could not start force feedback effect on device %s due to error %d.",
677 device->identifier.name.string(), errno);
678 return;
679 }
680 device->ffEffectPlaying = true;
681 }
682}
683
684void EventHub::cancelVibrate(int32_t deviceId) {
685 AutoMutex _l(mLock);
686 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700687 if (device && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800688 if (device->ffEffectPlaying) {
689 device->ffEffectPlaying = false;
690
691 struct input_event ev;
692 ev.time.tv_sec = 0;
693 ev.time.tv_usec = 0;
694 ev.type = EV_FF;
695 ev.code = device->ffEffectId;
696 ev.value = 0;
697 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
698 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
699 device->identifier.name.string(), errno);
700 return;
701 }
702 }
703 }
704}
705
706EventHub::Device* EventHub::getDeviceByDescriptorLocked(String8& descriptor) const {
707 size_t size = mDevices.size();
708 for (size_t i = 0; i < size; i++) {
709 Device* device = mDevices.valueAt(i);
710 if (descriptor.compare(device->identifier.descriptor) == 0) {
711 return device;
712 }
713 }
714 return NULL;
715}
716
717EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
718 if (deviceId == BUILT_IN_KEYBOARD_ID) {
719 deviceId = mBuiltInKeyboardId;
720 }
721 ssize_t index = mDevices.indexOfKey(deviceId);
722 return index >= 0 ? mDevices.valueAt(index) : NULL;
723}
724
725EventHub::Device* EventHub::getDeviceByPathLocked(const char* devicePath) const {
726 for (size_t i = 0; i < mDevices.size(); i++) {
727 Device* device = mDevices.valueAt(i);
728 if (device->path == devicePath) {
729 return device;
730 }
731 }
732 return NULL;
733}
734
735size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
736 ALOG_ASSERT(bufferSize >= 1);
737
738 AutoMutex _l(mLock);
739
740 struct input_event readBuffer[bufferSize];
741
742 RawEvent* event = buffer;
743 size_t capacity = bufferSize;
744 bool awoken = false;
745 for (;;) {
746 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
747
748 // Reopen input devices if needed.
749 if (mNeedToReopenDevices) {
750 mNeedToReopenDevices = false;
751
752 ALOGI("Reopening all input devices due to a configuration change.");
753
754 closeAllDevicesLocked();
755 mNeedToScanDevices = true;
756 break; // return to the caller before we actually rescan
757 }
758
759 // Report any devices that had last been added/removed.
760 while (mClosingDevices) {
761 Device* device = mClosingDevices;
762 ALOGV("Reporting device closed: id=%d, name=%s\n",
763 device->id, device->path.string());
764 mClosingDevices = device->next;
765 event->when = now;
766 event->deviceId = device->id == mBuiltInKeyboardId ? BUILT_IN_KEYBOARD_ID : device->id;
767 event->type = DEVICE_REMOVED;
768 event += 1;
769 delete device;
770 mNeedToSendFinishedDeviceScan = true;
771 if (--capacity == 0) {
772 break;
773 }
774 }
775
776 if (mNeedToScanDevices) {
777 mNeedToScanDevices = false;
778 scanDevicesLocked();
779 mNeedToSendFinishedDeviceScan = true;
780 }
781
782 while (mOpeningDevices != NULL) {
783 Device* device = mOpeningDevices;
784 ALOGV("Reporting device opened: id=%d, name=%s\n",
785 device->id, device->path.string());
786 mOpeningDevices = device->next;
787 event->when = now;
788 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
789 event->type = DEVICE_ADDED;
790 event += 1;
791 mNeedToSendFinishedDeviceScan = true;
792 if (--capacity == 0) {
793 break;
794 }
795 }
796
797 if (mNeedToSendFinishedDeviceScan) {
798 mNeedToSendFinishedDeviceScan = false;
799 event->when = now;
800 event->type = FINISHED_DEVICE_SCAN;
801 event += 1;
802 if (--capacity == 0) {
803 break;
804 }
805 }
806
807 // Grab the next input event.
808 bool deviceChanged = false;
809 while (mPendingEventIndex < mPendingEventCount) {
810 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
811 if (eventItem.data.u32 == EPOLL_ID_INOTIFY) {
812 if (eventItem.events & EPOLLIN) {
813 mPendingINotify = true;
814 } else {
815 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
816 }
817 continue;
818 }
819
820 if (eventItem.data.u32 == EPOLL_ID_WAKE) {
821 if (eventItem.events & EPOLLIN) {
822 ALOGV("awoken after wake()");
823 awoken = true;
824 char buffer[16];
825 ssize_t nRead;
826 do {
827 nRead = read(mWakeReadPipeFd, buffer, sizeof(buffer));
828 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(buffer));
829 } else {
830 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
831 eventItem.events);
832 }
833 continue;
834 }
835
836 ssize_t deviceIndex = mDevices.indexOfKey(eventItem.data.u32);
837 if (deviceIndex < 0) {
838 ALOGW("Received unexpected epoll event 0x%08x for unknown device id %d.",
839 eventItem.events, eventItem.data.u32);
840 continue;
841 }
842
843 Device* device = mDevices.valueAt(deviceIndex);
844 if (eventItem.events & EPOLLIN) {
845 int32_t readSize = read(device->fd, readBuffer,
846 sizeof(struct input_event) * capacity);
847 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
848 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -0700849 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
850 " bufferSize: %zu capacity: %zu errno: %d)\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800851 device->fd, readSize, bufferSize, capacity, errno);
852 deviceChanged = true;
853 closeDeviceLocked(device);
854 } else if (readSize < 0) {
855 if (errno != EAGAIN && errno != EINTR) {
856 ALOGW("could not get event (errno=%d)", errno);
857 }
858 } else if ((readSize % sizeof(struct input_event)) != 0) {
859 ALOGE("could not get event (wrong size: %d)", readSize);
860 } else {
861 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
862
863 size_t count = size_t(readSize) / sizeof(struct input_event);
864 for (size_t i = 0; i < count; i++) {
865 struct input_event& iev = readBuffer[i];
866 ALOGV("%s got: time=%d.%06d, type=%d, code=%d, value=%d",
867 device->path.string(),
868 (int) iev.time.tv_sec, (int) iev.time.tv_usec,
869 iev.type, iev.code, iev.value);
870
871 // Some input devices may have a better concept of the time
872 // when an input event was actually generated than the kernel
873 // which simply timestamps all events on entry to evdev.
874 // This is a custom Android extension of the input protocol
875 // mainly intended for use with uinput based device drivers.
876 if (iev.type == EV_MSC) {
877 if (iev.code == MSC_ANDROID_TIME_SEC) {
878 device->timestampOverrideSec = iev.value;
879 continue;
880 } else if (iev.code == MSC_ANDROID_TIME_USEC) {
881 device->timestampOverrideUsec = iev.value;
882 continue;
883 }
884 }
885 if (device->timestampOverrideSec || device->timestampOverrideUsec) {
886 iev.time.tv_sec = device->timestampOverrideSec;
887 iev.time.tv_usec = device->timestampOverrideUsec;
888 if (iev.type == EV_SYN && iev.code == SYN_REPORT) {
889 device->timestampOverrideSec = 0;
890 device->timestampOverrideUsec = 0;
891 }
892 ALOGV("applied override time %d.%06d",
893 int(iev.time.tv_sec), int(iev.time.tv_usec));
894 }
895
Michael Wrightd02c5b62014-02-10 15:10:22 -0800896 // Use the time specified in the event instead of the current time
897 // so that downstream code can get more accurate estimates of
898 // event dispatch latency from the time the event is enqueued onto
899 // the evdev client buffer.
900 //
901 // The event's timestamp fortuitously uses the same monotonic clock
902 // time base as the rest of Android. The kernel event device driver
903 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
904 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
905 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
906 // system call that also queries ktime_get_ts().
907 event->when = nsecs_t(iev.time.tv_sec) * 1000000000LL
908 + nsecs_t(iev.time.tv_usec) * 1000LL;
Mark Salyzyn5aa26b22014-06-10 13:07:44 -0700909 ALOGV("event time %" PRId64 ", now %" PRId64, event->when, now);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800910
911 // Bug 7291243: Add a guard in case the kernel generates timestamps
912 // that appear to be far into the future because they were generated
913 // using the wrong clock source.
914 //
915 // This can happen because when the input device is initially opened
916 // it has a default clock source of CLOCK_REALTIME. Any input events
917 // enqueued right after the device is opened will have timestamps
918 // generated using CLOCK_REALTIME. We later set the clock source
919 // to CLOCK_MONOTONIC but it is already too late.
920 //
921 // Invalid input event timestamps can result in ANRs, crashes and
922 // and other issues that are hard to track down. We must not let them
923 // propagate through the system.
924 //
925 // Log a warning so that we notice the problem and recover gracefully.
926 if (event->when >= now + 10 * 1000000000LL) {
927 // Double-check. Time may have moved on.
928 nsecs_t time = systemTime(SYSTEM_TIME_MONOTONIC);
929 if (event->when > time) {
930 ALOGW("An input event from %s has a timestamp that appears to "
931 "have been generated using the wrong clock source "
932 "(expected CLOCK_MONOTONIC): "
Mark Salyzyn5aa26b22014-06-10 13:07:44 -0700933 "event time %" PRId64 ", current time %" PRId64
934 ", call time %" PRId64 ". "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800935 "Using current time instead.",
936 device->path.string(), event->when, time, now);
937 event->when = time;
938 } else {
939 ALOGV("Event time is ok but failed the fast path and required "
940 "an extra call to systemTime: "
Mark Salyzyn5aa26b22014-06-10 13:07:44 -0700941 "event time %" PRId64 ", current time %" PRId64
942 ", call time %" PRId64 ".",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800943 event->when, time, now);
944 }
945 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800946 event->deviceId = deviceId;
947 event->type = iev.type;
948 event->code = iev.code;
949 event->value = iev.value;
950 event += 1;
951 capacity -= 1;
952 }
953 if (capacity == 0) {
954 // The result buffer is full. Reset the pending event index
955 // so we will try to read the device again on the next iteration.
956 mPendingEventIndex -= 1;
957 break;
958 }
959 }
960 } else if (eventItem.events & EPOLLHUP) {
961 ALOGI("Removing device %s due to epoll hang-up event.",
962 device->identifier.name.string());
963 deviceChanged = true;
964 closeDeviceLocked(device);
965 } else {
966 ALOGW("Received unexpected epoll event 0x%08x for device %s.",
967 eventItem.events, device->identifier.name.string());
968 }
969 }
970
971 // readNotify() will modify the list of devices so this must be done after
972 // processing all other events to ensure that we read all remaining events
973 // before closing the devices.
974 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
975 mPendingINotify = false;
976 readNotifyLocked();
977 deviceChanged = true;
978 }
979
980 // Report added or removed devices immediately.
981 if (deviceChanged) {
982 continue;
983 }
984
985 // Return now if we have collected any events or if we were explicitly awoken.
986 if (event != buffer || awoken) {
987 break;
988 }
989
990 // Poll for events. Mind the wake lock dance!
991 // We hold a wake lock at all times except during epoll_wait(). This works due to some
992 // subtle choreography. When a device driver has pending (unread) events, it acquires
993 // a kernel wake lock. However, once the last pending event has been read, the device
994 // driver will release the kernel wake lock. To prevent the system from going to sleep
995 // when this happens, the EventHub holds onto its own user wake lock while the client
996 // is processing events. Thus the system can only sleep if there are no events
997 // pending or currently being processed.
998 //
999 // The timeout is advisory only. If the device is asleep, it will not wake just to
1000 // service the timeout.
1001 mPendingEventIndex = 0;
1002
1003 mLock.unlock(); // release lock before poll, must be before release_wake_lock
1004 release_wake_lock(WAKE_LOCK_ID);
1005
1006 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1007
1008 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
1009 mLock.lock(); // reacquire lock after poll, must be after acquire_wake_lock
1010
1011 if (pollResult == 0) {
1012 // Timed out.
1013 mPendingEventCount = 0;
1014 break;
1015 }
1016
1017 if (pollResult < 0) {
1018 // An error occurred.
1019 mPendingEventCount = 0;
1020
1021 // Sleep after errors to avoid locking up the system.
1022 // Hopefully the error is transient.
1023 if (errno != EINTR) {
1024 ALOGW("poll failed (errno=%d)\n", errno);
1025 usleep(100000);
1026 }
1027 } else {
1028 // Some events occurred.
1029 mPendingEventCount = size_t(pollResult);
1030 }
1031 }
1032
1033 // All done, return the number of events we read.
1034 return event - buffer;
1035}
1036
1037void EventHub::wake() {
1038 ALOGV("wake() called");
1039
1040 ssize_t nWrite;
1041 do {
1042 nWrite = write(mWakeWritePipeFd, "W", 1);
1043 } while (nWrite == -1 && errno == EINTR);
1044
1045 if (nWrite != 1 && errno != EAGAIN) {
1046 ALOGW("Could not write wake signal, errno=%d", errno);
1047 }
1048}
1049
1050void EventHub::scanDevicesLocked() {
1051 status_t res = scanDirLocked(DEVICE_PATH);
1052 if(res < 0) {
1053 ALOGE("scan dir failed for %s\n", DEVICE_PATH);
1054 }
1055 if (mDevices.indexOfKey(VIRTUAL_KEYBOARD_ID) < 0) {
1056 createVirtualKeyboardLocked();
1057 }
1058}
1059
1060// ----------------------------------------------------------------------------
1061
1062static bool containsNonZeroByte(const uint8_t* array, uint32_t startIndex, uint32_t endIndex) {
1063 const uint8_t* end = array + endIndex;
1064 array += startIndex;
1065 while (array != end) {
1066 if (*(array++) != 0) {
1067 return true;
1068 }
1069 }
1070 return false;
1071}
1072
1073static const int32_t GAMEPAD_KEYCODES[] = {
1074 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C,
1075 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z,
1076 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1,
1077 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2,
1078 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR,
1079 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001080};
1081
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001082status_t EventHub::registerDeviceForEpollLocked(Device* device) {
1083 struct epoll_event eventItem;
1084 memset(&eventItem, 0, sizeof(eventItem));
1085 eventItem.events = EPOLLIN;
1086 if (mUsingEpollWakeup) {
1087 eventItem.events |= EPOLLWAKEUP;
1088 }
1089 eventItem.data.u32 = device->id;
1090 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, device->fd, &eventItem)) {
1091 ALOGE("Could not add device fd to epoll instance. errno=%d", errno);
1092 return -errno;
1093 }
1094 return OK;
1095}
1096
1097status_t EventHub::unregisterDeviceFromEpollLocked(Device* device) {
1098 if (device->hasValidFd()) {
1099 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, device->fd, NULL)) {
1100 ALOGW("Could not remove device fd from epoll instance. errno=%d", errno);
1101 return -errno;
1102 }
1103 }
1104 return OK;
1105}
1106
Michael Wrightd02c5b62014-02-10 15:10:22 -08001107status_t EventHub::openDeviceLocked(const char *devicePath) {
1108 char buffer[80];
1109
1110 ALOGV("Opening device: %s", devicePath);
1111
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001112 int fd = open(devicePath, O_RDWR | O_CLOEXEC | O_NONBLOCK);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001113 if(fd < 0) {
1114 ALOGE("could not open %s, %s\n", devicePath, strerror(errno));
1115 return -1;
1116 }
1117
1118 InputDeviceIdentifier identifier;
1119
1120 // Get device name.
1121 if(ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
1122 //fprintf(stderr, "could not get device name for %s, %s\n", devicePath, strerror(errno));
1123 } else {
1124 buffer[sizeof(buffer) - 1] = '\0';
1125 identifier.name.setTo(buffer);
1126 }
1127
1128 // Check to see if the device is on our excluded list
1129 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
1130 const String8& item = mExcludedDevices.itemAt(i);
1131 if (identifier.name == item) {
1132 ALOGI("ignoring event id %s driver %s\n", devicePath, item.string());
1133 close(fd);
1134 return -1;
1135 }
1136 }
1137
1138 // Get device driver version.
1139 int driverVersion;
1140 if(ioctl(fd, EVIOCGVERSION, &driverVersion)) {
1141 ALOGE("could not get driver version for %s, %s\n", devicePath, strerror(errno));
1142 close(fd);
1143 return -1;
1144 }
1145
1146 // Get device identifier.
1147 struct input_id inputId;
1148 if(ioctl(fd, EVIOCGID, &inputId)) {
1149 ALOGE("could not get device input id for %s, %s\n", devicePath, strerror(errno));
1150 close(fd);
1151 return -1;
1152 }
1153 identifier.bus = inputId.bustype;
1154 identifier.product = inputId.product;
1155 identifier.vendor = inputId.vendor;
1156 identifier.version = inputId.version;
1157
1158 // Get device physical location.
1159 if(ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
1160 //fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
1161 } else {
1162 buffer[sizeof(buffer) - 1] = '\0';
1163 identifier.location.setTo(buffer);
1164 }
1165
1166 // Get device unique id.
1167 if(ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
1168 //fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
1169 } else {
1170 buffer[sizeof(buffer) - 1] = '\0';
1171 identifier.uniqueId.setTo(buffer);
1172 }
1173
1174 // Fill in the descriptor.
1175 assignDescriptorLocked(identifier);
1176
Michael Wrightd02c5b62014-02-10 15:10:22 -08001177 // Allocate device. (The device object takes ownership of the fd at this point.)
1178 int32_t deviceId = mNextDeviceId++;
1179 Device* device = new Device(fd, deviceId, String8(devicePath), identifier);
1180
1181 ALOGV("add device %d: %s\n", deviceId, devicePath);
1182 ALOGV(" bus: %04x\n"
1183 " vendor %04x\n"
1184 " product %04x\n"
1185 " version %04x\n",
1186 identifier.bus, identifier.vendor, identifier.product, identifier.version);
1187 ALOGV(" name: \"%s\"\n", identifier.name.string());
1188 ALOGV(" location: \"%s\"\n", identifier.location.string());
1189 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.string());
1190 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.string());
1191 ALOGV(" driver: v%d.%d.%d\n",
1192 driverVersion >> 16, (driverVersion >> 8) & 0xff, driverVersion & 0xff);
1193
1194 // Load the configuration file for the device.
1195 loadConfigurationLocked(device);
1196
1197 // Figure out the kinds of events the device reports.
1198 ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(device->keyBitmask)), device->keyBitmask);
1199 ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(device->absBitmask)), device->absBitmask);
1200 ioctl(fd, EVIOCGBIT(EV_REL, sizeof(device->relBitmask)), device->relBitmask);
1201 ioctl(fd, EVIOCGBIT(EV_SW, sizeof(device->swBitmask)), device->swBitmask);
1202 ioctl(fd, EVIOCGBIT(EV_LED, sizeof(device->ledBitmask)), device->ledBitmask);
1203 ioctl(fd, EVIOCGBIT(EV_FF, sizeof(device->ffBitmask)), device->ffBitmask);
1204 ioctl(fd, EVIOCGPROP(sizeof(device->propBitmask)), device->propBitmask);
1205
1206 // See if this is a keyboard. Ignore everything in the button range except for
1207 // joystick and gamepad buttons which are handled like keyboards for the most part.
1208 bool haveKeyboardKeys = containsNonZeroByte(device->keyBitmask, 0, sizeof_bit_array(BTN_MISC))
1209 || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(KEY_OK),
1210 sizeof_bit_array(KEY_MAX + 1));
1211 bool haveGamepadButtons = containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_MISC),
1212 sizeof_bit_array(BTN_MOUSE))
1213 || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_JOYSTICK),
1214 sizeof_bit_array(BTN_DIGI));
1215 if (haveKeyboardKeys || haveGamepadButtons) {
1216 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1217 }
1218
1219 // See if this is a cursor device such as a trackball or mouse.
1220 if (test_bit(BTN_MOUSE, device->keyBitmask)
1221 && test_bit(REL_X, device->relBitmask)
1222 && test_bit(REL_Y, device->relBitmask)) {
1223 device->classes |= INPUT_DEVICE_CLASS_CURSOR;
1224 }
1225
Prashant Malani1941ff52015-08-11 18:29:28 -07001226 // See if this is a rotary encoder type device.
1227 String8 deviceType = String8();
1228 if (device->configuration &&
1229 device->configuration->tryGetProperty(String8("device.type"), deviceType)) {
1230 if (!deviceType.compare(String8("rotaryEncoder"))) {
1231 device->classes |= INPUT_DEVICE_CLASS_ROTARY_ENCODER;
1232 }
1233 }
1234
Michael Wrightd02c5b62014-02-10 15:10:22 -08001235 // See if this is a touch pad.
1236 // Is this a new modern multi-touch driver?
1237 if (test_bit(ABS_MT_POSITION_X, device->absBitmask)
1238 && test_bit(ABS_MT_POSITION_Y, device->absBitmask)) {
1239 // Some joysticks such as the PS3 controller report axes that conflict
1240 // with the ABS_MT range. Try to confirm that the device really is
1241 // a touch screen.
1242 if (test_bit(BTN_TOUCH, device->keyBitmask) || !haveGamepadButtons) {
1243 device->classes |= INPUT_DEVICE_CLASS_TOUCH | INPUT_DEVICE_CLASS_TOUCH_MT;
1244 }
1245 // Is this an old style single-touch driver?
1246 } else if (test_bit(BTN_TOUCH, device->keyBitmask)
1247 && test_bit(ABS_X, device->absBitmask)
1248 && test_bit(ABS_Y, device->absBitmask)) {
1249 device->classes |= INPUT_DEVICE_CLASS_TOUCH;
Michael Wright842500e2015-03-13 17:32:02 -07001250 // Is this a BT stylus?
1251 } else if ((test_bit(ABS_PRESSURE, device->absBitmask) ||
1252 test_bit(BTN_TOUCH, device->keyBitmask))
1253 && !test_bit(ABS_X, device->absBitmask)
1254 && !test_bit(ABS_Y, device->absBitmask)) {
1255 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
1256 // Keyboard will try to claim some of the buttons but we really want to reserve those so we
1257 // can fuse it with the touch screen data, so just take them back. Note this means an
1258 // external stylus cannot also be a keyboard device.
1259 device->classes &= ~INPUT_DEVICE_CLASS_KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001260 }
1261
1262 // See if this device is a joystick.
1263 // Assumes that joysticks always have gamepad buttons in order to distinguish them
1264 // from other devices such as accelerometers that also have absolute axes.
1265 if (haveGamepadButtons) {
1266 uint32_t assumedClasses = device->classes | INPUT_DEVICE_CLASS_JOYSTICK;
1267 for (int i = 0; i <= ABS_MAX; i++) {
1268 if (test_bit(i, device->absBitmask)
1269 && (getAbsAxisUsage(i, assumedClasses) & INPUT_DEVICE_CLASS_JOYSTICK)) {
1270 device->classes = assumedClasses;
1271 break;
1272 }
1273 }
1274 }
1275
1276 // Check whether this device has switches.
1277 for (int i = 0; i <= SW_MAX; i++) {
1278 if (test_bit(i, device->swBitmask)) {
1279 device->classes |= INPUT_DEVICE_CLASS_SWITCH;
1280 break;
1281 }
1282 }
1283
1284 // Check whether this device supports the vibrator.
1285 if (test_bit(FF_RUMBLE, device->ffBitmask)) {
1286 device->classes |= INPUT_DEVICE_CLASS_VIBRATOR;
1287 }
1288
1289 // Configure virtual keys.
1290 if ((device->classes & INPUT_DEVICE_CLASS_TOUCH)) {
1291 // Load the virtual keys for the touch screen, if any.
1292 // We do this now so that we can make sure to load the keymap if necessary.
1293 status_t status = loadVirtualKeyMapLocked(device);
1294 if (!status) {
1295 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1296 }
1297 }
1298
1299 // Load the key map.
1300 // We need to do this for joysticks too because the key layout may specify axes.
1301 status_t keyMapStatus = NAME_NOT_FOUND;
1302 if (device->classes & (INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_JOYSTICK)) {
1303 // Load the keymap for the device.
1304 keyMapStatus = loadKeyMapLocked(device);
1305 }
1306
1307 // Configure the keyboard, gamepad or virtual keyboard.
1308 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1309 // Register the keyboard as a built-in keyboard if it is eligible.
1310 if (!keyMapStatus
1311 && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD
1312 && isEligibleBuiltInKeyboard(device->identifier,
1313 device->configuration, &device->keyMap)) {
1314 mBuiltInKeyboardId = device->id;
1315 }
1316
1317 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
1318 if (hasKeycodeLocked(device, AKEYCODE_Q)) {
1319 device->classes |= INPUT_DEVICE_CLASS_ALPHAKEY;
1320 }
1321
1322 // See if this device has a DPAD.
1323 if (hasKeycodeLocked(device, AKEYCODE_DPAD_UP) &&
1324 hasKeycodeLocked(device, AKEYCODE_DPAD_DOWN) &&
1325 hasKeycodeLocked(device, AKEYCODE_DPAD_LEFT) &&
1326 hasKeycodeLocked(device, AKEYCODE_DPAD_RIGHT) &&
1327 hasKeycodeLocked(device, AKEYCODE_DPAD_CENTER)) {
1328 device->classes |= INPUT_DEVICE_CLASS_DPAD;
1329 }
1330
1331 // See if this device has a gamepad.
1332 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES)/sizeof(GAMEPAD_KEYCODES[0]); i++) {
1333 if (hasKeycodeLocked(device, GAMEPAD_KEYCODES[i])) {
1334 device->classes |= INPUT_DEVICE_CLASS_GAMEPAD;
1335 break;
1336 }
1337 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001338 }
1339
1340 // If the device isn't recognized as something we handle, don't monitor it.
1341 if (device->classes == 0) {
1342 ALOGV("Dropping device: id=%d, path='%s', name='%s'",
1343 deviceId, devicePath, device->identifier.name.string());
1344 delete device;
1345 return -1;
1346 }
1347
Tim Kilbourn063ff532015-04-08 10:26:18 -07001348 // Determine whether the device has a mic.
1349 if (deviceHasMicLocked(device)) {
1350 device->classes |= INPUT_DEVICE_CLASS_MIC;
1351 }
1352
Michael Wrightd02c5b62014-02-10 15:10:22 -08001353 // Determine whether the device is external or internal.
1354 if (isExternalDeviceLocked(device)) {
1355 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL;
1356 }
1357
Michael Wright42f2c6a2014-03-12 10:33:03 -07001358 if (device->classes & (INPUT_DEVICE_CLASS_JOYSTICK | INPUT_DEVICE_CLASS_DPAD)
1359 && device->classes & INPUT_DEVICE_CLASS_GAMEPAD) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001360 device->controllerNumber = getNextControllerNumberLocked(device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001361 setLedForControllerLocked(device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001362 }
1363
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001364
1365 if (registerDeviceForEpollLocked(device) != OK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001366 delete device;
1367 return -1;
1368 }
1369
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001370 configureFd(device);
1371
1372 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=0x%x, "
1373 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
1374 deviceId, fd, devicePath, device->identifier.name.string(),
1375 device->classes,
1376 device->configurationFile.string(),
1377 device->keyMap.keyLayoutFile.string(),
1378 device->keyMap.keyCharacterMapFile.string(),
1379 toString(mBuiltInKeyboardId == deviceId));
1380
1381 addDeviceLocked(device);
1382 return OK;
1383}
1384
1385void EventHub::configureFd(Device* device) {
1386 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
1387 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1388 // Disable kernel key repeat since we handle it ourselves
1389 unsigned int repeatRate[] = {0, 0};
1390 if (ioctl(device->fd, EVIOCSREP, repeatRate)) {
1391 ALOGW("Unable to disable kernel key repeat for %s: %s",
1392 device->path.string(), strerror(errno));
1393 }
1394 }
1395
Michael Wrightd02c5b62014-02-10 15:10:22 -08001396 String8 wakeMechanism("EPOLLWAKEUP");
1397 if (!mUsingEpollWakeup) {
1398#ifndef EVIOCSSUSPENDBLOCK
1399 // uapi headers don't include EVIOCSSUSPENDBLOCK, and future kernels
1400 // will use an epoll flag instead, so as long as we want to support
1401 // this feature, we need to be prepared to define the ioctl ourselves.
1402#define EVIOCSSUSPENDBLOCK _IOW('E', 0x91, int)
1403#endif
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001404 if (ioctl(device->fd, EVIOCSSUSPENDBLOCK, 1)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001405 wakeMechanism = "<none>";
1406 } else {
1407 wakeMechanism = "EVIOCSSUSPENDBLOCK";
1408 }
1409 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001410 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
1411 // associated with input events. This is important because the input system
1412 // uses the timestamps extensively and assumes they were recorded using the monotonic
1413 // clock.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001414 int clockId = CLOCK_MONOTONIC;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001415 bool usingClockIoctl = !ioctl(device->fd, EVIOCSCLOCKID, &clockId);
1416 ALOGI("wakeMechanism=%s, usingClockIoctl=%s", wakeMechanism.string(),
1417 toString(usingClockIoctl));
1418}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001419
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001420bool EventHub::isDeviceEnabled(int32_t deviceId) {
1421 AutoMutex _l(mLock);
1422 Device* device = getDeviceLocked(deviceId);
1423 if (device == NULL) {
1424 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1425 return false;
1426 }
1427 return device->enabled;
1428}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001429
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001430status_t EventHub::enableDevice(int32_t deviceId) {
1431 AutoMutex _l(mLock);
1432 Device* device = getDeviceLocked(deviceId);
1433 if (device == NULL) {
1434 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1435 return BAD_VALUE;
1436 }
1437 if (device->enabled) {
1438 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
1439 return OK;
1440 }
1441 status_t result = device->enable();
1442 if (result != OK) {
1443 ALOGE("Failed to enable device %" PRId32, deviceId);
1444 return result;
1445 }
1446
1447 configureFd(device);
1448
1449 return registerDeviceForEpollLocked(device);
1450}
1451
1452status_t EventHub::disableDevice(int32_t deviceId) {
1453 AutoMutex _l(mLock);
1454 Device* device = getDeviceLocked(deviceId);
1455 if (device == NULL) {
1456 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1457 return BAD_VALUE;
1458 }
1459 if (!device->enabled) {
1460 ALOGW("Duplicate call to %s, input device already disabled", __func__);
1461 return OK;
1462 }
1463 unregisterDeviceFromEpollLocked(device);
1464 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001465}
1466
1467void EventHub::createVirtualKeyboardLocked() {
1468 InputDeviceIdentifier identifier;
1469 identifier.name = "Virtual";
1470 identifier.uniqueId = "<virtual>";
1471 assignDescriptorLocked(identifier);
1472
1473 Device* device = new Device(-1, VIRTUAL_KEYBOARD_ID, String8("<virtual>"), identifier);
1474 device->classes = INPUT_DEVICE_CLASS_KEYBOARD
1475 | INPUT_DEVICE_CLASS_ALPHAKEY
1476 | INPUT_DEVICE_CLASS_DPAD
1477 | INPUT_DEVICE_CLASS_VIRTUAL;
1478 loadKeyMapLocked(device);
1479 addDeviceLocked(device);
1480}
1481
1482void EventHub::addDeviceLocked(Device* device) {
1483 mDevices.add(device->id, device);
1484 device->next = mOpeningDevices;
1485 mOpeningDevices = device;
1486}
1487
1488void EventHub::loadConfigurationLocked(Device* device) {
1489 device->configurationFile = getInputDeviceConfigurationFilePathByDeviceIdentifier(
1490 device->identifier, INPUT_DEVICE_CONFIGURATION_FILE_TYPE_CONFIGURATION);
1491 if (device->configurationFile.isEmpty()) {
1492 ALOGD("No input device configuration file found for device '%s'.",
1493 device->identifier.name.string());
1494 } else {
1495 status_t status = PropertyMap::load(device->configurationFile,
1496 &device->configuration);
1497 if (status) {
1498 ALOGE("Error loading input device configuration file for device '%s'. "
1499 "Using default configuration.",
1500 device->identifier.name.string());
1501 }
1502 }
1503}
1504
1505status_t EventHub::loadVirtualKeyMapLocked(Device* device) {
1506 // The virtual key map is supplied by the kernel as a system board property file.
1507 String8 path;
1508 path.append("/sys/board_properties/virtualkeys.");
1509 path.append(device->identifier.name);
1510 if (access(path.string(), R_OK)) {
1511 return NAME_NOT_FOUND;
1512 }
1513 return VirtualKeyMap::load(path, &device->virtualKeyMap);
1514}
1515
1516status_t EventHub::loadKeyMapLocked(Device* device) {
1517 return device->keyMap.load(device->identifier, device->configuration);
1518}
1519
1520bool EventHub::isExternalDeviceLocked(Device* device) {
1521 if (device->configuration) {
1522 bool value;
1523 if (device->configuration->tryGetProperty(String8("device.internal"), value)) {
1524 return !value;
1525 }
1526 }
1527 return device->identifier.bus == BUS_USB || device->identifier.bus == BUS_BLUETOOTH;
1528}
1529
Tim Kilbourn063ff532015-04-08 10:26:18 -07001530bool EventHub::deviceHasMicLocked(Device* device) {
1531 if (device->configuration) {
1532 bool value;
1533 if (device->configuration->tryGetProperty(String8("audio.mic"), value)) {
1534 return value;
1535 }
1536 }
1537 return false;
1538}
1539
Michael Wrightd02c5b62014-02-10 15:10:22 -08001540int32_t EventHub::getNextControllerNumberLocked(Device* device) {
1541 if (mControllerNumbers.isFull()) {
1542 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
1543 device->identifier.name.string());
1544 return 0;
1545 }
1546 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
1547 // one
1548 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
1549}
1550
1551void EventHub::releaseControllerNumberLocked(Device* device) {
1552 int32_t num = device->controllerNumber;
1553 device->controllerNumber= 0;
1554 if (num == 0) {
1555 return;
1556 }
1557 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
1558}
1559
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001560void EventHub::setLedForControllerLocked(Device* device) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001561 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
1562 setLedStateLocked(device, ALED_CONTROLLER_1 + i, device->controllerNumber == i + 1);
1563 }
1564}
1565
1566bool EventHub::hasKeycodeLocked(Device* device, int keycode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001567 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001568 return false;
1569 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001570
Michael Wrightd02c5b62014-02-10 15:10:22 -08001571 Vector<int32_t> scanCodes;
1572 device->keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes);
1573 const size_t N = scanCodes.size();
1574 for (size_t i=0; i<N && i<=KEY_MAX; i++) {
1575 int32_t sc = scanCodes.itemAt(i);
1576 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, device->keyBitmask)) {
1577 return true;
1578 }
1579 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001580
Michael Wrightd02c5b62014-02-10 15:10:22 -08001581 return false;
1582}
1583
1584status_t EventHub::mapLed(Device* device, int32_t led, int32_t* outScanCode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001585 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001586 return NAME_NOT_FOUND;
1587 }
1588
1589 int32_t scanCode;
1590 if(device->keyMap.keyLayoutMap->findScanCodeForLed(led, &scanCode) != NAME_NOT_FOUND) {
1591 if(scanCode >= 0 && scanCode <= LED_MAX && test_bit(scanCode, device->ledBitmask)) {
1592 *outScanCode = scanCode;
1593 return NO_ERROR;
1594 }
1595 }
1596 return NAME_NOT_FOUND;
1597}
1598
1599status_t EventHub::closeDeviceByPathLocked(const char *devicePath) {
1600 Device* device = getDeviceByPathLocked(devicePath);
1601 if (device) {
1602 closeDeviceLocked(device);
1603 return 0;
1604 }
1605 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath);
1606 return -1;
1607}
1608
1609void EventHub::closeAllDevicesLocked() {
1610 while (mDevices.size() > 0) {
1611 closeDeviceLocked(mDevices.valueAt(mDevices.size() - 1));
1612 }
1613}
1614
1615void EventHub::closeDeviceLocked(Device* device) {
1616 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=0x%x\n",
1617 device->path.string(), device->identifier.name.string(), device->id,
1618 device->fd, device->classes);
1619
1620 if (device->id == mBuiltInKeyboardId) {
1621 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
1622 device->path.string(), mBuiltInKeyboardId);
1623 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
1624 }
1625
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001626 unregisterDeviceFromEpollLocked(device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001627
1628 releaseControllerNumberLocked(device);
1629
1630 mDevices.removeItem(device->id);
1631 device->close();
1632
1633 // Unlink for opening devices list if it is present.
1634 Device* pred = NULL;
1635 bool found = false;
1636 for (Device* entry = mOpeningDevices; entry != NULL; ) {
1637 if (entry == device) {
1638 found = true;
1639 break;
1640 }
1641 pred = entry;
1642 entry = entry->next;
1643 }
1644 if (found) {
1645 // Unlink the device from the opening devices list then delete it.
1646 // We don't need to tell the client that the device was closed because
1647 // it does not even know it was opened in the first place.
1648 ALOGI("Device %s was immediately closed after opening.", device->path.string());
1649 if (pred) {
1650 pred->next = device->next;
1651 } else {
1652 mOpeningDevices = device->next;
1653 }
1654 delete device;
1655 } else {
1656 // Link into closing devices list.
1657 // The device will be deleted later after we have informed the client.
1658 device->next = mClosingDevices;
1659 mClosingDevices = device;
1660 }
1661}
1662
1663status_t EventHub::readNotifyLocked() {
1664 int res;
1665 char devname[PATH_MAX];
1666 char *filename;
1667 char event_buf[512];
1668 int event_size;
1669 int event_pos = 0;
1670 struct inotify_event *event;
1671
1672 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
1673 res = read(mINotifyFd, event_buf, sizeof(event_buf));
1674 if(res < (int)sizeof(*event)) {
1675 if(errno == EINTR)
1676 return 0;
1677 ALOGW("could not get event, %s\n", strerror(errno));
1678 return -1;
1679 }
1680 //printf("got %d bytes of event information\n", res);
1681
1682 strcpy(devname, DEVICE_PATH);
1683 filename = devname + strlen(devname);
1684 *filename++ = '/';
1685
1686 while(res >= (int)sizeof(*event)) {
1687 event = (struct inotify_event *)(event_buf + event_pos);
1688 //printf("%d: %08x \"%s\"\n", event->wd, event->mask, event->len ? event->name : "");
1689 if(event->len) {
1690 strcpy(filename, event->name);
1691 if(event->mask & IN_CREATE) {
1692 openDeviceLocked(devname);
1693 } else {
1694 ALOGI("Removing device '%s' due to inotify event\n", devname);
1695 closeDeviceByPathLocked(devname);
1696 }
1697 }
1698 event_size = sizeof(*event) + event->len;
1699 res -= event_size;
1700 event_pos += event_size;
1701 }
1702 return 0;
1703}
1704
1705status_t EventHub::scanDirLocked(const char *dirname)
1706{
1707 char devname[PATH_MAX];
1708 char *filename;
1709 DIR *dir;
1710 struct dirent *de;
1711 dir = opendir(dirname);
1712 if(dir == NULL)
1713 return -1;
1714 strcpy(devname, dirname);
1715 filename = devname + strlen(devname);
1716 *filename++ = '/';
1717 while((de = readdir(dir))) {
1718 if(de->d_name[0] == '.' &&
1719 (de->d_name[1] == '\0' ||
1720 (de->d_name[1] == '.' && de->d_name[2] == '\0')))
1721 continue;
1722 strcpy(filename, de->d_name);
1723 openDeviceLocked(devname);
1724 }
1725 closedir(dir);
1726 return 0;
1727}
1728
1729void EventHub::requestReopenDevices() {
1730 ALOGV("requestReopenDevices() called");
1731
1732 AutoMutex _l(mLock);
1733 mNeedToReopenDevices = true;
1734}
1735
1736void EventHub::dump(String8& dump) {
1737 dump.append("Event Hub State:\n");
1738
1739 { // acquire lock
1740 AutoMutex _l(mLock);
1741
1742 dump.appendFormat(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
1743
1744 dump.append(INDENT "Devices:\n");
1745
1746 for (size_t i = 0; i < mDevices.size(); i++) {
1747 const Device* device = mDevices.valueAt(i);
1748 if (mBuiltInKeyboardId == device->id) {
1749 dump.appendFormat(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
1750 device->id, device->identifier.name.string());
1751 } else {
1752 dump.appendFormat(INDENT2 "%d: %s\n", device->id,
1753 device->identifier.name.string());
1754 }
1755 dump.appendFormat(INDENT3 "Classes: 0x%08x\n", device->classes);
1756 dump.appendFormat(INDENT3 "Path: %s\n", device->path.string());
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001757 dump.appendFormat(INDENT3 "Enabled: %s\n", toString(device->enabled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001758 dump.appendFormat(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.string());
1759 dump.appendFormat(INDENT3 "Location: %s\n", device->identifier.location.string());
1760 dump.appendFormat(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
1761 dump.appendFormat(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.string());
1762 dump.appendFormat(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
1763 "product=0x%04x, version=0x%04x\n",
1764 device->identifier.bus, device->identifier.vendor,
1765 device->identifier.product, device->identifier.version);
1766 dump.appendFormat(INDENT3 "KeyLayoutFile: %s\n",
1767 device->keyMap.keyLayoutFile.string());
1768 dump.appendFormat(INDENT3 "KeyCharacterMapFile: %s\n",
1769 device->keyMap.keyCharacterMapFile.string());
1770 dump.appendFormat(INDENT3 "ConfigurationFile: %s\n",
1771 device->configurationFile.string());
1772 dump.appendFormat(INDENT3 "HaveKeyboardLayoutOverlay: %s\n",
1773 toString(device->overlayKeyMap != NULL));
1774 }
1775 } // release lock
1776}
1777
1778void EventHub::monitor() {
1779 // Acquire and release the lock to ensure that the event hub has not deadlocked.
1780 mLock.lock();
1781 mLock.unlock();
1782}
1783
1784
1785}; // namespace android