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