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 #define MAX_USBFS_WD_COUNT      10
     68 
     69 struct usb_host_context {
     70     int                         fd;
     71     usb_device_added_cb         cb_added;
     72     usb_device_removed_cb       cb_removed;
     73     void                        *data;
     74     int                         wds[MAX_USBFS_WD_COUNT];
     75     int                         wdd;
     76     int                         wddbus;
     77 };
     78 
     79 #define MAX_DESCRIPTORS_LENGTH 4096
     80 
     81 struct usb_device {
     82     char dev_name[64];
     83     unsigned char desc[MAX_DESCRIPTORS_LENGTH];
     84     int desc_length;
     85     int fd;
     86     int writeable;
     87 };
     88 
     89 static inline int badname(const char *name)
     90 {
     91     while(*name) {
     92         if(!isdigit(*name++)) return 1;
     93     }
     94     return 0;
     95 }
     96 
     97 static int find_existing_devices_bus(char *busname,
     98                                      usb_device_added_cb added_cb,
     99                                      void *client_data)
    100 {
    101     char devname[32];
    102     DIR *devdir;
    103     struct dirent *de;
    104     int done = 0;
    105 
    106     devdir = opendir(busname);
    107     if(devdir == 0) return 0;
    108 
    109     while ((de = readdir(devdir)) && !done) {
    110         if(badname(de->d_name)) continue;
    111 
    112         snprintf(devname, sizeof(devname), "%s/%s", busname, de->d_name);
    113         done = added_cb(devname, client_data);
    114     } // end of devdir while
    115     closedir(devdir);
    116 
    117     return done;
    118 }
    119 
    120 /* returns true if one of the callbacks indicates we are done */
    121 static int find_existing_devices(usb_device_added_cb added_cb,
    122                                   void *client_data)
    123 {
    124     char busname[32];
    125     DIR *busdir;
    126     struct dirent *de;
    127     int done = 0;
    128 
    129     busdir = opendir(USB_FS_DIR);
    130     if(busdir == 0) return 0;
    131 
    132     while ((de = readdir(busdir)) != 0 && !done) {
    133         if(badname(de->d_name)) continue;
    134 
    135         snprintf(busname, sizeof(busname), USB_FS_DIR "/%s", de->d_name);
    136         done = find_existing_devices_bus(busname, added_cb,
    137                                          client_data);
    138     } //end of busdir while
    139     closedir(busdir);
    140 
    141     return done;
    142 }
    143 
    144 static void watch_existing_subdirs(struct usb_host_context *context,
    145                                    int *wds, int wd_count)
    146 {
    147     char path[100];
    148     int i, ret;
    149 
    150     wds[0] = inotify_add_watch(context->fd, USB_FS_DIR, IN_CREATE | IN_DELETE);
    151     if (wds[0] < 0)
    152         return;
    153 
    154     /* watch existing subdirectories of USB_FS_DIR */
    155     for (i = 1; i < wd_count; i++) {
    156         snprintf(path, sizeof(path), USB_FS_DIR "/%03d", i);
    157         ret = inotify_add_watch(context->fd, path, IN_CREATE | IN_DELETE);
    158         if (ret >= 0)
    159             wds[i] = ret;
    160     }
    161 }
    162 
    163 struct usb_host_context *usb_host_init()
    164 {
    165     struct usb_host_context *context = calloc(1, sizeof(struct usb_host_context));
    166     if (!context) {
    167         fprintf(stderr, "out of memory in usb_host_context\n");
    168         return NULL;
    169     }
    170     context->fd = inotify_init();
    171     if (context->fd < 0) {
    172         fprintf(stderr, "inotify_init failed\n");
    173         free(context);
    174         return NULL;
    175     }
    176     return context;
    177 }
    178 
    179 void usb_host_cleanup(struct usb_host_context *context)
    180 {
    181     close(context->fd);
    182     free(context);
    183 }
    184 
    185 int usb_host_get_fd(struct usb_host_context *context)
    186 {
    187     return context->fd;
    188 } /* usb_host_get_fd() */
    189 
    190 int usb_host_load(struct usb_host_context *context,
    191                   usb_device_added_cb added_cb,
    192                   usb_device_removed_cb removed_cb,
    193                   usb_discovery_done_cb discovery_done_cb,
    194                   void *client_data)
    195 {
    196     int done = 0;
    197     int i;
    198 
    199     context->cb_added = added_cb;
    200     context->cb_removed = removed_cb;
    201     context->data = client_data;
    202 
    203     D("Created device discovery thread\n");
    204 
    205     /* watch for files added and deleted within USB_FS_DIR */
    206     context->wddbus = -1;
    207     for (i = 0; i < MAX_USBFS_WD_COUNT; i++)
    208         context->wds[i] = -1;
    209 
    210     /* watch the root for new subdirectories */
    211     context->wdd = inotify_add_watch(context->fd, DEV_DIR, IN_CREATE | IN_DELETE);
    212     if (context->wdd < 0) {
    213         fprintf(stderr, "inotify_add_watch failed\n");
    214         if (discovery_done_cb)
    215             discovery_done_cb(client_data);
    216         return done;
    217     }
    218 
    219     watch_existing_subdirs(context, context->wds, MAX_USBFS_WD_COUNT);
    220 
    221     /* check for existing devices first, after we have inotify set up */
    222     done = find_existing_devices(added_cb, client_data);
    223     if (discovery_done_cb)
    224         done |= discovery_done_cb(client_data);
    225 
    226     return done;
    227 } /* usb_host_load() */
    228 
    229 int usb_host_read_event(struct usb_host_context *context)
    230 {
    231     struct inotify_event* event;
    232     char event_buf[512];
    233     char path[100];
    234     int i, ret, done = 0;
    235     int offset = 0;
    236     int wd;
    237 
    238     ret = read(context->fd, event_buf, sizeof(event_buf));
    239     if (ret >= (int)sizeof(struct inotify_event)) {
    240         while (offset < ret && !done) {
    241             event = (struct inotify_event*)&event_buf[offset];
    242             done = 0;
    243             wd = event->wd;
    244             if (wd == context->wdd) {
    245                 if ((event->mask & IN_CREATE) && !strcmp(event->name, "bus")) {
    246                     context->wddbus = inotify_add_watch(context->fd, DEV_BUS_DIR, IN_CREATE | IN_DELETE);
    247                     if (context->wddbus < 0) {
    248                         done = 1;
    249                     } else {
    250                         watch_existing_subdirs(context, context->wds, MAX_USBFS_WD_COUNT);
    251                         done = find_existing_devices(context->cb_added, context->data);
    252                     }
    253                 }
    254             } else if (wd == context->wddbus) {
    255                 if ((event->mask & IN_CREATE) && !strcmp(event->name, "usb")) {
    256                     watch_existing_subdirs(context, context->wds, MAX_USBFS_WD_COUNT);
    257                     done = find_existing_devices(context->cb_added, context->data);
    258                 } else if ((event->mask & IN_DELETE) && !strcmp(event->name, "usb")) {
    259                     for (i = 0; i < MAX_USBFS_WD_COUNT; i++) {
    260                         if (context->wds[i] >= 0) {
    261                             inotify_rm_watch(context->fd, context->wds[i]);
    262                             context->wds[i] = -1;
    263                         }
    264                     }
    265                 }
    266             } else if (wd == context->wds[0]) {
    267                 i = atoi(event->name);
    268                 snprintf(path, sizeof(path), USB_FS_DIR "/%s", event->name);
    269                 D("%s subdirectory %s: index: %d\n", (event->mask & IN_CREATE) ?
    270                         "new" : "gone", path, i);
    271                 if (i > 0 && i < MAX_USBFS_WD_COUNT) {
    272                     int local_ret = 0;
    273                     if (event->mask & IN_CREATE) {
    274                         local_ret = inotify_add_watch(context->fd, path,
    275                                 IN_CREATE | IN_DELETE);
    276                         if (local_ret >= 0)
    277                             context->wds[i] = local_ret;
    278                         done = find_existing_devices_bus(path, context->cb_added,
    279                                 context->data);
    280                     } else if (event->mask & IN_DELETE) {
    281                         inotify_rm_watch(context->fd, context->wds[i]);
    282                         context->wds[i] = -1;
    283                     }
    284                 }
    285             } else {
    286                 for (i = 1; (i < MAX_USBFS_WD_COUNT) && !done; i++) {
    287                     if (wd == context->wds[i]) {
    288                         snprintf(path, sizeof(path), USB_FS_DIR "/%03d/%s", i, event->name);
    289                         if (event->mask == IN_CREATE) {
    290                             D("new device %s\n", path);
    291                             done = context->cb_added(path, context->data);
    292                         } else if (event->mask == IN_DELETE) {
    293                             D("gone device %s\n", path);
    294                             done = context->cb_removed(path, context->data);
    295                         }
    296                     }
    297                 }
    298             }
    299 
    300             offset += sizeof(struct inotify_event) + event->len;
    301         }
    302     }
    303 
    304     return done;
    305 } /* usb_host_read_event() */
    306 
    307 void usb_host_run(struct usb_host_context *context,
    308                   usb_device_added_cb added_cb,
    309                   usb_device_removed_cb removed_cb,
    310                   usb_discovery_done_cb discovery_done_cb,
    311                   void *client_data)
    312 {
    313     int done;
    314 
    315     done = usb_host_load(context, added_cb, removed_cb, discovery_done_cb, client_data);
    316 
    317     while (!done) {
    318 
    319         done = usb_host_read_event(context);
    320     }
    321 } /* usb_host_run() */
    322 
    323 struct usb_device *usb_device_open(const char *dev_name)
    324 {
    325     int fd, attempts, writeable = 1;
    326     const int SLEEP_BETWEEN_ATTEMPTS_US = 100000; /* 100 ms */
    327     const int64_t MAX_ATTEMPTS = 10;              /* 1s */
    328     D("usb_device_open %s\n", dev_name);
    329 
    330     /* Hack around waiting for permissions to be set on the USB device node.
    331      * Should really be a timeout instead of attempt count, and should REALLY
    332      * be triggered by the perm change via inotify rather than polling.
    333      */
    334     for (attempts = 0; attempts < MAX_ATTEMPTS; ++attempts) {
    335         if (access(dev_name, R_OK | W_OK) == 0) {
    336             writeable = 1;
    337             break;
    338         } else {
    339             if (access(dev_name, R_OK) == 0) {
    340                 /* double check that write permission didn't just come along too! */
    341                 writeable = (access(dev_name, R_OK | W_OK) == 0);
    342                 break;
    343             }
    344         }
    345         /* not writeable or readable - sleep and try again. */
    346         D("usb_device_open no access sleeping\n");
    347         usleep(SLEEP_BETWEEN_ATTEMPTS_US);
    348     }
    349 
    350     if (writeable) {
    351         fd = open(dev_name, O_RDWR);
    352     } else {
    353         fd = open(dev_name, O_RDONLY);
    354     }
    355     D("usb_device_open open returned %d writeable %d errno %d\n", fd, writeable, errno);
    356     if (fd < 0) return NULL;
    357 
    358     struct usb_device* result = usb_device_new(dev_name, fd);
    359     if (result)
    360         result->writeable = writeable;
    361     return result;
    362 }
    363 
    364 void usb_device_close(struct usb_device *device)
    365 {
    366     close(device->fd);
    367     free(device);
    368 }
    369 
    370 struct usb_device *usb_device_new(const char *dev_name, int fd)
    371 {
    372     struct usb_device *device = calloc(1, sizeof(struct usb_device));
    373     int length;
    374 
    375     D("usb_device_new %s fd: %d\n", dev_name, fd);
    376 
    377     if (lseek(fd, 0, SEEK_SET) != 0)
    378         goto failed;
    379     length = read(fd, device->desc, sizeof(device->desc));
    380     D("usb_device_new read returned %d errno %d\n", length, errno);
    381     if (length < 0)
    382         goto failed;
    383 
    384     strncpy(device->dev_name, dev_name, sizeof(device->dev_name) - 1);
    385     device->fd = fd;
    386     device->desc_length = length;
    387     // assume we are writeable, since usb_device_get_fd will only return writeable fds
    388     device->writeable = 1;
    389     return device;
    390 
    391 failed:
    392     // TODO It would be more appropriate to have callers do this
    393     // since this function doesn't "own" this file descriptor.
    394     close(fd);
    395     free(device);
    396     return NULL;
    397 }
    398 
    399 static int usb_device_reopen_writeable(struct usb_device *device)
    400 {
    401     if (device->writeable)
    402         return 1;
    403 
    404     int fd = open(device->dev_name, O_RDWR);
    405     if (fd >= 0) {
    406         close(device->fd);
    407         device->fd = fd;
    408         device->writeable = 1;
    409         return 1;
    410     }
    411     D("usb_device_reopen_writeable failed errno %d\n", errno);
    412     return 0;
    413 }
    414 
    415 int usb_device_get_fd(struct usb_device *device)
    416 {
    417     if (!usb_device_reopen_writeable(device))
    418         return -1;
    419     return device->fd;
    420 }
    421 
    422 const char* usb_device_get_name(struct usb_device *device)
    423 {
    424     return device->dev_name;
    425 }
    426 
    427 int usb_device_get_unique_id(struct usb_device *device)
    428 {
    429     int bus = 0, dev = 0;
    430     sscanf(device->dev_name, USB_FS_ID_SCANNER, &bus, &dev);
    431     return bus * 1000 + dev;
    432 }
    433 
    434 int usb_device_get_unique_id_from_name(const char* name)
    435 {
    436     int bus = 0, dev = 0;
    437     sscanf(name, USB_FS_ID_SCANNER, &bus, &dev);
    438     return bus * 1000 + dev;
    439 }
    440 
    441 char* usb_device_get_name_from_unique_id(int id)
    442 {
    443     int bus = id / 1000;
    444     int dev = id % 1000;
    445     char* result = (char *)calloc(1, strlen(USB_FS_ID_FORMAT));
    446     snprintf(result, strlen(USB_FS_ID_FORMAT) - 1, USB_FS_ID_FORMAT, bus, dev);
    447     return result;
    448 }
    449 
    450 uint16_t usb_device_get_vendor_id(struct usb_device *device)
    451 {
    452     struct usb_device_descriptor* desc = (struct usb_device_descriptor*)device->desc;
    453     return __le16_to_cpu(desc->idVendor);
    454 }
    455 
    456 uint16_t usb_device_get_product_id(struct usb_device *device)
    457 {
    458     struct usb_device_descriptor* desc = (struct usb_device_descriptor*)device->desc;
    459     return __le16_to_cpu(desc->idProduct);
    460 }
    461 
    462 const struct usb_device_descriptor* usb_device_get_device_descriptor(struct usb_device* device) {
    463     return (struct usb_device_descriptor*)device->desc;
    464 }
    465 
    466 size_t usb_device_get_descriptors_length(const struct usb_device* device) {
    467     return device->desc_length;
    468 }
    469 
    470 const unsigned char* usb_device_get_raw_descriptors(const struct usb_device* device) {
    471     return device->desc;
    472 }
    473 
    474 /* Returns a USB descriptor string for the given string ID.
    475  * Return value: < 0 on error.  0 on success.
    476  * The string is returned in ucs2_out in USB-native UCS-2 encoding.
    477  *
    478  * parameters:
    479  *  id - the string descriptor index.
    480  *  timeout - in milliseconds (see Documentation/driver-api/usb/usb.rst)
    481  *  ucs2_out - Must point to null on call.
    482  *             Will be filled in with a buffer on success.
    483  *             If this is non-null on return, it must be free()d.
    484  *  response_size - size, in bytes, of ucs-2 string in ucs2_out.
    485  *                  The size isn't guaranteed to include null termination.
    486  * Call free() to free the result when you are done with it.
    487  */
    488 int usb_device_get_string_ucs2(struct usb_device* device, int id, int timeout, void** ucs2_out,
    489                                size_t* response_size) {
    490     __u16 languages[MAX_STRING_DESCRIPTOR_LENGTH / sizeof(__u16)];
    491     char response[MAX_STRING_DESCRIPTOR_LENGTH];
    492     int result;
    493     int languageCount = 0;
    494 
    495     if (id == 0) return -1;
    496     if (*ucs2_out != NULL) return -1;
    497 
    498     memset(languages, 0, sizeof(languages));
    499 
    500     // read list of supported languages
    501     result = usb_device_control_transfer(device,
    502             USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE, USB_REQ_GET_DESCRIPTOR,
    503             (USB_DT_STRING << 8) | 0, 0, languages, sizeof(languages),
    504             timeout);
    505     if (result > 0)
    506         languageCount = (result - 2) / 2;
    507 
    508     for (int i = 1; i <= languageCount; i++) {
    509         memset(response, 0, sizeof(response));
    510 
    511         result = usb_device_control_transfer(
    512             device, USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE, USB_REQ_GET_DESCRIPTOR,
    513             (USB_DT_STRING << 8) | id, languages[i], response, sizeof(response), timeout);
    514         if (result >= 2) {  // string contents begin at offset 2.
    515             int descriptor_len = result - 2;
    516             char* out = malloc(descriptor_len + 3);
    517             if (out == NULL) {
    518                 return -1;
    519             }
    520             memcpy(out, response + 2, descriptor_len);
    521             // trail with three additional NULLs, so that there's guaranteed
    522             // to be a UCS-2 NULL character beyond whatever USB returned.
    523             // The returned string length is still just what USB returned.
    524             memset(out + descriptor_len, '\0', 3);
    525             *ucs2_out = (void*)out;
    526             *response_size = descriptor_len;
    527             return 0;
    528         }
    529     }
    530     return -1;
    531 }
    532 
    533 /* Warning: previously this blindly returned the lower 8 bits of
    534  * every UCS-2 character in a USB descriptor.  Now it will replace
    535  * values > 127 with ascii '?'.
    536  */
    537 char* usb_device_get_string(struct usb_device* device, int id, int timeout) {
    538     char* ascii_string = NULL;
    539     size_t raw_string_len = 0;
    540     size_t i;
    541     if (usb_device_get_string_ucs2(device, id, timeout, (void**)&ascii_string, &raw_string_len) < 0)
    542         return NULL;
    543     if (ascii_string == NULL) return NULL;
    544     for (i = 0; i < raw_string_len / 2; ++i) {
    545         // wire format for USB is always little-endian.
    546         char lower = ascii_string[2 * i];
    547         char upper = ascii_string[2 * i + 1];
    548         if (upper || (lower & 0x80)) {
    549             ascii_string[i] = '?';
    550         } else {
    551             ascii_string[i] = lower;
    552         }
    553     }
    554     ascii_string[i] = '\0';
    555     return ascii_string;
    556 }
    557 
    558 char* usb_device_get_manufacturer_name(struct usb_device *device, int timeout)
    559 {
    560     struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc;
    561     return usb_device_get_string(device, desc->iManufacturer, timeout);
    562 }
    563 
    564 char* usb_device_get_product_name(struct usb_device *device, int timeout)
    565 {
    566     struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc;
    567     return usb_device_get_string(device, desc->iProduct, timeout);
    568 }
    569 
    570 int usb_device_get_version(struct usb_device *device)
    571 {
    572     struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc;
    573     return desc->bcdUSB;
    574 }
    575 
    576 char* usb_device_get_serial(struct usb_device *device, int timeout)
    577 {
    578     struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc;
    579     return usb_device_get_string(device, desc->iSerialNumber, timeout);
    580 }
    581 
    582 int usb_device_is_writeable(struct usb_device *device)
    583 {
    584     return device->writeable;
    585 }
    586 
    587 void usb_descriptor_iter_init(struct usb_device *device, struct usb_descriptor_iter *iter)
    588 {
    589     iter->config = device->desc;
    590     iter->config_end = device->desc + device->desc_length;
    591     iter->curr_desc = device->desc;
    592 }
    593 
    594 struct usb_descriptor_header *usb_descriptor_iter_next(struct usb_descriptor_iter *iter)
    595 {
    596     struct usb_descriptor_header* next;
    597     if (iter->curr_desc >= iter->config_end)
    598         return NULL;
    599     next = (struct usb_descriptor_header*)iter->curr_desc;
    600     iter->curr_desc += next->bLength;
    601     return next;
    602 }
    603 
    604 int usb_device_claim_interface(struct usb_device *device, unsigned int interface)
    605 {
    606     return ioctl(device->fd, USBDEVFS_CLAIMINTERFACE, &interface);
    607 }
    608 
    609 int usb_device_release_interface(struct usb_device *device, unsigned int interface)
    610 {
    611     return ioctl(device->fd, USBDEVFS_RELEASEINTERFACE, &interface);
    612 }
    613 
    614 int usb_device_connect_kernel_driver(struct usb_device *device,
    615         unsigned int interface, int connect)
    616 {
    617     struct usbdevfs_ioctl ctl;
    618 
    619     ctl.ifno = interface;
    620     ctl.ioctl_code = (connect ? USBDEVFS_CONNECT : USBDEVFS_DISCONNECT);
    621     ctl.data = NULL;
    622     return ioctl(device->fd, USBDEVFS_IOCTL, &ctl);
    623 }
    624 
    625 int usb_device_set_configuration(struct usb_device *device, int configuration)
    626 {
    627     return ioctl(device->fd, USBDEVFS_SETCONFIGURATION, &configuration);
    628 }
    629 
    630 int usb_device_set_interface(struct usb_device *device, unsigned int interface,
    631                             unsigned int alt_setting)
    632 {
    633     struct usbdevfs_setinterface ctl;
    634 
    635     ctl.interface = interface;
    636     ctl.altsetting = alt_setting;
    637     return ioctl(device->fd, USBDEVFS_SETINTERFACE, &ctl);
    638 }
    639 
    640 int usb_device_control_transfer(struct usb_device *device,
    641                             int requestType,
    642                             int request,
    643                             int value,
    644                             int index,
    645                             void* buffer,
    646                             int length,
    647                             unsigned int timeout)
    648 {
    649     struct usbdevfs_ctrltransfer  ctrl;
    650 
    651     // this usually requires read/write permission
    652     if (!usb_device_reopen_writeable(device))
    653         return -1;
    654 
    655     memset(&ctrl, 0, sizeof(ctrl));
    656     ctrl.bRequestType = requestType;
    657     ctrl.bRequest = request;
    658     ctrl.wValue = value;
    659     ctrl.wIndex = index;
    660     ctrl.wLength = length;
    661     ctrl.data = buffer;
    662     ctrl.timeout = timeout;
    663     return ioctl(device->fd, USBDEVFS_CONTROL, &ctrl);
    664 }
    665 
    666 int usb_device_bulk_transfer(struct usb_device *device,
    667                             int endpoint,
    668                             void* buffer,
    669                             unsigned int length,
    670                             unsigned int timeout)
    671 {
    672     struct usbdevfs_bulktransfer  ctrl;
    673 
    674     memset(&ctrl, 0, sizeof(ctrl));
    675     ctrl.ep = endpoint;
    676     ctrl.len = length;
    677     ctrl.data = buffer;
    678     ctrl.timeout = timeout;
    679     return ioctl(device->fd, USBDEVFS_BULK, &ctrl);
    680 }
    681 
    682 int usb_device_reset(struct usb_device *device)
    683 {
    684     return ioctl(device->fd, USBDEVFS_RESET);
    685 }
    686 
    687 struct usb_request *usb_request_new(struct usb_device *dev,
    688         const struct usb_endpoint_descriptor *ep_desc)
    689 {
    690     struct usbdevfs_urb *urb = calloc(1, sizeof(struct usbdevfs_urb));
    691     if (!urb)
    692         return NULL;
    693 
    694     if ((ep_desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_BULK)
    695         urb->type = USBDEVFS_URB_TYPE_BULK;
    696     else if ((ep_desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_INT)
    697         urb->type = USBDEVFS_URB_TYPE_INTERRUPT;
    698     else {
    699         D("Unsupported endpoint type %d", ep_desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK);
    700         free(urb);
    701         return NULL;
    702     }
    703     urb->endpoint = ep_desc->bEndpointAddress;
    704 
    705     struct usb_request *req = calloc(1, sizeof(struct usb_request));
    706     if (!req) {
    707         free(urb);
    708         return NULL;
    709     }
    710 
    711     req->dev = dev;
    712     req->max_packet_size = __le16_to_cpu(ep_desc->wMaxPacketSize);
    713     req->private_data = urb;
    714     req->endpoint = urb->endpoint;
    715     urb->usercontext = req;
    716 
    717     return req;
    718 }
    719 
    720 void usb_request_free(struct usb_request *req)
    721 {
    722     free(req->private_data);
    723     free(req);
    724 }
    725 
    726 int usb_request_queue(struct usb_request *req)
    727 {
    728     struct usbdevfs_urb *urb = (struct usbdevfs_urb*)req->private_data;
    729     int res;
    730 
    731     urb->status = -1;
    732     urb->buffer = req->buffer;
    733     urb->buffer_length = req->buffer_length;
    734 
    735     do {
    736         res = ioctl(req->dev->fd, USBDEVFS_SUBMITURB, urb);
    737     } while((res < 0) && (errno == EINTR));
    738 
    739     return res;
    740 }
    741 
    742 struct usb_request *usb_request_wait(struct usb_device *dev, int timeoutMillis)
    743 {
    744     // Poll until a request becomes available if there is a timeout
    745     if (timeoutMillis > 0) {
    746         struct pollfd p = {.fd = dev->fd, .events = POLLOUT, .revents = 0};
    747 
    748         int res = poll(&p, 1, timeoutMillis);
    749 
    750         if (res != 1 || p.revents != POLLOUT) {
    751             D("[ poll - event %d, error %d]\n", p.revents, errno);
    752             return NULL;
    753         }
    754     }
    755 
    756     // Read the request. This should usually succeed as we polled before, but it can fail e.g. when
    757     // two threads are reading usb requests at the same time and only a single request is available.
    758     struct usbdevfs_urb *urb = NULL;
    759     int res = TEMP_FAILURE_RETRY(ioctl(dev->fd, timeoutMillis == -1 ? USBDEVFS_REAPURB :
    760                                        USBDEVFS_REAPURBNDELAY, &urb));
    761     D("%s returned %d\n", timeoutMillis == -1 ? "USBDEVFS_REAPURB" : "USBDEVFS_REAPURBNDELAY", res);
    762 
    763     if (res < 0) {
    764         D("[ reap urb - error %d]\n", errno);
    765         return NULL;
    766     } else {
    767         D("[ urb @%p status = %d, actual = %d ]\n", urb, urb->status, urb->actual_length);
    768 
    769         struct usb_request *req = (struct usb_request*)urb->usercontext;
    770         req->actual_length = urb->actual_length;
    771 
    772         return req;
    773     }
    774 }
    775 
    776 int usb_request_cancel(struct usb_request *req)
    777 {
    778     struct usbdevfs_urb *urb = ((struct usbdevfs_urb*)req->private_data);
    779     return ioctl(req->dev->fd, USBDEVFS_DISCARDURB, urb);
    780 }
    781