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