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