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 #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 <androidfw/KeyLayoutMap.h>
40 #include <androidfw/KeyCharacterMap.h>
41 #include <androidfw/VirtualKeyMap.h>
42
43 #include <sha1.h>
44 #include <string.h>
45 #include <stdint.h>
46 #include <dirent.h>
47
48 #include <sys/inotify.h>
49 #include <sys/epoll.h>
50 #include <sys/ioctl.h>
51 #include <sys/limits.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 SHA1_CTX ctx;
84 SHA1Init(&ctx);
85 SHA1Update(&ctx, reinterpret_cast<const u_char*>(in.string()), in.size());
86 u_char digest[SHA1_DIGEST_LENGTH];
87 SHA1Final(digest, &ctx);
88
89 String8 out;
90 for (size_t i = 0; i < SHA1_DIGEST_LENGTH; i++) {
91 out.appendFormat("%02x", digest[i]);
92 }
93 return out;
94 }
95
setDescriptor(InputDeviceIdentifier & identifier)96 static void setDescriptor(InputDeviceIdentifier& identifier) {
97 // Compute a device descriptor that uniquely identifies the device.
98 // The descriptor is assumed to be a stable identifier. Its value should not
99 // change between reboots, reconnections, firmware updates or new releases of Android.
100 // Ideally, we also want the descriptor to be short and relatively opaque.
101 String8 rawDescriptor;
102 rawDescriptor.appendFormat(":%04x:%04x:", identifier.vendor, identifier.product);
103 if (!identifier.uniqueId.isEmpty()) {
104 rawDescriptor.append("uniqueId:");
105 rawDescriptor.append(identifier.uniqueId);
106 } if (identifier.vendor == 0 && identifier.product == 0) {
107 // If we don't know the vendor and product id, then the device is probably
108 // built-in so we need to rely on other information to uniquely identify
109 // the input device. Usually we try to avoid relying on the device name or
110 // location but for built-in input device, they are unlikely to ever change.
111 if (!identifier.name.isEmpty()) {
112 rawDescriptor.append("name:");
113 rawDescriptor.append(identifier.name);
114 } else if (!identifier.location.isEmpty()) {
115 rawDescriptor.append("location:");
116 rawDescriptor.append(identifier.location);
117 }
118 }
119 identifier.descriptor = sha1(rawDescriptor);
120 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.string(),
121 identifier.descriptor.string());
122 }
123
124 // --- Global Functions ---
125
getAbsAxisUsage(int32_t axis,uint32_t deviceClasses)126 uint32_t getAbsAxisUsage(int32_t axis, uint32_t deviceClasses) {
127 // Touch devices get dibs on touch-related axes.
128 if (deviceClasses & INPUT_DEVICE_CLASS_TOUCH) {
129 switch (axis) {
130 case ABS_X:
131 case ABS_Y:
132 case ABS_PRESSURE:
133 case ABS_TOOL_WIDTH:
134 case ABS_DISTANCE:
135 case ABS_TILT_X:
136 case ABS_TILT_Y:
137 case ABS_MT_SLOT:
138 case ABS_MT_TOUCH_MAJOR:
139 case ABS_MT_TOUCH_MINOR:
140 case ABS_MT_WIDTH_MAJOR:
141 case ABS_MT_WIDTH_MINOR:
142 case ABS_MT_ORIENTATION:
143 case ABS_MT_POSITION_X:
144 case ABS_MT_POSITION_Y:
145 case ABS_MT_TOOL_TYPE:
146 case ABS_MT_BLOB_ID:
147 case ABS_MT_TRACKING_ID:
148 case ABS_MT_PRESSURE:
149 case ABS_MT_DISTANCE:
150 return INPUT_DEVICE_CLASS_TOUCH;
151 }
152 }
153
154 // Joystick devices get the rest.
155 return deviceClasses & INPUT_DEVICE_CLASS_JOYSTICK;
156 }
157
158 // --- EventHub::Device ---
159
Device(int fd,int32_t id,const String8 & path,const InputDeviceIdentifier & identifier)160 EventHub::Device::Device(int fd, int32_t id, const String8& path,
161 const InputDeviceIdentifier& identifier) :
162 next(NULL),
163 fd(fd), id(id), path(path), identifier(identifier),
164 classes(0), configuration(NULL), virtualKeyMap(NULL),
165 ffEffectPlaying(false), ffEffectId(-1) {
166 memset(keyBitmask, 0, sizeof(keyBitmask));
167 memset(absBitmask, 0, sizeof(absBitmask));
168 memset(relBitmask, 0, sizeof(relBitmask));
169 memset(swBitmask, 0, sizeof(swBitmask));
170 memset(ledBitmask, 0, sizeof(ledBitmask));
171 memset(ffBitmask, 0, sizeof(ffBitmask));
172 memset(propBitmask, 0, sizeof(propBitmask));
173 }
174
~Device()175 EventHub::Device::~Device() {
176 close();
177 delete configuration;
178 delete virtualKeyMap;
179 }
180
close()181 void EventHub::Device::close() {
182 if (fd >= 0) {
183 ::close(fd);
184 fd = -1;
185 }
186 }
187
188
189 // --- EventHub ---
190
191 const uint32_t EventHub::EPOLL_ID_INOTIFY;
192 const uint32_t EventHub::EPOLL_ID_WAKE;
193 const int EventHub::EPOLL_SIZE_HINT;
194 const int EventHub::EPOLL_MAX_EVENTS;
195
EventHub(void)196 EventHub::EventHub(void) :
197 mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD), mNextDeviceId(1),
198 mOpeningDevices(0), mClosingDevices(0),
199 mNeedToSendFinishedDeviceScan(false),
200 mNeedToReopenDevices(false), mNeedToScanDevices(true),
201 mPendingEventCount(0), mPendingEventIndex(0), mPendingINotify(false) {
202 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
203
204 mEpollFd = epoll_create(EPOLL_SIZE_HINT);
205 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance. errno=%d", errno);
206
207 mINotifyFd = inotify_init();
208 int result = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
209 LOG_ALWAYS_FATAL_IF(result < 0, "Could not register INotify for %s. errno=%d",
210 DEVICE_PATH, errno);
211
212 struct epoll_event eventItem;
213 memset(&eventItem, 0, sizeof(eventItem));
214 eventItem.events = EPOLLIN;
215 eventItem.data.u32 = EPOLL_ID_INOTIFY;
216 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
217 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
218
219 int wakeFds[2];
220 result = pipe(wakeFds);
221 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
222
223 mWakeReadPipeFd = wakeFds[0];
224 mWakeWritePipeFd = wakeFds[1];
225
226 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
227 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
228 errno);
229
230 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
231 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
232 errno);
233
234 eventItem.data.u32 = EPOLL_ID_WAKE;
235 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
236 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
237 errno);
238 }
239
~EventHub(void)240 EventHub::~EventHub(void) {
241 closeAllDevicesLocked();
242
243 while (mClosingDevices) {
244 Device* device = mClosingDevices;
245 mClosingDevices = device->next;
246 delete device;
247 }
248
249 ::close(mEpollFd);
250 ::close(mINotifyFd);
251 ::close(mWakeReadPipeFd);
252 ::close(mWakeWritePipeFd);
253
254 release_wake_lock(WAKE_LOCK_ID);
255 }
256
getDeviceIdentifier(int32_t deviceId) const257 InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
258 AutoMutex _l(mLock);
259 Device* device = getDeviceLocked(deviceId);
260 if (device == NULL) return InputDeviceIdentifier();
261 return device->identifier;
262 }
263
getDeviceClasses(int32_t deviceId) const264 uint32_t EventHub::getDeviceClasses(int32_t deviceId) const {
265 AutoMutex _l(mLock);
266 Device* device = getDeviceLocked(deviceId);
267 if (device == NULL) return 0;
268 return device->classes;
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 if (device && led >= 0 && led <= LED_MAX) {
505 if (test_bit(led, device->ledBitmask)) {
506 return true;
507 }
508 }
509 return false;
510 }
511
setLedState(int32_t deviceId,int32_t led,bool on)512 void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
513 AutoMutex _l(mLock);
514 Device* device = getDeviceLocked(deviceId);
515 if (device && !device->isVirtual() && led >= 0 && led <= LED_MAX) {
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 = led;
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
getVirtualKeyDefinitions(int32_t deviceId,Vector<VirtualKeyDefinition> & outVirtualKeys) const530 void 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
getKeyCharacterMap(int32_t deviceId) const541 sp<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
setKeyboardLayoutOverlay(int32_t deviceId,const sp<KeyCharacterMap> & map)550 bool 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
vibrate(int32_t deviceId,nsecs_t duration)565 void EventHub::vibrate(int32_t deviceId, nsecs_t duration) {
566 AutoMutex _l(mLock);
567 Device* device = getDeviceLocked(deviceId);
568 if (device && !device->isVirtual()) {
569 ff_effect effect;
570 memset(&effect, 0, sizeof(effect));
571 effect.type = FF_RUMBLE;
572 effect.id = device->ffEffectId;
573 effect.u.rumble.strong_magnitude = 0xc000;
574 effect.u.rumble.weak_magnitude = 0xc000;
575 effect.replay.length = (duration + 999999LL) / 1000000LL;
576 effect.replay.delay = 0;
577 if (ioctl(device->fd, EVIOCSFF, &effect)) {
578 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
579 device->identifier.name.string(), errno);
580 return;
581 }
582 device->ffEffectId = effect.id;
583
584 struct input_event ev;
585 ev.time.tv_sec = 0;
586 ev.time.tv_usec = 0;
587 ev.type = EV_FF;
588 ev.code = device->ffEffectId;
589 ev.value = 1;
590 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
591 ALOGW("Could not start force feedback effect on device %s due to error %d.",
592 device->identifier.name.string(), errno);
593 return;
594 }
595 device->ffEffectPlaying = true;
596 }
597 }
598
cancelVibrate(int32_t deviceId)599 void EventHub::cancelVibrate(int32_t deviceId) {
600 AutoMutex _l(mLock);
601 Device* device = getDeviceLocked(deviceId);
602 if (device && !device->isVirtual()) {
603 if (device->ffEffectPlaying) {
604 device->ffEffectPlaying = false;
605
606 struct input_event ev;
607 ev.time.tv_sec = 0;
608 ev.time.tv_usec = 0;
609 ev.type = EV_FF;
610 ev.code = device->ffEffectId;
611 ev.value = 0;
612 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
613 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
614 device->identifier.name.string(), errno);
615 return;
616 }
617 }
618 }
619 }
620
getDeviceLocked(int32_t deviceId) const621 EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
622 if (deviceId == BUILT_IN_KEYBOARD_ID) {
623 deviceId = mBuiltInKeyboardId;
624 }
625 ssize_t index = mDevices.indexOfKey(deviceId);
626 return index >= 0 ? mDevices.valueAt(index) : NULL;
627 }
628
getDeviceByPathLocked(const char * devicePath) const629 EventHub::Device* EventHub::getDeviceByPathLocked(const char* devicePath) const {
630 for (size_t i = 0; i < mDevices.size(); i++) {
631 Device* device = mDevices.valueAt(i);
632 if (device->path == devicePath) {
633 return device;
634 }
635 }
636 return NULL;
637 }
638
getEvents(int timeoutMillis,RawEvent * buffer,size_t bufferSize)639 size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
640 ALOG_ASSERT(bufferSize >= 1);
641
642 AutoMutex _l(mLock);
643
644 struct input_event readBuffer[bufferSize];
645
646 RawEvent* event = buffer;
647 size_t capacity = bufferSize;
648 bool awoken = false;
649 for (;;) {
650 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
651
652 // Reopen input devices if needed.
653 if (mNeedToReopenDevices) {
654 mNeedToReopenDevices = false;
655
656 ALOGI("Reopening all input devices due to a configuration change.");
657
658 closeAllDevicesLocked();
659 mNeedToScanDevices = true;
660 break; // return to the caller before we actually rescan
661 }
662
663 // Report any devices that had last been added/removed.
664 while (mClosingDevices) {
665 Device* device = mClosingDevices;
666 ALOGV("Reporting device closed: id=%d, name=%s\n",
667 device->id, device->path.string());
668 mClosingDevices = device->next;
669 event->when = now;
670 event->deviceId = device->id == mBuiltInKeyboardId ? BUILT_IN_KEYBOARD_ID : device->id;
671 event->type = DEVICE_REMOVED;
672 event += 1;
673 delete device;
674 mNeedToSendFinishedDeviceScan = true;
675 if (--capacity == 0) {
676 break;
677 }
678 }
679
680 if (mNeedToScanDevices) {
681 mNeedToScanDevices = false;
682 scanDevicesLocked();
683 mNeedToSendFinishedDeviceScan = true;
684 }
685
686 while (mOpeningDevices != NULL) {
687 Device* device = mOpeningDevices;
688 ALOGV("Reporting device opened: id=%d, name=%s\n",
689 device->id, device->path.string());
690 mOpeningDevices = device->next;
691 event->when = now;
692 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
693 event->type = DEVICE_ADDED;
694 event += 1;
695 mNeedToSendFinishedDeviceScan = true;
696 if (--capacity == 0) {
697 break;
698 }
699 }
700
701 if (mNeedToSendFinishedDeviceScan) {
702 mNeedToSendFinishedDeviceScan = false;
703 event->when = now;
704 event->type = FINISHED_DEVICE_SCAN;
705 event += 1;
706 if (--capacity == 0) {
707 break;
708 }
709 }
710
711 // Grab the next input event.
712 bool deviceChanged = false;
713 while (mPendingEventIndex < mPendingEventCount) {
714 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
715 if (eventItem.data.u32 == EPOLL_ID_INOTIFY) {
716 if (eventItem.events & EPOLLIN) {
717 mPendingINotify = true;
718 } else {
719 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
720 }
721 continue;
722 }
723
724 if (eventItem.data.u32 == EPOLL_ID_WAKE) {
725 if (eventItem.events & EPOLLIN) {
726 ALOGV("awoken after wake()");
727 awoken = true;
728 char buffer[16];
729 ssize_t nRead;
730 do {
731 nRead = read(mWakeReadPipeFd, buffer, sizeof(buffer));
732 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(buffer));
733 } else {
734 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
735 eventItem.events);
736 }
737 continue;
738 }
739
740 ssize_t deviceIndex = mDevices.indexOfKey(eventItem.data.u32);
741 if (deviceIndex < 0) {
742 ALOGW("Received unexpected epoll event 0x%08x for unknown device id %d.",
743 eventItem.events, eventItem.data.u32);
744 continue;
745 }
746
747 Device* device = mDevices.valueAt(deviceIndex);
748 if (eventItem.events & EPOLLIN) {
749 int32_t readSize = read(device->fd, readBuffer,
750 sizeof(struct input_event) * capacity);
751 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
752 // Device was removed before INotify noticed.
753 ALOGW("could not get event, removed? (fd: %d size: %d bufferSize: %d "
754 "capacity: %d errno: %d)\n",
755 device->fd, readSize, bufferSize, capacity, errno);
756 deviceChanged = true;
757 closeDeviceLocked(device);
758 } else if (readSize < 0) {
759 if (errno != EAGAIN && errno != EINTR) {
760 ALOGW("could not get event (errno=%d)", errno);
761 }
762 } else if ((readSize % sizeof(struct input_event)) != 0) {
763 ALOGE("could not get event (wrong size: %d)", readSize);
764 } else {
765 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
766
767 size_t count = size_t(readSize) / sizeof(struct input_event);
768 for (size_t i = 0; i < count; i++) {
769 const struct input_event& iev = readBuffer[i];
770 ALOGV("%s got: t0=%d, t1=%d, type=%d, code=%d, value=%d",
771 device->path.string(),
772 (int) iev.time.tv_sec, (int) iev.time.tv_usec,
773 iev.type, iev.code, iev.value);
774
775 #ifdef HAVE_POSIX_CLOCKS
776 // Use the time specified in the event instead of the current time
777 // so that downstream code can get more accurate estimates of
778 // event dispatch latency from the time the event is enqueued onto
779 // the evdev client buffer.
780 //
781 // The event's timestamp fortuitously uses the same monotonic clock
782 // time base as the rest of Android. The kernel event device driver
783 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
784 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
785 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
786 // system call that also queries ktime_get_ts().
787 event->when = nsecs_t(iev.time.tv_sec) * 1000000000LL
788 + nsecs_t(iev.time.tv_usec) * 1000LL;
789 ALOGV("event time %lld, now %lld", event->when, now);
790 #else
791 event->when = now;
792 #endif
793 event->deviceId = deviceId;
794 event->type = iev.type;
795 event->code = iev.code;
796 event->value = iev.value;
797 event += 1;
798 }
799 capacity -= count;
800 if (capacity == 0) {
801 // The result buffer is full. Reset the pending event index
802 // so we will try to read the device again on the next iteration.
803 mPendingEventIndex -= 1;
804 break;
805 }
806 }
807 } else if (eventItem.events & EPOLLHUP) {
808 ALOGI("Removing device %s due to epoll hang-up event.",
809 device->identifier.name.string());
810 deviceChanged = true;
811 closeDeviceLocked(device);
812 } else {
813 ALOGW("Received unexpected epoll event 0x%08x for device %s.",
814 eventItem.events, device->identifier.name.string());
815 }
816 }
817
818 // readNotify() will modify the list of devices so this must be done after
819 // processing all other events to ensure that we read all remaining events
820 // before closing the devices.
821 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
822 mPendingINotify = false;
823 readNotifyLocked();
824 deviceChanged = true;
825 }
826
827 // Report added or removed devices immediately.
828 if (deviceChanged) {
829 continue;
830 }
831
832 // Return now if we have collected any events or if we were explicitly awoken.
833 if (event != buffer || awoken) {
834 break;
835 }
836
837 // Poll for events. Mind the wake lock dance!
838 // We hold a wake lock at all times except during epoll_wait(). This works due to some
839 // subtle choreography. When a device driver has pending (unread) events, it acquires
840 // a kernel wake lock. However, once the last pending event has been read, the device
841 // driver will release the kernel wake lock. To prevent the system from going to sleep
842 // when this happens, the EventHub holds onto its own user wake lock while the client
843 // is processing events. Thus the system can only sleep if there are no events
844 // pending or currently being processed.
845 //
846 // The timeout is advisory only. If the device is asleep, it will not wake just to
847 // service the timeout.
848 mPendingEventIndex = 0;
849
850 mLock.unlock(); // release lock before poll, must be before release_wake_lock
851 release_wake_lock(WAKE_LOCK_ID);
852
853 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
854
855 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
856 mLock.lock(); // reacquire lock after poll, must be after acquire_wake_lock
857
858 if (pollResult == 0) {
859 // Timed out.
860 mPendingEventCount = 0;
861 break;
862 }
863
864 if (pollResult < 0) {
865 // An error occurred.
866 mPendingEventCount = 0;
867
868 // Sleep after errors to avoid locking up the system.
869 // Hopefully the error is transient.
870 if (errno != EINTR) {
871 ALOGW("poll failed (errno=%d)\n", errno);
872 usleep(100000);
873 }
874 } else {
875 // Some events occurred.
876 mPendingEventCount = size_t(pollResult);
877 }
878 }
879
880 // All done, return the number of events we read.
881 return event - buffer;
882 }
883
wake()884 void EventHub::wake() {
885 ALOGV("wake() called");
886
887 ssize_t nWrite;
888 do {
889 nWrite = write(mWakeWritePipeFd, "W", 1);
890 } while (nWrite == -1 && errno == EINTR);
891
892 if (nWrite != 1 && errno != EAGAIN) {
893 ALOGW("Could not write wake signal, errno=%d", errno);
894 }
895 }
896
scanDevicesLocked()897 void EventHub::scanDevicesLocked() {
898 status_t res = scanDirLocked(DEVICE_PATH);
899 if(res < 0) {
900 ALOGE("scan dir failed for %s\n", DEVICE_PATH);
901 }
902 if (mDevices.indexOfKey(VIRTUAL_KEYBOARD_ID) < 0) {
903 createVirtualKeyboardLocked();
904 }
905 }
906
907 // ----------------------------------------------------------------------------
908
containsNonZeroByte(const uint8_t * array,uint32_t startIndex,uint32_t endIndex)909 static bool containsNonZeroByte(const uint8_t* array, uint32_t startIndex, uint32_t endIndex) {
910 const uint8_t* end = array + endIndex;
911 array += startIndex;
912 while (array != end) {
913 if (*(array++) != 0) {
914 return true;
915 }
916 }
917 return false;
918 }
919
920 static const int32_t GAMEPAD_KEYCODES[] = {
921 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C,
922 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z,
923 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1,
924 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2,
925 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR,
926 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE,
927 AKEYCODE_BUTTON_1, AKEYCODE_BUTTON_2, AKEYCODE_BUTTON_3, AKEYCODE_BUTTON_4,
928 AKEYCODE_BUTTON_5, AKEYCODE_BUTTON_6, AKEYCODE_BUTTON_7, AKEYCODE_BUTTON_8,
929 AKEYCODE_BUTTON_9, AKEYCODE_BUTTON_10, AKEYCODE_BUTTON_11, AKEYCODE_BUTTON_12,
930 AKEYCODE_BUTTON_13, AKEYCODE_BUTTON_14, AKEYCODE_BUTTON_15, AKEYCODE_BUTTON_16,
931 };
932
openDeviceLocked(const char * devicePath)933 status_t EventHub::openDeviceLocked(const char *devicePath) {
934 char buffer[80];
935
936 ALOGV("Opening device: %s", devicePath);
937
938 int fd = open(devicePath, O_RDWR | O_CLOEXEC);
939 if(fd < 0) {
940 ALOGE("could not open %s, %s\n", devicePath, strerror(errno));
941 return -1;
942 }
943
944 InputDeviceIdentifier identifier;
945
946 // Get device name.
947 if(ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
948 //fprintf(stderr, "could not get device name for %s, %s\n", devicePath, strerror(errno));
949 } else {
950 buffer[sizeof(buffer) - 1] = '\0';
951 identifier.name.setTo(buffer);
952 }
953
954 // Check to see if the device is on our excluded list
955 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
956 const String8& item = mExcludedDevices.itemAt(i);
957 if (identifier.name == item) {
958 ALOGI("ignoring event id %s driver %s\n", devicePath, item.string());
959 close(fd);
960 return -1;
961 }
962 }
963
964 // Get device driver version.
965 int driverVersion;
966 if(ioctl(fd, EVIOCGVERSION, &driverVersion)) {
967 ALOGE("could not get driver version for %s, %s\n", devicePath, strerror(errno));
968 close(fd);
969 return -1;
970 }
971
972 // Get device identifier.
973 struct input_id inputId;
974 if(ioctl(fd, EVIOCGID, &inputId)) {
975 ALOGE("could not get device input id for %s, %s\n", devicePath, strerror(errno));
976 close(fd);
977 return -1;
978 }
979 identifier.bus = inputId.bustype;
980 identifier.product = inputId.product;
981 identifier.vendor = inputId.vendor;
982 identifier.version = inputId.version;
983
984 // Get device physical location.
985 if(ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
986 //fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
987 } else {
988 buffer[sizeof(buffer) - 1] = '\0';
989 identifier.location.setTo(buffer);
990 }
991
992 // Get device unique id.
993 if(ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
994 //fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
995 } else {
996 buffer[sizeof(buffer) - 1] = '\0';
997 identifier.uniqueId.setTo(buffer);
998 }
999
1000 // Fill in the descriptor.
1001 setDescriptor(identifier);
1002
1003 // Make file descriptor non-blocking for use with poll().
1004 if (fcntl(fd, F_SETFL, O_NONBLOCK)) {
1005 ALOGE("Error %d making device file descriptor non-blocking.", errno);
1006 close(fd);
1007 return -1;
1008 }
1009
1010 // Allocate device. (The device object takes ownership of the fd at this point.)
1011 int32_t deviceId = mNextDeviceId++;
1012 Device* device = new Device(fd, deviceId, String8(devicePath), identifier);
1013
1014 ALOGV("add device %d: %s\n", deviceId, devicePath);
1015 ALOGV(" bus: %04x\n"
1016 " vendor %04x\n"
1017 " product %04x\n"
1018 " version %04x\n",
1019 identifier.bus, identifier.vendor, identifier.product, identifier.version);
1020 ALOGV(" name: \"%s\"\n", identifier.name.string());
1021 ALOGV(" location: \"%s\"\n", identifier.location.string());
1022 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.string());
1023 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.string());
1024 ALOGV(" driver: v%d.%d.%d\n",
1025 driverVersion >> 16, (driverVersion >> 8) & 0xff, driverVersion & 0xff);
1026
1027 // Load the configuration file for the device.
1028 loadConfigurationLocked(device);
1029
1030 // Figure out the kinds of events the device reports.
1031 ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(device->keyBitmask)), device->keyBitmask);
1032 ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(device->absBitmask)), device->absBitmask);
1033 ioctl(fd, EVIOCGBIT(EV_REL, sizeof(device->relBitmask)), device->relBitmask);
1034 ioctl(fd, EVIOCGBIT(EV_SW, sizeof(device->swBitmask)), device->swBitmask);
1035 ioctl(fd, EVIOCGBIT(EV_LED, sizeof(device->ledBitmask)), device->ledBitmask);
1036 ioctl(fd, EVIOCGBIT(EV_FF, sizeof(device->ffBitmask)), device->ffBitmask);
1037 ioctl(fd, EVIOCGPROP(sizeof(device->propBitmask)), device->propBitmask);
1038
1039 // See if this is a keyboard. Ignore everything in the button range except for
1040 // joystick and gamepad buttons which are handled like keyboards for the most part.
1041 bool haveKeyboardKeys = containsNonZeroByte(device->keyBitmask, 0, sizeof_bit_array(BTN_MISC))
1042 || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(KEY_OK),
1043 sizeof_bit_array(KEY_MAX + 1));
1044 bool haveGamepadButtons = containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_MISC),
1045 sizeof_bit_array(BTN_MOUSE))
1046 || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_JOYSTICK),
1047 sizeof_bit_array(BTN_DIGI));
1048 if (haveKeyboardKeys || haveGamepadButtons) {
1049 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1050 }
1051
1052 // See if this is a cursor device such as a trackball or mouse.
1053 if (test_bit(BTN_MOUSE, device->keyBitmask)
1054 && test_bit(REL_X, device->relBitmask)
1055 && test_bit(REL_Y, device->relBitmask)) {
1056 device->classes |= INPUT_DEVICE_CLASS_CURSOR;
1057 }
1058
1059 // See if this is a touch pad.
1060 // Is this a new modern multi-touch driver?
1061 if (test_bit(ABS_MT_POSITION_X, device->absBitmask)
1062 && test_bit(ABS_MT_POSITION_Y, device->absBitmask)) {
1063 // Some joysticks such as the PS3 controller report axes that conflict
1064 // with the ABS_MT range. Try to confirm that the device really is
1065 // a touch screen.
1066 if (test_bit(BTN_TOUCH, device->keyBitmask) || !haveGamepadButtons) {
1067 device->classes |= INPUT_DEVICE_CLASS_TOUCH | INPUT_DEVICE_CLASS_TOUCH_MT;
1068 }
1069 // Is this an old style single-touch driver?
1070 } else if (test_bit(BTN_TOUCH, device->keyBitmask)
1071 && test_bit(ABS_X, device->absBitmask)
1072 && test_bit(ABS_Y, device->absBitmask)) {
1073 device->classes |= INPUT_DEVICE_CLASS_TOUCH;
1074 }
1075
1076 // See if this device is a joystick.
1077 // Assumes that joysticks always have gamepad buttons in order to distinguish them
1078 // from other devices such as accelerometers that also have absolute axes.
1079 if (haveGamepadButtons) {
1080 uint32_t assumedClasses = device->classes | INPUT_DEVICE_CLASS_JOYSTICK;
1081 for (int i = 0; i <= ABS_MAX; i++) {
1082 if (test_bit(i, device->absBitmask)
1083 && (getAbsAxisUsage(i, assumedClasses) & INPUT_DEVICE_CLASS_JOYSTICK)) {
1084 device->classes = assumedClasses;
1085 break;
1086 }
1087 }
1088 }
1089
1090 // Check whether this device has switches.
1091 for (int i = 0; i <= SW_MAX; i++) {
1092 if (test_bit(i, device->swBitmask)) {
1093 device->classes |= INPUT_DEVICE_CLASS_SWITCH;
1094 break;
1095 }
1096 }
1097
1098 // Check whether this device supports the vibrator.
1099 if (test_bit(FF_RUMBLE, device->ffBitmask)) {
1100 device->classes |= INPUT_DEVICE_CLASS_VIBRATOR;
1101 }
1102
1103 // Configure virtual keys.
1104 if ((device->classes & INPUT_DEVICE_CLASS_TOUCH)) {
1105 // Load the virtual keys for the touch screen, if any.
1106 // We do this now so that we can make sure to load the keymap if necessary.
1107 status_t status = loadVirtualKeyMapLocked(device);
1108 if (!status) {
1109 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1110 }
1111 }
1112
1113 // Load the key map.
1114 // We need to do this for joysticks too because the key layout may specify axes.
1115 status_t keyMapStatus = NAME_NOT_FOUND;
1116 if (device->classes & (INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_JOYSTICK)) {
1117 // Load the keymap for the device.
1118 keyMapStatus = loadKeyMapLocked(device);
1119 }
1120
1121 // Configure the keyboard, gamepad or virtual keyboard.
1122 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1123 // Register the keyboard as a built-in keyboard if it is eligible.
1124 if (!keyMapStatus
1125 && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD
1126 && isEligibleBuiltInKeyboard(device->identifier,
1127 device->configuration, &device->keyMap)) {
1128 mBuiltInKeyboardId = device->id;
1129 }
1130
1131 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
1132 if (hasKeycodeLocked(device, AKEYCODE_Q)) {
1133 device->classes |= INPUT_DEVICE_CLASS_ALPHAKEY;
1134 }
1135
1136 // See if this device has a DPAD.
1137 if (hasKeycodeLocked(device, AKEYCODE_DPAD_UP) &&
1138 hasKeycodeLocked(device, AKEYCODE_DPAD_DOWN) &&
1139 hasKeycodeLocked(device, AKEYCODE_DPAD_LEFT) &&
1140 hasKeycodeLocked(device, AKEYCODE_DPAD_RIGHT) &&
1141 hasKeycodeLocked(device, AKEYCODE_DPAD_CENTER)) {
1142 device->classes |= INPUT_DEVICE_CLASS_DPAD;
1143 }
1144
1145 // See if this device has a gamepad.
1146 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES)/sizeof(GAMEPAD_KEYCODES[0]); i++) {
1147 if (hasKeycodeLocked(device, GAMEPAD_KEYCODES[i])) {
1148 device->classes |= INPUT_DEVICE_CLASS_GAMEPAD;
1149 break;
1150 }
1151 }
1152 }
1153
1154 // If the device isn't recognized as something we handle, don't monitor it.
1155 if (device->classes == 0) {
1156 ALOGV("Dropping device: id=%d, path='%s', name='%s'",
1157 deviceId, devicePath, device->identifier.name.string());
1158 delete device;
1159 return -1;
1160 }
1161
1162 // Determine whether the device is external or internal.
1163 if (isExternalDeviceLocked(device)) {
1164 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL;
1165 }
1166
1167 // Register with epoll.
1168 struct epoll_event eventItem;
1169 memset(&eventItem, 0, sizeof(eventItem));
1170 eventItem.events = EPOLLIN;
1171 eventItem.data.u32 = deviceId;
1172 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1173 ALOGE("Could not add device fd to epoll instance. errno=%d", errno);
1174 delete device;
1175 return -1;
1176 }
1177
1178 // Enable wake-lock behavior on kernels that support it.
1179 // TODO: Only need this for devices that can really wake the system.
1180 bool usingSuspendBlockIoctl = !ioctl(fd, EVIOCSSUSPENDBLOCK, 1);
1181
1182 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
1183 // associated with input events. This is important because the input system
1184 // uses the timestamps extensively and assumes they were recorded using the monotonic
1185 // clock.
1186 //
1187 // In older kernel, before Linux 3.4, there was no way to tell the kernel which
1188 // clock to use to input event timestamps. The standard kernel behavior was to
1189 // record a real time timestamp, which isn't what we want. Android kernels therefore
1190 // contained a patch to the evdev_event() function in drivers/input/evdev.c to
1191 // replace the call to do_gettimeofday() with ktime_get_ts() to cause the monotonic
1192 // clock to be used instead of the real time clock.
1193 //
1194 // As of Linux 3.4, there is a new EVIOCSCLOCKID ioctl to set the desired clock.
1195 // Therefore, we no longer require the Android-specific kernel patch described above
1196 // as long as we make sure to set select the monotonic clock. We do that here.
1197 int clockId = CLOCK_MONOTONIC;
1198 bool usingClockIoctl = !ioctl(fd, EVIOCSCLOCKID, &clockId);
1199
1200 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=0x%x, "
1201 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, "
1202 "usingSuspendBlockIoctl=%s, usingClockIoctl=%s",
1203 deviceId, fd, devicePath, device->identifier.name.string(),
1204 device->classes,
1205 device->configurationFile.string(),
1206 device->keyMap.keyLayoutFile.string(),
1207 device->keyMap.keyCharacterMapFile.string(),
1208 toString(mBuiltInKeyboardId == deviceId),
1209 toString(usingSuspendBlockIoctl), toString(usingClockIoctl));
1210
1211 addDeviceLocked(device);
1212 return 0;
1213 }
1214
createVirtualKeyboardLocked()1215 void EventHub::createVirtualKeyboardLocked() {
1216 InputDeviceIdentifier identifier;
1217 identifier.name = "Virtual";
1218 identifier.uniqueId = "<virtual>";
1219 setDescriptor(identifier);
1220
1221 Device* device = new Device(-1, VIRTUAL_KEYBOARD_ID, String8("<virtual>"), identifier);
1222 device->classes = INPUT_DEVICE_CLASS_KEYBOARD
1223 | INPUT_DEVICE_CLASS_ALPHAKEY
1224 | INPUT_DEVICE_CLASS_DPAD
1225 | INPUT_DEVICE_CLASS_VIRTUAL;
1226 loadKeyMapLocked(device);
1227 addDeviceLocked(device);
1228 }
1229
addDeviceLocked(Device * device)1230 void EventHub::addDeviceLocked(Device* device) {
1231 mDevices.add(device->id, device);
1232 device->next = mOpeningDevices;
1233 mOpeningDevices = device;
1234 }
1235
loadConfigurationLocked(Device * device)1236 void EventHub::loadConfigurationLocked(Device* device) {
1237 device->configurationFile = getInputDeviceConfigurationFilePathByDeviceIdentifier(
1238 device->identifier, INPUT_DEVICE_CONFIGURATION_FILE_TYPE_CONFIGURATION);
1239 if (device->configurationFile.isEmpty()) {
1240 ALOGD("No input device configuration file found for device '%s'.",
1241 device->identifier.name.string());
1242 } else {
1243 status_t status = PropertyMap::load(device->configurationFile,
1244 &device->configuration);
1245 if (status) {
1246 ALOGE("Error loading input device configuration file for device '%s'. "
1247 "Using default configuration.",
1248 device->identifier.name.string());
1249 }
1250 }
1251 }
1252
loadVirtualKeyMapLocked(Device * device)1253 status_t EventHub::loadVirtualKeyMapLocked(Device* device) {
1254 // The virtual key map is supplied by the kernel as a system board property file.
1255 String8 path;
1256 path.append("/sys/board_properties/virtualkeys.");
1257 path.append(device->identifier.name);
1258 if (access(path.string(), R_OK)) {
1259 return NAME_NOT_FOUND;
1260 }
1261 return VirtualKeyMap::load(path, &device->virtualKeyMap);
1262 }
1263
loadKeyMapLocked(Device * device)1264 status_t EventHub::loadKeyMapLocked(Device* device) {
1265 return device->keyMap.load(device->identifier, device->configuration);
1266 }
1267
isExternalDeviceLocked(Device * device)1268 bool EventHub::isExternalDeviceLocked(Device* device) {
1269 if (device->configuration) {
1270 bool value;
1271 if (device->configuration->tryGetProperty(String8("device.internal"), value)) {
1272 return !value;
1273 }
1274 }
1275 return device->identifier.bus == BUS_USB || device->identifier.bus == BUS_BLUETOOTH;
1276 }
1277
hasKeycodeLocked(Device * device,int keycode) const1278 bool EventHub::hasKeycodeLocked(Device* device, int keycode) const {
1279 if (!device->keyMap.haveKeyLayout() || !device->keyBitmask) {
1280 return false;
1281 }
1282
1283 Vector<int32_t> scanCodes;
1284 device->keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes);
1285 const size_t N = scanCodes.size();
1286 for (size_t i=0; i<N && i<=KEY_MAX; i++) {
1287 int32_t sc = scanCodes.itemAt(i);
1288 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, device->keyBitmask)) {
1289 return true;
1290 }
1291 }
1292
1293 return false;
1294 }
1295
closeDeviceByPathLocked(const char * devicePath)1296 status_t EventHub::closeDeviceByPathLocked(const char *devicePath) {
1297 Device* device = getDeviceByPathLocked(devicePath);
1298 if (device) {
1299 closeDeviceLocked(device);
1300 return 0;
1301 }
1302 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath);
1303 return -1;
1304 }
1305
closeAllDevicesLocked()1306 void EventHub::closeAllDevicesLocked() {
1307 while (mDevices.size() > 0) {
1308 closeDeviceLocked(mDevices.valueAt(mDevices.size() - 1));
1309 }
1310 }
1311
closeDeviceLocked(Device * device)1312 void EventHub::closeDeviceLocked(Device* device) {
1313 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=0x%x\n",
1314 device->path.string(), device->identifier.name.string(), device->id,
1315 device->fd, device->classes);
1316
1317 if (device->id == mBuiltInKeyboardId) {
1318 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
1319 device->path.string(), mBuiltInKeyboardId);
1320 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
1321 }
1322
1323 if (!device->isVirtual()) {
1324 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, device->fd, NULL)) {
1325 ALOGW("Could not remove device fd from epoll instance. errno=%d", errno);
1326 }
1327 }
1328
1329 mDevices.removeItem(device->id);
1330 device->close();
1331
1332 // Unlink for opening devices list if it is present.
1333 Device* pred = NULL;
1334 bool found = false;
1335 for (Device* entry = mOpeningDevices; entry != NULL; ) {
1336 if (entry == device) {
1337 found = true;
1338 break;
1339 }
1340 pred = entry;
1341 entry = entry->next;
1342 }
1343 if (found) {
1344 // Unlink the device from the opening devices list then delete it.
1345 // We don't need to tell the client that the device was closed because
1346 // it does not even know it was opened in the first place.
1347 ALOGI("Device %s was immediately closed after opening.", device->path.string());
1348 if (pred) {
1349 pred->next = device->next;
1350 } else {
1351 mOpeningDevices = device->next;
1352 }
1353 delete device;
1354 } else {
1355 // Link into closing devices list.
1356 // The device will be deleted later after we have informed the client.
1357 device->next = mClosingDevices;
1358 mClosingDevices = device;
1359 }
1360 }
1361
readNotifyLocked()1362 status_t EventHub::readNotifyLocked() {
1363 int res;
1364 char devname[PATH_MAX];
1365 char *filename;
1366 char event_buf[512];
1367 int event_size;
1368 int event_pos = 0;
1369 struct inotify_event *event;
1370
1371 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
1372 res = read(mINotifyFd, event_buf, sizeof(event_buf));
1373 if(res < (int)sizeof(*event)) {
1374 if(errno == EINTR)
1375 return 0;
1376 ALOGW("could not get event, %s\n", strerror(errno));
1377 return -1;
1378 }
1379 //printf("got %d bytes of event information\n", res);
1380
1381 strcpy(devname, DEVICE_PATH);
1382 filename = devname + strlen(devname);
1383 *filename++ = '/';
1384
1385 while(res >= (int)sizeof(*event)) {
1386 event = (struct inotify_event *)(event_buf + event_pos);
1387 //printf("%d: %08x \"%s\"\n", event->wd, event->mask, event->len ? event->name : "");
1388 if(event->len) {
1389 strcpy(filename, event->name);
1390 if(event->mask & IN_CREATE) {
1391 openDeviceLocked(devname);
1392 } else {
1393 ALOGI("Removing device '%s' due to inotify event\n", devname);
1394 closeDeviceByPathLocked(devname);
1395 }
1396 }
1397 event_size = sizeof(*event) + event->len;
1398 res -= event_size;
1399 event_pos += event_size;
1400 }
1401 return 0;
1402 }
1403
scanDirLocked(const char * dirname)1404 status_t EventHub::scanDirLocked(const char *dirname)
1405 {
1406 char devname[PATH_MAX];
1407 char *filename;
1408 DIR *dir;
1409 struct dirent *de;
1410 dir = opendir(dirname);
1411 if(dir == NULL)
1412 return -1;
1413 strcpy(devname, dirname);
1414 filename = devname + strlen(devname);
1415 *filename++ = '/';
1416 while((de = readdir(dir))) {
1417 if(de->d_name[0] == '.' &&
1418 (de->d_name[1] == '\0' ||
1419 (de->d_name[1] == '.' && de->d_name[2] == '\0')))
1420 continue;
1421 strcpy(filename, de->d_name);
1422 openDeviceLocked(devname);
1423 }
1424 closedir(dir);
1425 return 0;
1426 }
1427
requestReopenDevices()1428 void EventHub::requestReopenDevices() {
1429 ALOGV("requestReopenDevices() called");
1430
1431 AutoMutex _l(mLock);
1432 mNeedToReopenDevices = true;
1433 }
1434
dump(String8 & dump)1435 void EventHub::dump(String8& dump) {
1436 dump.append("Event Hub State:\n");
1437
1438 { // acquire lock
1439 AutoMutex _l(mLock);
1440
1441 dump.appendFormat(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
1442
1443 dump.append(INDENT "Devices:\n");
1444
1445 for (size_t i = 0; i < mDevices.size(); i++) {
1446 const Device* device = mDevices.valueAt(i);
1447 if (mBuiltInKeyboardId == device->id) {
1448 dump.appendFormat(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
1449 device->id, device->identifier.name.string());
1450 } else {
1451 dump.appendFormat(INDENT2 "%d: %s\n", device->id,
1452 device->identifier.name.string());
1453 }
1454 dump.appendFormat(INDENT3 "Classes: 0x%08x\n", device->classes);
1455 dump.appendFormat(INDENT3 "Path: %s\n", device->path.string());
1456 dump.appendFormat(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.string());
1457 dump.appendFormat(INDENT3 "Location: %s\n", device->identifier.location.string());
1458 dump.appendFormat(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.string());
1459 dump.appendFormat(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
1460 "product=0x%04x, version=0x%04x\n",
1461 device->identifier.bus, device->identifier.vendor,
1462 device->identifier.product, device->identifier.version);
1463 dump.appendFormat(INDENT3 "KeyLayoutFile: %s\n",
1464 device->keyMap.keyLayoutFile.string());
1465 dump.appendFormat(INDENT3 "KeyCharacterMapFile: %s\n",
1466 device->keyMap.keyCharacterMapFile.string());
1467 dump.appendFormat(INDENT3 "ConfigurationFile: %s\n",
1468 device->configurationFile.string());
1469 dump.appendFormat(INDENT3 "HaveKeyboardLayoutOverlay: %s\n",
1470 toString(device->overlayKeyMap != NULL));
1471 }
1472 } // release lock
1473 }
1474
monitor()1475 void EventHub::monitor() {
1476 // Acquire and release the lock to ensure that the event hub has not deadlocked.
1477 mLock.lock();
1478 mLock.unlock();
1479 }
1480
1481
1482 }; // namespace android
1483