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