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