1 /*
2  * Copyright (C) 2015 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 "InputHub"
18 //#define LOG_NDEBUG 0
19 
20 #include "InputHub.h"
21 
22 #include <dirent.h>
23 #include <errno.h>
24 #include <fcntl.h>
25 #include <string.h>
26 #include <sys/capability.h>
27 #include <sys/epoll.h>
28 #include <sys/eventfd.h>
29 #include <sys/inotify.h>
30 #include <sys/ioctl.h>
31 #include <sys/stat.h>
32 #include <sys/types.h>
33 #include <sys/utsname.h>
34 #include <unistd.h>
35 
36 #include <vector>
37 
38 #include <android/input.h>
39 #include <hardware_legacy/power.h>
40 #include <linux/input.h>
41 
42 #include <utils/Log.h>
43 
44 #include "BitUtils.h"
45 
46 namespace android {
47 
48 static const char WAKE_LOCK_ID[] = "KeyEvents";
49 static const int NO_TIMEOUT = -1;
50 static const int EPOLL_MAX_EVENTS = 16;
51 static const int INPUT_MAX_EVENTS = 128;
52 
testBit(int bit,const uint8_t arr[])53 static constexpr bool testBit(int bit, const uint8_t arr[]) {
54     return arr[bit / 8] & (1 << (bit % 8));
55 }
56 
sizeofBitArray(size_t bits)57 static constexpr size_t sizeofBitArray(size_t bits) {
58     return (bits + 7) / 8;
59 }
60 
getLinuxRelease(int * major,int * minor)61 static void getLinuxRelease(int* major, int* minor) {
62     struct utsname info;
63     if (uname(&info) || sscanf(info.release, "%d.%d", major, minor) <= 0) {
64         *major = 0, *minor = 0;
65         ALOGE("Could not get linux version: %s", strerror(errno));
66     }
67 }
68 
69 class EvdevDeviceNode : public InputDeviceNode {
70 public:
71     static EvdevDeviceNode* openDeviceNode(const std::string& path);
72 
~EvdevDeviceNode()73     virtual ~EvdevDeviceNode() {
74         ALOGV("closing %s (fd=%d)", mPath.c_str(), mFd);
75         if (mFd >= 0) {
76             ::close(mFd);
77         }
78     }
79 
getFd() const80     virtual int getFd() const { return mFd; }
getPath() const81     virtual const std::string& getPath() const override { return mPath; }
getName() const82     virtual const std::string& getName() const override { return mName; }
getLocation() const83     virtual const std::string& getLocation() const override { return mLocation; }
getUniqueId() const84     virtual const std::string& getUniqueId() const override { return mUniqueId; }
85 
getBusType() const86     virtual uint16_t getBusType() const override { return mBusType; }
getVendorId() const87     virtual uint16_t getVendorId() const override { return mVendorId; }
getProductId() const88     virtual uint16_t getProductId() const override { return mProductId; }
getVersion() const89     virtual uint16_t getVersion() const override { return mVersion; }
90 
91     virtual bool hasKey(int32_t key) const override;
92     virtual bool hasKeyInRange(int32_t start, int32_t end) const override;
93     virtual bool hasRelativeAxis(int32_t axis) const override;
94     virtual bool hasAbsoluteAxis(int32_t axis) const override;
95     virtual bool hasSwitch(int32_t sw) const override;
96     virtual bool hasForceFeedback(int32_t ff) const override;
97     virtual bool hasInputProperty(int property) const override;
98 
99     virtual int32_t getKeyState(int32_t key) const override;
100     virtual int32_t getSwitchState(int32_t sw) const override;
101     virtual const AbsoluteAxisInfo* getAbsoluteAxisInfo(int32_t axis) const override;
102     virtual status_t getAbsoluteAxisValue(int32_t axis, int32_t* outValue) const override;
103 
104     virtual void vibrate(nsecs_t duration) override;
105     virtual void cancelVibrate() override;
106 
107     virtual void disableDriverKeyRepeat() override;
108 
109 private:
EvdevDeviceNode(const std::string & path,int fd)110     EvdevDeviceNode(const std::string& path, int fd) :
111         mFd(fd), mPath(path) {}
112 
113     status_t queryProperties();
114     void queryAxisInfo();
115 
116     int mFd;
117     std::string mPath;
118 
119     std::string mName;
120     std::string mLocation;
121     std::string mUniqueId;
122 
123     uint16_t mBusType;
124     uint16_t mVendorId;
125     uint16_t mProductId;
126     uint16_t mVersion;
127 
128     uint8_t mKeyBitmask[KEY_CNT / 8];
129     uint8_t mAbsBitmask[ABS_CNT / 8];
130     uint8_t mRelBitmask[REL_CNT / 8];
131     uint8_t mSwBitmask[SW_CNT / 8];
132     uint8_t mLedBitmask[LED_CNT / 8];
133     uint8_t mFfBitmask[FF_CNT / 8];
134     uint8_t mPropBitmask[INPUT_PROP_CNT / 8];
135 
136     std::unordered_map<uint32_t, std::unique_ptr<AbsoluteAxisInfo>> mAbsInfo;
137 
138     bool mFfEffectPlaying = false;
139     int16_t mFfEffectId = -1;
140 };
141 
openDeviceNode(const std::string & path)142 EvdevDeviceNode* EvdevDeviceNode::openDeviceNode(const std::string& path) {
143     auto fd = TEMP_FAILURE_RETRY(::open(path.c_str(), O_RDONLY | O_NONBLOCK | O_CLOEXEC));
144     if (fd < 0) {
145         ALOGE("could not open evdev device %s. err=%d", path.c_str(), errno);
146         return nullptr;
147     }
148 
149     // Tell the kernel that we want to use the monotonic clock for reporting
150     // timestamps associated with input events. This is important because the
151     // input system uses the timestamps extensively and assumes they were
152     // recorded using the monotonic clock.
153     //
154     // The EVIOCSCLOCKID ioctl was introduced in Linux 3.4.
155     int clockId = CLOCK_MONOTONIC;
156     if (TEMP_FAILURE_RETRY(ioctl(fd, EVIOCSCLOCKID, &clockId)) < 0) {
157         ALOGW("Could not set input clock id to CLOCK_MONOTONIC. errno=%d", errno);
158     }
159 
160     auto node = new EvdevDeviceNode(path, fd);
161     status_t ret = node->queryProperties();
162     if (ret != OK) {
163         ALOGE("could not open evdev device %s: failed to read properties. errno=%d",
164                 path.c_str(), ret);
165         delete node;
166         return nullptr;
167     }
168     return node;
169 }
170 
queryProperties()171 status_t EvdevDeviceNode::queryProperties() {
172     char buffer[80];
173 
174     if (TEMP_FAILURE_RETRY(ioctl(mFd, EVIOCGNAME(sizeof(buffer) - 1), buffer)) < 1) {
175         ALOGV("could not get device name for %s.", mPath.c_str());
176     } else {
177         buffer[sizeof(buffer) - 1] = '\0';
178         mName = buffer;
179     }
180 
181     int driverVersion;
182     if (TEMP_FAILURE_RETRY(ioctl(mFd, EVIOCGVERSION, &driverVersion))) {
183         ALOGE("could not get driver version for %s. err=%d", mPath.c_str(), errno);
184         return -errno;
185     }
186 
187     struct input_id inputId;
188     if (TEMP_FAILURE_RETRY(ioctl(mFd, EVIOCGID, &inputId))) {
189         ALOGE("could not get device input id for %s. err=%d", mPath.c_str(), errno);
190         return -errno;
191     }
192     mBusType = inputId.bustype;
193     mVendorId = inputId.vendor;
194     mProductId = inputId.product;
195     mVersion = inputId.version;
196 
197     if (TEMP_FAILURE_RETRY(ioctl(mFd, EVIOCGPHYS(sizeof(buffer) - 1), buffer)) < 1) {
198         ALOGV("could not get location for %s.", mPath.c_str());
199     } else {
200         buffer[sizeof(buffer) - 1] = '\0';
201         mLocation = buffer;
202     }
203 
204     if (TEMP_FAILURE_RETRY(ioctl(mFd, EVIOCGUNIQ(sizeof(buffer) - 1), buffer)) < 1) {
205         ALOGV("could not get unique id for %s.", mPath.c_str());
206     } else {
207         buffer[sizeof(buffer) - 1] = '\0';
208         mUniqueId = buffer;
209     }
210 
211     ALOGV("add device %s", mPath.c_str());
212     ALOGV("  bus:        %04x\n"
213           "  vendor:     %04x\n"
214           "  product:    %04x\n"
215           "  version:    %04x\n",
216         mBusType, mVendorId, mProductId, mVersion);
217     ALOGV("  name:       \"%s\"\n"
218           "  location:   \"%s\"\n"
219           "  unique_id:  \"%s\"\n"
220           "  descriptor: (TODO)\n"
221           "  driver:     v%d.%d.%d",
222         mName.c_str(), mLocation.c_str(), mUniqueId.c_str(),
223         driverVersion >> 16, (driverVersion >> 8) & 0xff, (driverVersion >> 16) & 0xff);
224 
225     TEMP_FAILURE_RETRY(ioctl(mFd, EVIOCGBIT(EV_KEY, sizeof(mKeyBitmask)), mKeyBitmask));
226     TEMP_FAILURE_RETRY(ioctl(mFd, EVIOCGBIT(EV_ABS, sizeof(mAbsBitmask)), mAbsBitmask));
227     TEMP_FAILURE_RETRY(ioctl(mFd, EVIOCGBIT(EV_REL, sizeof(mRelBitmask)), mRelBitmask));
228     TEMP_FAILURE_RETRY(ioctl(mFd, EVIOCGBIT(EV_SW,  sizeof(mSwBitmask)),  mSwBitmask));
229     TEMP_FAILURE_RETRY(ioctl(mFd, EVIOCGBIT(EV_LED, sizeof(mLedBitmask)), mLedBitmask));
230     TEMP_FAILURE_RETRY(ioctl(mFd, EVIOCGBIT(EV_FF,  sizeof(mFfBitmask)),  mFfBitmask));
231     TEMP_FAILURE_RETRY(ioctl(mFd, EVIOCGPROP(sizeof(mPropBitmask)), mPropBitmask));
232 
233     queryAxisInfo();
234 
235     return OK;
236 }
237 
queryAxisInfo()238 void EvdevDeviceNode::queryAxisInfo() {
239     for (int32_t axis = 0; axis < ABS_MAX; ++axis) {
240         if (testBit(axis, mAbsBitmask)) {
241             struct input_absinfo info;
242             if (TEMP_FAILURE_RETRY(ioctl(mFd, EVIOCGABS(axis), &info))) {
243                 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d",
244                         axis, mPath.c_str(), mFd, errno);
245                 continue;
246             }
247 
248             mAbsInfo[axis] = std::unique_ptr<AbsoluteAxisInfo>(new AbsoluteAxisInfo{
249                     .minValue = info.minimum,
250                     .maxValue = info.maximum,
251                     .flat = info.flat,
252                     .fuzz = info.fuzz,
253                     .resolution = info.resolution
254                     });
255         }
256     }
257 }
258 
hasKey(int32_t key) const259 bool EvdevDeviceNode::hasKey(int32_t key) const {
260     if (key >= 0 && key <= KEY_MAX) {
261         return testBit(key, mKeyBitmask);
262     }
263     return false;
264 }
265 
hasKeyInRange(int32_t startKey,int32_t endKey) const266 bool EvdevDeviceNode::hasKeyInRange(int32_t startKey, int32_t endKey) const {
267     return testBitInRange(mKeyBitmask, startKey, endKey);
268 }
269 
hasRelativeAxis(int axis) const270 bool EvdevDeviceNode::hasRelativeAxis(int axis) const {
271     if (axis >= 0 && axis <= REL_MAX) {
272         return testBit(axis, mRelBitmask);
273     }
274     return false;
275 }
276 
hasAbsoluteAxis(int axis) const277 bool EvdevDeviceNode::hasAbsoluteAxis(int axis) const {
278     if (axis >= 0 && axis <= ABS_MAX) {
279         return getAbsoluteAxisInfo(axis) != nullptr;
280     }
281     return false;
282 }
283 
getAbsoluteAxisInfo(int32_t axis) const284 const AbsoluteAxisInfo* EvdevDeviceNode::getAbsoluteAxisInfo(int32_t axis) const {
285     if (axis < 0 || axis > ABS_MAX) {
286         return nullptr;
287     }
288 
289     const auto absInfo = mAbsInfo.find(axis);
290     if (absInfo != mAbsInfo.end()) {
291         return absInfo->second.get();
292     }
293     return nullptr;
294 }
295 
hasSwitch(int32_t sw) const296 bool EvdevDeviceNode::hasSwitch(int32_t sw) const {
297     if (sw >= 0 && sw <= SW_MAX) {
298         return testBit(sw, mSwBitmask);
299     }
300     return false;
301 }
302 
hasForceFeedback(int32_t ff) const303 bool EvdevDeviceNode::hasForceFeedback(int32_t ff) const {
304     if (ff >= 0 && ff <= FF_MAX) {
305         return testBit(ff, mFfBitmask);
306     }
307     return false;
308 }
309 
hasInputProperty(int property) const310 bool EvdevDeviceNode::hasInputProperty(int property) const {
311     if (property >= 0 && property <= INPUT_PROP_MAX) {
312         return testBit(property, mPropBitmask);
313     }
314     return false;
315 }
316 
getKeyState(int32_t key) const317 int32_t EvdevDeviceNode::getKeyState(int32_t key) const {
318     if (key >= 0 && key <= KEY_MAX) {
319         if (testBit(key, mKeyBitmask)) {
320             uint8_t keyState[sizeofBitArray(KEY_CNT)];
321             memset(keyState, 0, sizeof(keyState));
322             if (TEMP_FAILURE_RETRY(ioctl(mFd, EVIOCGKEY(sizeof(keyState)), keyState)) >= 0) {
323                 return testBit(key, keyState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
324             }
325         }
326     }
327     return AKEY_STATE_UNKNOWN;
328 }
329 
getSwitchState(int32_t sw) const330 int32_t EvdevDeviceNode::getSwitchState(int32_t sw) const {
331     if (sw >= 0 && sw <= SW_MAX) {
332         if (testBit(sw, mSwBitmask)) {
333             uint8_t swState[sizeofBitArray(SW_CNT)];
334             memset(swState, 0, sizeof(swState));
335             if (TEMP_FAILURE_RETRY(ioctl(mFd, EVIOCGSW(sizeof(swState)), swState)) >= 0) {
336                 return testBit(sw, swState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
337             }
338         }
339     }
340     return AKEY_STATE_UNKNOWN;
341 }
342 
getAbsoluteAxisValue(int32_t axis,int32_t * outValue) const343 status_t EvdevDeviceNode::getAbsoluteAxisValue(int32_t axis, int32_t* outValue) const {
344     *outValue = 0;
345 
346     if (axis >= 0 && axis <= ABS_MAX) {
347         if (testBit(axis, mAbsBitmask)) {
348             struct input_absinfo info;
349             if (TEMP_FAILURE_RETRY(ioctl(mFd, EVIOCGABS(axis), &info))) {
350                 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d",
351                         axis, mPath.c_str(), mFd, errno);
352                 return -errno;
353             }
354 
355             *outValue = info.value;
356             return OK;
357         }
358     }
359     return -1;
360 }
361 
vibrate(nsecs_t duration)362 void EvdevDeviceNode::vibrate(nsecs_t duration) {
363     ff_effect effect{};
364     effect.type = FF_RUMBLE;
365     effect.id = mFfEffectId;
366     effect.u.rumble.strong_magnitude = 0xc000;
367     effect.u.rumble.weak_magnitude = 0xc000;
368     effect.replay.length = (duration + 999'999LL) / 1'000'000LL;
369     effect.replay.delay = 0;
370     if (TEMP_FAILURE_RETRY(ioctl(mFd, EVIOCSFF, &effect))) {
371         ALOGW("Could not upload force feedback effect to device %s due to error %d.",
372                 mPath.c_str(), errno);
373         return;
374     }
375     mFfEffectId = effect.id;
376 
377     struct input_event ev{};
378     ev.type = EV_FF;
379     ev.code = mFfEffectId;
380     ev.value = 1;
381     size_t written = TEMP_FAILURE_RETRY(write(mFd, &ev, sizeof(ev)));
382     if (written != sizeof(ev)) {
383         ALOGW("Could not start force feedback effect on device %s due to error %d.",
384                 mPath.c_str(), errno);
385         return;
386     }
387     mFfEffectPlaying = true;
388 }
389 
cancelVibrate()390 void EvdevDeviceNode::cancelVibrate() {
391     if (mFfEffectPlaying) {
392         mFfEffectPlaying = false;
393 
394         struct input_event ev{};
395         ev.type = EV_FF;
396         ev.code = mFfEffectId;
397         ev.value = 0;
398         size_t written = TEMP_FAILURE_RETRY(write(mFd, &ev, sizeof(ev)));
399         if (written != sizeof(ev)) {
400             ALOGW("Could not stop force feedback effect on device %s due to error %d.",
401                     mPath.c_str(), errno);
402             return;
403         }
404     }
405 }
406 
disableDriverKeyRepeat()407 void EvdevDeviceNode::disableDriverKeyRepeat() {
408     unsigned int repeatRate[] = {0, 0};
409     if (TEMP_FAILURE_RETRY(ioctl(mFd, EVIOCSREP, repeatRate))) {
410         ALOGW("Unable to disable kernel key repeat for %s due to error %d.",
411                 mPath.c_str(), errno);
412     }
413 }
414 
InputHub(const std::shared_ptr<InputCallbackInterface> & cb)415 InputHub::InputHub(const std::shared_ptr<InputCallbackInterface>& cb) :
416     mInputCallback(cb) {
417     // Determine the type of suspend blocking we can do on this device. There
418     // are 3 options, in decreasing order of preference:
419     //   1) EPOLLWAKEUP: introduced in Linux kernel 3.5, this flag can be set on
420     //   an epoll event to indicate that a wake lock should be held from the
421     //   time an fd has data until the next epoll_wait (or the epoll fd is
422     //   closed).
423     //   2) EVIOCSSUSPENDBLOCK: introduced into the Android kernel's evdev
424     //   driver, this ioctl blocks suspend while the event queue for the fd is
425     //   not empty. This was never accepted into the mainline kernel, and it was
426     //   replaced by EPOLLWAKEUP.
427     //   3) explicit wake locks: use acquire_wake_lock to manage suspend
428     //   blocking explicitly in the InputHub code.
429     //
430     // (1) can be checked by simply observing the Linux kernel version. (2)
431     // requires an fd from an evdev node, which cannot be done in the InputHub
432     // constructor. So we assume (3) unless (1) is true, and we can verify
433     // whether (2) is true once we have an evdev fd (and we're not in (1)).
434     int major, minor;
435     getLinuxRelease(&major, &minor);
436     if (major > 3 || (major == 3 && minor >= 5)) {
437         ALOGI("Using EPOLLWAKEUP to block suspend while processing input events.");
438         mWakeupMechanism = WakeMechanism::EPOLL_WAKEUP;
439         mNeedToCheckSuspendBlockIoctl = false;
440     }
441     if (manageWakeLocks()) {
442         acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
443     }
444 
445     // epoll_create argument is ignored, but it must be > 0.
446     mEpollFd = epoll_create(1);
447     LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance. errno=%d", errno);
448 
449     mINotifyFd = inotify_init();
450     LOG_ALWAYS_FATAL_IF(mINotifyFd < 0, "Could not create inotify instance. errno=%d", errno);
451 
452     struct epoll_event eventItem;
453     memset(&eventItem, 0, sizeof(eventItem));
454     eventItem.events = EPOLLIN;
455     if (mWakeupMechanism == WakeMechanism::EPOLL_WAKEUP) {
456         eventItem.events |= EPOLLWAKEUP;
457     }
458     eventItem.data.u32 = mINotifyFd;
459     int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
460     LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
461 
462     int wakeFds[2];
463     result = pipe(wakeFds);
464     LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
465 
466     mWakeEventFd = eventfd(0, EFD_NONBLOCK);
467     LOG_ALWAYS_FATAL_IF(mWakeEventFd == -1, "Could not create wake event fd. errno=%d", errno);
468 
469     eventItem.data.u32 = mWakeEventFd;
470     result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeEventFd, &eventItem);
471     LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake event fd to epoll instance. errno=%d", errno);
472 }
473 
~InputHub()474 InputHub::~InputHub() {
475     ::close(mEpollFd);
476     ::close(mINotifyFd);
477     ::close(mWakeEventFd);
478 
479     if (manageWakeLocks()) {
480         release_wake_lock(WAKE_LOCK_ID);
481     }
482 }
483 
registerDevicePath(const std::string & path)484 status_t InputHub::registerDevicePath(const std::string& path) {
485     ALOGV("registering device path %s", path.c_str());
486     int wd = inotify_add_watch(mINotifyFd, path.c_str(), IN_DELETE | IN_CREATE);
487     if (wd < 0) {
488         ALOGE("Could not add %s to INotify watch. errno=%d", path.c_str(), errno);
489         return -errno;
490     }
491     mWatchedPaths[wd] = path;
492     scanDir(path);
493     return OK;
494 }
495 
unregisterDevicePath(const std::string & path)496 status_t InputHub::unregisterDevicePath(const std::string& path) {
497     int wd = -1;
498     for (const auto& pair : mWatchedPaths) {
499         if (pair.second == path) {
500             wd = pair.first;
501             break;
502         }
503     }
504 
505     if (wd == -1) {
506         return BAD_VALUE;
507     }
508     mWatchedPaths.erase(wd);
509     if (inotify_rm_watch(mINotifyFd, wd) != 0) {
510         return -errno;
511     }
512     return OK;
513 }
514 
poll()515 status_t InputHub::poll() {
516     bool deviceChange = false;
517 
518     if (manageWakeLocks()) {
519         // Mind the wake lock dance!
520         // If we're relying on wake locks, we hold a wake lock at all times
521         // except during epoll_wait(). This works due to some subtle
522         // choreography. When a device driver has pending (unread) events, it
523         // acquires a kernel wake lock. However, once the last pending event
524         // has been read, the device driver will release the kernel wake lock.
525         // To prevent the system from going to sleep when this happens, the
526         // InputHub holds onto its own user wake lock while the client is
527         // processing events. Thus the system can only sleep if there are no
528         // events pending or currently being processed.
529         release_wake_lock(WAKE_LOCK_ID);
530     }
531 
532     struct epoll_event pendingEventItems[EPOLL_MAX_EVENTS];
533     int pollResult = epoll_wait(mEpollFd, pendingEventItems, EPOLL_MAX_EVENTS, NO_TIMEOUT);
534 
535     if (manageWakeLocks()) {
536         acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
537     }
538 
539     if (pollResult == 0) {
540         ALOGW("epoll_wait should not return 0 with no timeout");
541         return UNKNOWN_ERROR;
542     }
543     if (pollResult < 0) {
544         // An error occurred. Return even if it's EINTR, and let the caller
545         // restart the poll.
546         ALOGE("epoll_wait returned with errno=%d", errno);
547         return -errno;
548     }
549 
550     // pollResult > 0: there are events to process
551     nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
552     std::vector<int> removedDeviceFds;
553     int inputFd = -1;
554     std::shared_ptr<InputDeviceNode> deviceNode;
555     for (int i = 0; i < pollResult; ++i) {
556         const struct epoll_event& eventItem = pendingEventItems[i];
557 
558         int dataFd = static_cast<int>(eventItem.data.u32);
559         if (dataFd == mINotifyFd) {
560             if (eventItem.events & EPOLLIN) {
561                 deviceChange = true;
562             } else {
563                 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
564             }
565             continue;
566         }
567 
568         if (dataFd == mWakeEventFd) {
569             if (eventItem.events & EPOLLIN) {
570                 ALOGV("awoken after wake()");
571                 uint64_t u;
572                 ssize_t nRead = TEMP_FAILURE_RETRY(read(mWakeEventFd, &u, sizeof(uint64_t)));
573                 if (nRead != sizeof(uint64_t)) {
574                     ALOGW("Could not read event fd; waking anyway.");
575                 }
576             } else {
577                 ALOGW("Received unexpected epoll event 0x%08x for wake event.",
578                         eventItem.events);
579             }
580             continue;
581         }
582 
583         // Update the fd and device node when the fd changes. When several
584         // events are read back-to-back with the same fd, this saves many reads
585         // from the hash table.
586         if (inputFd != dataFd) {
587             inputFd = dataFd;
588             deviceNode = mDeviceNodes[inputFd];
589         }
590         if (deviceNode == nullptr) {
591             ALOGE("could not find device node for fd %d", inputFd);
592             continue;
593         }
594         if (eventItem.events & EPOLLIN) {
595             struct input_event ievs[INPUT_MAX_EVENTS];
596             for (;;) {
597                 ssize_t readSize = TEMP_FAILURE_RETRY(read(inputFd, ievs, sizeof(ievs)));
598                 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
599                     ALOGW("could not get event, removed? (fd: %d, size: %zd errno: %d)",
600                             inputFd, readSize, errno);
601 
602                     removedDeviceFds.push_back(inputFd);
603                     break;
604                 } else if (readSize < 0) {
605                     if (errno != EAGAIN && errno != EINTR) {
606                         ALOGW("could not get event. errno=%d", errno);
607                     }
608                     break;
609                 } else if (readSize % sizeof(input_event) != 0) {
610                     ALOGE("could not get event. wrong size=%zd", readSize);
611                     break;
612                 } else {
613                     size_t count = static_cast<size_t>(readSize) / sizeof(struct input_event);
614                     for (size_t i = 0; i < count; ++i) {
615                         auto& iev = ievs[i];
616                         auto when = s2ns(iev.time.tv_sec) + us2ns(iev.time.tv_usec);
617                         InputEvent inputEvent = { when, iev.type, iev.code, iev.value };
618                         mInputCallback->onInputEvent(deviceNode, inputEvent, now);
619                     }
620                 }
621             }
622         } else if (eventItem.events & EPOLLHUP) {
623             ALOGI("Removing device fd %d due to epoll hangup event.", inputFd);
624             removedDeviceFds.push_back(inputFd);
625         } else {
626             ALOGW("Received unexpected epoll event 0x%08x for device fd %d",
627                     eventItem.events, inputFd);
628         }
629     }
630 
631     if (removedDeviceFds.size()) {
632         for (auto deviceFd : removedDeviceFds) {
633             auto deviceNode = mDeviceNodes[deviceFd];
634             if (deviceNode != nullptr) {
635                 status_t ret = closeNodeByFd(deviceFd);
636                 if (ret != OK) {
637                     ALOGW("Could not close device with fd %d. errno=%d", deviceFd, ret);
638                 } else {
639                     mInputCallback->onDeviceRemoved(deviceNode);
640                 }
641             }
642         }
643     }
644 
645     if (deviceChange) {
646         readNotify();
647     }
648 
649     return OK;
650 }
651 
wake()652 status_t InputHub::wake() {
653     ALOGV("wake() called");
654 
655     uint64_t u = 1;
656     ssize_t nWrite = TEMP_FAILURE_RETRY(write(mWakeEventFd, &u, sizeof(uint64_t)));
657 
658     if (nWrite != sizeof(uint64_t) && errno != EAGAIN) {
659         ALOGW("Could not write wake signal, errno=%d", errno);
660         return -errno;
661     }
662     return OK;
663 }
664 
dump(String8 & dump)665 void InputHub::dump(String8& dump) {
666     // TODO
667 }
668 
readNotify()669 status_t InputHub::readNotify() {
670     char event_buf[512];
671     struct inotify_event* event;
672 
673     ssize_t res = TEMP_FAILURE_RETRY(read(mINotifyFd, event_buf, sizeof(event_buf)));
674     if (res < static_cast<int>(sizeof(*event))) {
675         ALOGW("could not get inotify event, %s\n", strerror(errno));
676         return -errno;
677     }
678 
679     size_t event_pos = 0;
680     while (res >= static_cast<int>(sizeof(*event))) {
681         event = reinterpret_cast<struct inotify_event*>(event_buf + event_pos);
682         if (event->len) {
683             std::string path = mWatchedPaths[event->wd];
684             path.append("/").append(event->name);
685             ALOGV("inotify event for path %s", path.c_str());
686 
687             if (event->mask & IN_CREATE) {
688                 auto deviceNode = openNode(path);
689                 if (deviceNode == nullptr) {
690                     ALOGE("could not open device node %s. err=%zd", path.c_str(), res);
691                 } else {
692                     mInputCallback->onDeviceAdded(deviceNode);
693                 }
694             } else {
695                 auto deviceNode = findNodeByPath(path);
696                 if (deviceNode != nullptr) {
697                     status_t ret = closeNode(deviceNode.get());
698                     if (ret != OK) {
699                         ALOGW("Could not close device %s. errno=%d", path.c_str(), ret);
700                     } else {
701                         mInputCallback->onDeviceRemoved(deviceNode);
702                     }
703                 } else {
704                     ALOGW("could not find device node for %s", path.c_str());
705                 }
706             }
707         }
708         int event_size = sizeof(*event) + event->len;
709         res -= event_size;
710         event_pos += event_size;
711     }
712 
713     return OK;
714 }
715 
scanDir(const std::string & path)716 status_t InputHub::scanDir(const std::string& path) {
717     auto dir = ::opendir(path.c_str());
718     if (dir == nullptr) {
719         ALOGE("could not open device path %s to scan for devices. err=%d", path.c_str(), errno);
720         return -errno;
721     }
722 
723     while (auto dirent = readdir(dir)) {
724         if (strcmp(dirent->d_name, ".") == 0 ||
725             strcmp(dirent->d_name, "..") == 0) {
726             continue;
727         }
728         std::string filename = path + "/" + dirent->d_name;
729         auto node = openNode(filename);
730         if (node == nullptr) {
731             ALOGE("could not open device node %s", filename.c_str());
732         } else {
733             mInputCallback->onDeviceAdded(node);
734         }
735     }
736     ::closedir(dir);
737     return OK;
738 }
739 
openNode(const std::string & path)740 std::shared_ptr<InputDeviceNode> InputHub::openNode(const std::string& path) {
741     ALOGV("opening %s...", path.c_str());
742     auto evdevNode = std::shared_ptr<EvdevDeviceNode>(EvdevDeviceNode::openDeviceNode(path));
743     if (evdevNode == nullptr) {
744         return nullptr;
745     }
746 
747     auto fd = evdevNode->getFd();
748     ALOGV("opened %s with fd %d", path.c_str(), fd);
749     mDeviceNodes[fd] = evdevNode;
750     struct epoll_event eventItem{};
751     eventItem.events = EPOLLIN;
752     if (mWakeupMechanism == WakeMechanism::EPOLL_WAKEUP) {
753         eventItem.events |= EPOLLWAKEUP;
754     }
755     eventItem.data.u32 = fd;
756     if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
757         ALOGE("Could not add device fd to epoll instance. errno=%d", errno);
758         return nullptr;
759     }
760 
761     if (mNeedToCheckSuspendBlockIoctl) {
762 #ifndef EVIOCSSUSPENDBLOCK
763         // uapi headers don't include EVIOCSSUSPENDBLOCK, and future kernels
764         // will use an epoll flag instead, so as long as we want to support this
765         // feature, we need to be prepared to define the ioctl ourselves.
766 #define EVIOCSSUSPENDBLOCK _IOW('E', 0x91, int)
767 #endif
768         if (TEMP_FAILURE_RETRY(ioctl(fd, EVIOCSSUSPENDBLOCK, 1))) {
769             // no wake mechanism, continue using explicit wake locks
770             ALOGI("Using explicit wakelocks to block suspend while processing input events.");
771         } else {
772             mWakeupMechanism = WakeMechanism::LEGACY_EVDEV_SUSPENDBLOCK_IOCTL;
773             // release any held wakelocks since we won't need them anymore
774             release_wake_lock(WAKE_LOCK_ID);
775             ALOGI("Using EVIOCSSUSPENDBLOCK to block suspend while processing input events.");
776         }
777         mNeedToCheckSuspendBlockIoctl = false;
778     }
779 
780     return evdevNode;
781 }
782 
closeNode(const InputDeviceNode * node)783 status_t InputHub::closeNode(const InputDeviceNode* node) {
784     for (const auto& pair : mDeviceNodes) {
785         if (pair.second.get() == node) {
786             return closeNodeByFd(pair.first);
787         }
788     }
789     return BAD_VALUE;
790 }
791 
closeNodeByFd(int fd)792 status_t InputHub::closeNodeByFd(int fd) {
793     status_t ret = OK;
794     if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, NULL)) {
795         ALOGW("Could not remove device fd from epoll instance. errno=%d", errno);
796         ret = -errno;
797     }
798     mDeviceNodes.erase(fd);
799     ::close(fd);
800     return ret;
801 }
802 
findNodeByPath(const std::string & path)803 std::shared_ptr<InputDeviceNode> InputHub::findNodeByPath(const std::string& path) {
804     for (const auto& pair : mDeviceNodes) {
805         if (pair.second->getPath() == path) return pair.second;
806     }
807     return nullptr;
808 }
809 
manageWakeLocks() const810 bool InputHub::manageWakeLocks() const {
811     return mWakeupMechanism != WakeMechanism::EPOLL_WAKEUP;
812 }
813 
814 }  // namespace android
815