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