Home | History | Annotate | Download | only in libusbhost
      1 /*
      2  * Copyright (C) 2010 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 #ifndef _GNU_SOURCE
     18 #define _GNU_SOURCE
     19 #endif
     20 
     21 // #define DEBUG 1
     22 #if DEBUG
     23 
     24 #ifdef USE_LIBLOG
     25 #define LOG_TAG "usbhost"
     26 #include "log/log.h"
     27 #define D ALOGD
     28 #else
     29 #define D printf
     30 #endif
     31 
     32 #else
     33 #define D(...)
     34 #endif
     35 
     36 #include <stdio.h>
     37 #include <stdlib.h>
     38 #include <unistd.h>
     39 #include <string.h>
     40 #include <stddef.h>
     41 
     42 #include <sys/ioctl.h>
     43 #include <sys/types.h>
     44 #include <sys/time.h>
     45 #include <sys/inotify.h>
     46 #include <dirent.h>
     47 #include <fcntl.h>
     48 #include <errno.h>
     49 #include <ctype.h>
     50 #include <poll.h>
     51 #include <pthread.h>
     52 
     53 #include <linux/usbdevice_fs.h>
     54 #include <asm/byteorder.h>
     55 
     56 #include "usbhost/usbhost.h"
     57 
     58 #define DEV_DIR             "/dev"
     59 #define DEV_BUS_DIR         DEV_DIR "/bus"
     60 #define USB_FS_DIR          DEV_BUS_DIR "/usb"
     61 #define USB_FS_ID_SCANNER   USB_FS_DIR "/%d/%d"
     62 #define USB_FS_ID_FORMAT    USB_FS_DIR "/%03d/%03d"
     63 
     64 // Some devices fail to send string descriptors if we attempt reading > 255 bytes
     65 #define MAX_STRING_DESCRIPTOR_LENGTH    255
     66 
     67 // From drivers/usb/core/devio.c
     68 // I don't know why this isn't in a kernel header
     69 #define MAX_USBFS_BUFFER_SIZE   16384
     70 
     71 #define MAX_USBFS_WD_COUNT      10
     72 
     73 struct usb_host_context {
     74     int                         fd;
     75     usb_device_added_cb         cb_added;
     76     usb_device_removed_cb       cb_removed;
     77     void                        *data;
     78     int                         wds[MAX_USBFS_WD_COUNT];
     79     int                         wdd;
     80     int                         wddbus;
     81 };
     82 
     83 struct usb_device {
     84     char dev_name[64];
     85     unsigned char desc[4096];
     86     int desc_length;
     87     int fd;
     88     int writeable;
     89 };
     90 
     91 static inline int badname(const char *name)
     92 {
     93     while(*name) {
     94         if(!isdigit(*name++)) return 1;
     95     }
     96     return 0;
     97 }
     98 
     99 static int find_existing_devices_bus(char *busname,
    100                                      usb_device_added_cb added_cb,
    101                                      void *client_data)
    102 {
    103     char devname[32];
    104     DIR *devdir;
    105     struct dirent *de;
    106     int done = 0;
    107 
    108     devdir = opendir(busname);
    109     if(devdir == 0) return 0;
    110 
    111     while ((de = readdir(devdir)) && !done) {
    112         if(badname(de->d_name)) continue;
    113 
    114         snprintf(devname, sizeof(devname), "%s/%s", busname, de->d_name);
    115         done = added_cb(devname, client_data);
    116     } // end of devdir while
    117     closedir(devdir);
    118 
    119     return done;
    120 }
    121 
    122 /* returns true if one of the callbacks indicates we are done */
    123 static int find_existing_devices(usb_device_added_cb added_cb,
    124                                   void *client_data)
    125 {
    126     char busname[32];
    127     DIR *busdir;
    128     struct dirent *de;
    129     int done = 0;
    130 
    131     busdir = opendir(USB_FS_DIR);
    132     if(busdir == 0) return 0;
    133 
    134     while ((de = readdir(busdir)) != 0 && !done) {
    135         if(badname(de->d_name)) continue;
    136 
    137         snprintf(busname, sizeof(busname), USB_FS_DIR "/%s", de->d_name);
    138         done = find_existing_devices_bus(busname, added_cb,
    139                                          client_data);
    140     } //end of busdir while
    141     closedir(busdir);
    142 
    143     return done;
    144 }
    145 
    146 static void watch_existing_subdirs(struct usb_host_context *context,
    147                                    int *wds, int wd_count)
    148 {
    149     char path[100];
    150     int i, ret;
    151 
    152     wds[0] = inotify_add_watch(context->fd, USB_FS_DIR, IN_CREATE | IN_DELETE);
    153     if (wds[0] < 0)
    154         return;
    155 
    156     /* watch existing subdirectories of USB_FS_DIR */
    157     for (i = 1; i < wd_count; i++) {
    158         snprintf(path, sizeof(path), USB_FS_DIR "/%03d", i);
    159         ret = inotify_add_watch(context->fd, path, IN_CREATE | IN_DELETE);
    160         if (ret >= 0)
    161             wds[i] = ret;
    162     }
    163 }
    164 
    165 struct usb_host_context *usb_host_init()
    166 {
    167     struct usb_host_context *context = calloc(1, sizeof(struct usb_host_context));
    168     if (!context) {
    169         fprintf(stderr, "out of memory in usb_host_context\n");
    170         return NULL;
    171     }
    172     context->fd = inotify_init();
    173     if (context->fd < 0) {
    174         fprintf(stderr, "inotify_init failed\n");
    175         free(context);
    176         return NULL;
    177     }
    178     return context;
    179 }
    180 
    181 void usb_host_cleanup(struct usb_host_context *context)
    182 {
    183     close(context->fd);
    184     free(context);
    185 }
    186 
    187 int usb_host_get_fd(struct usb_host_context *context)
    188 {
    189     return context->fd;
    190 } /* usb_host_get_fd() */
    191 
    192 int usb_host_load(struct usb_host_context *context,
    193                   usb_device_added_cb added_cb,
    194                   usb_device_removed_cb removed_cb,
    195                   usb_discovery_done_cb discovery_done_cb,
    196                   void *client_data)
    197 {
    198     int done = 0;
    199     int i;
    200 
    201     context->cb_added = added_cb;
    202     context->cb_removed = removed_cb;
    203     context->data = client_data;
    204 
    205     D("Created device discovery thread\n");
    206 
    207     /* watch for files added and deleted within USB_FS_DIR */
    208     context->wddbus = -1;
    209     for (i = 0; i < MAX_USBFS_WD_COUNT; i++)
    210         context->wds[i] = -1;
    211 
    212     /* watch the root for new subdirectories */
    213     context->wdd = inotify_add_watch(context->fd, DEV_DIR, IN_CREATE | IN_DELETE);
    214     if (context->wdd < 0) {
    215         fprintf(stderr, "inotify_add_watch failed\n");
    216         if (discovery_done_cb)
    217             discovery_done_cb(client_data);
    218         return done;
    219     }
    220 
    221     watch_existing_subdirs(context, context->wds, MAX_USBFS_WD_COUNT);
    222 
    223     /* check for existing devices first, after we have inotify set up */
    224     done = find_existing_devices(added_cb, client_data);
    225     if (discovery_done_cb)
    226         done |= discovery_done_cb(client_data);
    227 
    228     return done;
    229 } /* usb_host_load() */
    230 
    231 int usb_host_read_event(struct usb_host_context *context)
    232 {
    233     struct inotify_event* event;
    234     char event_buf[512];
    235     char path[100];
    236     int i, ret, done = 0;
    237     int offset = 0;
    238     int wd;
    239 
    240     ret = read(context->fd, event_buf, sizeof(event_buf));
    241     if (ret >= (int)sizeof(struct inotify_event)) {
    242         while (offset < ret && !done) {
    243             event = (struct inotify_event*)&event_buf[offset];
    244             done = 0;
    245             wd = event->wd;
    246             if (wd == context->wdd) {
    247                 if ((event->mask & IN_CREATE) && !strcmp(event->name, "bus")) {
    248                     context->wddbus = inotify_add_watch(context->fd, DEV_BUS_DIR, IN_CREATE | IN_DELETE);
    249                     if (context->wddbus < 0) {
    250                         done = 1;
    251                     } else {
    252                         watch_existing_subdirs(context, context->wds, MAX_USBFS_WD_COUNT);
    253                         done = find_existing_devices(context->cb_added, context->data);
    254                     }
    255                 }
    256             } else if (wd == context->wddbus) {
    257                 if ((event->mask & IN_CREATE) && !strcmp(event->name, "usb")) {
    258                     watch_existing_subdirs(context, context->wds, MAX_USBFS_WD_COUNT);
    259                     done = find_existing_devices(context->cb_added, context->data);
    260                 } else if ((event->mask & IN_DELETE) && !strcmp(event->name, "usb")) {
    261                     for (i = 0; i < MAX_USBFS_WD_COUNT; i++) {
    262                         if (context->wds[i] >= 0) {
    263                             inotify_rm_watch(context->fd, context->wds[i]);
    264                             context->wds[i] = -1;
    265                         }
    266                     }
    267                 }
    268             } else if (wd == context->wds[0]) {
    269                 i = atoi(event->name);
    270                 snprintf(path, sizeof(path), USB_FS_DIR "/%s", event->name);
    271                 D("%s subdirectory %s: index: %d\n", (event->mask & IN_CREATE) ?
    272                         "new" : "gone", path, i);
    273                 if (i > 0 && i < MAX_USBFS_WD_COUNT) {
    274                     int local_ret = 0;
    275                     if (event->mask & IN_CREATE) {
    276                         local_ret = inotify_add_watch(context->fd, path,
    277                                 IN_CREATE | IN_DELETE);
    278                         if (local_ret >= 0)
    279                             context->wds[i] = local_ret;
    280                         done = find_existing_devices_bus(path, context->cb_added,
    281                                 context->data);
    282                     } else if (event->mask & IN_DELETE) {
    283                         inotify_rm_watch(context->fd, context->wds[i]);
    284                         context->wds[i] = -1;
    285                     }
    286                 }
    287             } else {
    288                 for (i = 1; (i < MAX_USBFS_WD_COUNT) && !done; i++) {
    289                     if (wd == context->wds[i]) {
    290                         snprintf(path, sizeof(path), USB_FS_DIR "/%03d/%s", i, event->name);
    291                         if (event->mask == IN_CREATE) {
    292                             D("new device %s\n", path);
    293                             done = context->cb_added(path, context->data);
    294                         } else if (event->mask == IN_DELETE) {
    295                             D("gone device %s\n", path);
    296                             done = context->cb_removed(path, context->data);
    297                         }
    298                     }
    299                 }
    300             }
    301 
    302             offset += sizeof(struct inotify_event) + event->len;
    303         }
    304     }
    305 
    306     return done;
    307 } /* usb_host_read_event() */
    308 
    309 void usb_host_run(struct usb_host_context *context,
    310                   usb_device_added_cb added_cb,
    311                   usb_device_removed_cb removed_cb,
    312                   usb_discovery_done_cb discovery_done_cb,
    313                   void *client_data)
    314 {
    315     int done;
    316 
    317     done = usb_host_load(context, added_cb, removed_cb, discovery_done_cb, client_data);
    318 
    319     while (!done) {
    320 
    321         done = usb_host_read_event(context);
    322     }
    323 } /* usb_host_run() */
    324 
    325 struct usb_device *usb_device_open(const char *dev_name)
    326 {
    327     int fd, did_retry = 0, writeable = 1;
    328 
    329     D("usb_device_open %s\n", dev_name);
    330 
    331 retry:
    332     fd = open(dev_name, O_RDWR);
    333     if (fd < 0) {
    334         /* if we fail, see if have read-only access */
    335         fd = open(dev_name, O_RDONLY);
    336         D("usb_device_open open returned %d errno %d\n", fd, errno);
    337         if (fd < 0 && (errno == EACCES || errno == ENOENT) && !did_retry) {
    338             /* work around race condition between inotify and permissions management */
    339             sleep(1);
    340             did_retry = 1;
    341             goto retry;
    342         }
    343 
    344         if (fd < 0)
    345             return NULL;
    346         writeable = 0;
    347         D("[ usb open read-only %s fd = %d]\n", dev_name, fd);
    348     }
    349 
    350     struct usb_device* result = usb_device_new(dev_name, fd);
    351     if (result)
    352         result->writeable = writeable;
    353     return result;
    354 }
    355 
    356 void usb_device_close(struct usb_device *device)
    357 {
    358     close(device->fd);
    359     free(device);
    360 }
    361 
    362 struct usb_device *usb_device_new(const char *dev_name, int fd)
    363 {
    364     struct usb_device *device = calloc(1, sizeof(struct usb_device));
    365     int length;
    366 
    367     D("usb_device_new %s fd: %d\n", dev_name, fd);
    368 
    369     if (lseek(fd, 0, SEEK_SET) != 0)
    370         goto failed;
    371     length = read(fd, device->desc, sizeof(device->desc));
    372     D("usb_device_new read returned %d errno %d\n", length, errno);
    373     if (length < 0)
    374         goto failed;
    375 
    376     strncpy(device->dev_name, dev_name, sizeof(device->dev_name) - 1);
    377     device->fd = fd;
    378     device->desc_length = length;
    379     // assume we are writeable, since usb_device_get_fd will only return writeable fds
    380     device->writeable = 1;
    381     return device;
    382 
    383 failed:
    384     close(fd);
    385     free(device);
    386     return NULL;
    387 }
    388 
    389 static int usb_device_reopen_writeable(struct usb_device *device)
    390 {
    391     if (device->writeable)
    392         return 1;
    393 
    394     int fd = open(device->dev_name, O_RDWR);
    395     if (fd >= 0) {
    396         close(device->fd);
    397         device->fd = fd;
    398         device->writeable = 1;
    399         return 1;
    400     }
    401     D("usb_device_reopen_writeable failed errno %d\n", errno);
    402     return 0;
    403 }
    404 
    405 int usb_device_get_fd(struct usb_device *device)
    406 {
    407     if (!usb_device_reopen_writeable(device))
    408         return -1;
    409     return device->fd;
    410 }
    411 
    412 const char* usb_device_get_name(struct usb_device *device)
    413 {
    414     return device->dev_name;
    415 }
    416 
    417 int usb_device_get_unique_id(struct usb_device *device)
    418 {
    419     int bus = 0, dev = 0;
    420     sscanf(device->dev_name, USB_FS_ID_SCANNER, &bus, &dev);
    421     return bus * 1000 + dev;
    422 }
    423 
    424 int usb_device_get_unique_id_from_name(const char* name)
    425 {
    426     int bus = 0, dev = 0;
    427     sscanf(name, USB_FS_ID_SCANNER, &bus, &dev);
    428     return bus * 1000 + dev;
    429 }
    430 
    431 char* usb_device_get_name_from_unique_id(int id)
    432 {
    433     int bus = id / 1000;
    434     int dev = id % 1000;
    435     char* result = (char *)calloc(1, strlen(USB_FS_ID_FORMAT));
    436     snprintf(result, strlen(USB_FS_ID_FORMAT) - 1, USB_FS_ID_FORMAT, bus, dev);
    437     return result;
    438 }
    439 
    440 uint16_t usb_device_get_vendor_id(struct usb_device *device)
    441 {
    442     struct usb_device_descriptor* desc = (struct usb_device_descriptor*)device->desc;
    443     return __le16_to_cpu(desc->idVendor);
    444 }
    445 
    446 uint16_t usb_device_get_product_id(struct usb_device *device)
    447 {
    448     struct usb_device_descriptor* desc = (struct usb_device_descriptor*)device->desc;
    449     return __le16_to_cpu(desc->idProduct);
    450 }
    451 
    452 const struct usb_device_descriptor* usb_device_get_device_descriptor(struct usb_device *device)
    453 {
    454     return (struct usb_device_descriptor*)device->desc;
    455 }
    456 
    457 char* usb_device_get_string(struct usb_device *device, int id, int timeout)
    458 {
    459     char string[256];
    460     __u16 buffer[MAX_STRING_DESCRIPTOR_LENGTH / sizeof(__u16)];
    461     __u16 languages[MAX_STRING_DESCRIPTOR_LENGTH / sizeof(__u16)];
    462     int i, result;
    463     int languageCount = 0;
    464 
    465     if (id == 0) return NULL;
    466 
    467     string[0] = 0;
    468     memset(languages, 0, sizeof(languages));
    469 
    470     // read list of supported languages
    471     result = usb_device_control_transfer(device,
    472             USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE, USB_REQ_GET_DESCRIPTOR,
    473             (USB_DT_STRING << 8) | 0, 0, languages, sizeof(languages),
    474             timeout);
    475     if (result > 0)
    476         languageCount = (result - 2) / 2;
    477 
    478     for (i = 1; i <= languageCount; i++) {
    479         memset(buffer, 0, sizeof(buffer));
    480 
    481         result = usb_device_control_transfer(device,
    482                 USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE, USB_REQ_GET_DESCRIPTOR,
    483                 (USB_DT_STRING << 8) | id, languages[i], buffer, sizeof(buffer),
    484                 timeout);
    485         if (result > 0) {
    486             int i;
    487             // skip first word, and copy the rest to the string, changing shorts to bytes.
    488             result /= 2;
    489             for (i = 1; i < result; i++)
    490                 string[i - 1] = buffer[i];
    491             string[i - 1] = 0;
    492             return strdup(string);
    493         }
    494     }
    495 
    496     return NULL;
    497 }
    498 
    499 char* usb_device_get_manufacturer_name(struct usb_device *device, int timeout)
    500 {
    501     struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc;
    502     return usb_device_get_string(device, desc->iManufacturer, timeout);
    503 }
    504 
    505 char* usb_device_get_product_name(struct usb_device *device, int timeout)
    506 {
    507     struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc;
    508     return usb_device_get_string(device, desc->iProduct, timeout);
    509 }
    510 
    511 int usb_device_get_version(struct usb_device *device)
    512 {
    513     struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc;
    514     return desc->bcdUSB;
    515 }
    516 
    517 char* usb_device_get_serial(struct usb_device *device, int timeout)
    518 {
    519     struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc;
    520     return usb_device_get_string(device, desc->iSerialNumber, timeout);
    521 }
    522 
    523 int usb_device_is_writeable(struct usb_device *device)
    524 {
    525     return device->writeable;
    526 }
    527 
    528 void usb_descriptor_iter_init(struct usb_device *device, struct usb_descriptor_iter *iter)
    529 {
    530     iter->config = device->desc;
    531     iter->config_end = device->desc + device->desc_length;
    532     iter->curr_desc = device->desc;
    533 }
    534 
    535 struct usb_descriptor_header *usb_descriptor_iter_next(struct usb_descriptor_iter *iter)
    536 {
    537     struct usb_descriptor_header* next;
    538     if (iter->curr_desc >= iter->config_end)
    539         return NULL;
    540     next = (struct usb_descriptor_header*)iter->curr_desc;
    541     iter->curr_desc += next->bLength;
    542     return next;
    543 }
    544 
    545 int usb_device_claim_interface(struct usb_device *device, unsigned int interface)
    546 {
    547     return ioctl(device->fd, USBDEVFS_CLAIMINTERFACE, &interface);
    548 }
    549 
    550 int usb_device_release_interface(struct usb_device *device, unsigned int interface)
    551 {
    552     return ioctl(device->fd, USBDEVFS_RELEASEINTERFACE, &interface);
    553 }
    554 
    555 int usb_device_connect_kernel_driver(struct usb_device *device,
    556         unsigned int interface, int connect)
    557 {
    558     struct usbdevfs_ioctl ctl;
    559 
    560     ctl.ifno = interface;
    561     ctl.ioctl_code = (connect ? USBDEVFS_CONNECT : USBDEVFS_DISCONNECT);
    562     ctl.data = NULL;
    563     return ioctl(device->fd, USBDEVFS_IOCTL, &ctl);
    564 }
    565 
    566 int usb_device_set_configuration(struct usb_device *device, int configuration)
    567 {
    568     return ioctl(device->fd, USBDEVFS_SETCONFIGURATION, &configuration);
    569 }
    570 
    571 int usb_device_set_interface(struct usb_device *device, unsigned int interface,
    572                             unsigned int alt_setting)
    573 {
    574     struct usbdevfs_setinterface ctl;
    575 
    576     ctl.interface = interface;
    577     ctl.altsetting = alt_setting;
    578     return ioctl(device->fd, USBDEVFS_SETINTERFACE, &ctl);
    579 }
    580 
    581 int usb_device_control_transfer(struct usb_device *device,
    582                             int requestType,
    583                             int request,
    584                             int value,
    585                             int index,
    586                             void* buffer,
    587                             int length,
    588                             unsigned int timeout)
    589 {
    590     struct usbdevfs_ctrltransfer  ctrl;
    591 
    592     // this usually requires read/write permission
    593     if (!usb_device_reopen_writeable(device))
    594         return -1;
    595 
    596     memset(&ctrl, 0, sizeof(ctrl));
    597     ctrl.bRequestType = requestType;
    598     ctrl.bRequest = request;
    599     ctrl.wValue = value;
    600     ctrl.wIndex = index;
    601     ctrl.wLength = length;
    602     ctrl.data = buffer;
    603     ctrl.timeout = timeout;
    604     return ioctl(device->fd, USBDEVFS_CONTROL, &ctrl);
    605 }
    606 
    607 int usb_device_bulk_transfer(struct usb_device *device,
    608                             int endpoint,
    609                             void* buffer,
    610                             unsigned int length,
    611                             unsigned int timeout)
    612 {
    613     struct usbdevfs_bulktransfer  ctrl;
    614 
    615     // need to limit request size to avoid EINVAL
    616     if (length > MAX_USBFS_BUFFER_SIZE)
    617         length = MAX_USBFS_BUFFER_SIZE;
    618 
    619     memset(&ctrl, 0, sizeof(ctrl));
    620     ctrl.ep = endpoint;
    621     ctrl.len = length;
    622     ctrl.data = buffer;
    623     ctrl.timeout = timeout;
    624     return ioctl(device->fd, USBDEVFS_BULK, &ctrl);
    625 }
    626 
    627 int usb_device_reset(struct usb_device *device)
    628 {
    629     return ioctl(device->fd, USBDEVFS_RESET);
    630 }
    631 
    632 struct usb_request *usb_request_new(struct usb_device *dev,
    633         const struct usb_endpoint_descriptor *ep_desc)
    634 {
    635     struct usbdevfs_urb *urb = calloc(1, sizeof(struct usbdevfs_urb));
    636     if (!urb)
    637         return NULL;
    638 
    639     if ((ep_desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_BULK)
    640         urb->type = USBDEVFS_URB_TYPE_BULK;
    641     else if ((ep_desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_INT)
    642         urb->type = USBDEVFS_URB_TYPE_INTERRUPT;
    643     else {
    644         D("Unsupported endpoint type %d", ep_desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK);
    645         free(urb);
    646         return NULL;
    647     }
    648     urb->endpoint = ep_desc->bEndpointAddress;
    649 
    650     struct usb_request *req = calloc(1, sizeof(struct usb_request));
    651     if (!req) {
    652         free(urb);
    653         return NULL;
    654     }
    655 
    656     req->dev = dev;
    657     req->max_packet_size = __le16_to_cpu(ep_desc->wMaxPacketSize);
    658     req->private_data = urb;
    659     req->endpoint = urb->endpoint;
    660     urb->usercontext = req;
    661 
    662     return req;
    663 }
    664 
    665 void usb_request_free(struct usb_request *req)
    666 {
    667     free(req->private_data);
    668     free(req);
    669 }
    670 
    671 int usb_request_queue(struct usb_request *req)
    672 {
    673     struct usbdevfs_urb *urb = (struct usbdevfs_urb*)req->private_data;
    674     int res;
    675 
    676     urb->status = -1;
    677     urb->buffer = req->buffer;
    678     // need to limit request size to avoid EINVAL
    679     if (req->buffer_length > MAX_USBFS_BUFFER_SIZE)
    680         urb->buffer_length = MAX_USBFS_BUFFER_SIZE;
    681     else
    682         urb->buffer_length = req->buffer_length;
    683 
    684     do {
    685         res = ioctl(req->dev->fd, USBDEVFS_SUBMITURB, urb);
    686     } while((res < 0) && (errno == EINTR));
    687 
    688     return res;
    689 }
    690 
    691 struct usb_request *usb_request_wait(struct usb_device *dev, int timeoutMillis)
    692 {
    693     // Poll until a request becomes available if there is a timeout
    694     if (timeoutMillis > 0) {
    695         struct pollfd p = {.fd = dev->fd, .events = POLLOUT, .revents = 0};
    696 
    697         int res = poll(&p, 1, timeoutMillis);
    698 
    699         if (res != 1 || p.revents != POLLOUT) {
    700             D("[ poll - event %d, error %d]\n", p.revents, errno);
    701             return NULL;
    702         }
    703     }
    704 
    705     // Read the request. This should usually succeed as we polled before, but it can fail e.g. when
    706     // two threads are reading usb requests at the same time and only a single request is available.
    707     struct usbdevfs_urb *urb = NULL;
    708     int res = TEMP_FAILURE_RETRY(ioctl(dev->fd, timeoutMillis == -1 ? USBDEVFS_REAPURB :
    709                                        USBDEVFS_REAPURBNDELAY, &urb));
    710     D("%s returned %d\n", timeoutMillis == -1 ? "USBDEVFS_REAPURB" : "USBDEVFS_REAPURBNDELAY", res);
    711 
    712     if (res < 0) {
    713         D("[ reap urb - error %d]\n", errno);
    714         return NULL;
    715     } else {
    716         D("[ urb @%p status = %d, actual = %d ]\n", urb, urb->status, urb->actual_length);
    717 
    718         struct usb_request *req = (struct usb_request*)urb->usercontext;
    719         req->actual_length = urb->actual_length;
    720 
    721         return req;
    722     }
    723 }
    724 
    725 int usb_request_cancel(struct usb_request *req)
    726 {
    727     struct usbdevfs_urb *urb = ((struct usbdevfs_urb*)req->private_data);
    728     return ioctl(req->dev->fd, USBDEVFS_DISCARDURB, urb);
    729 }
    730