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