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