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