usb_linux.c revision 13081c6915220db03886b177f1a8e0b2c63467c9
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *  * Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 *  * Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in
12 *    the documentation and/or other materials provided with the
13 *    distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
29#include <stdio.h>
30#include <stdlib.h>
31#include <unistd.h>
32#include <string.h>
33
34#include <sys/ioctl.h>
35#include <sys/stat.h>
36#include <sys/types.h>
37#include <dirent.h>
38#include <fcntl.h>
39#include <errno.h>
40#include <pthread.h>
41#include <ctype.h>
42
43#include <linux/usbdevice_fs.h>
44#include <linux/usbdevice_fs.h>
45#include <linux/version.h>
46#if LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 20)
47#include <linux/usb/ch9.h>
48#else
49#include <linux/usb_ch9.h>
50#endif
51#include <asm/byteorder.h>
52
53#include "usb.h"
54
55#define MAX_RETRIES 5
56
57#ifdef TRACE_USB
58#define DBG1(x...) fprintf(stderr, x)
59#define DBG(x...) fprintf(stderr, x)
60#else
61#define DBG(x...)
62#define DBG1(x...)
63#endif
64
65/* The max bulk size for linux is 16384 which is defined
66 * in drivers/usb/core/devio.c.
67 */
68#define MAX_USBFS_BULK_SIZE (16 * 1024)
69
70struct usb_handle
71{
72    char fname[64];
73    int desc;
74    unsigned char ep_in;
75    unsigned char ep_out;
76};
77
78static inline int badname(const char *name)
79{
80    while(*name) {
81        if(!isdigit(*name++)) return 1;
82    }
83    return 0;
84}
85
86static int check(void *_desc, int len, unsigned type, int size)
87{
88    unsigned char *desc = _desc;
89
90    if(len < size) return -1;
91    if(desc[0] < size) return -1;
92    if(desc[0] > len) return -1;
93    if(desc[1] != type) return -1;
94
95    return 0;
96}
97
98static int filter_usb_device(int fd, char *ptr, int len, int writable,
99                             ifc_match_func callback,
100                             int *ept_in_id, int *ept_out_id, int *ifc_id)
101{
102    struct usb_device_descriptor *dev;
103    struct usb_config_descriptor *cfg;
104    struct usb_interface_descriptor *ifc;
105    struct usb_endpoint_descriptor *ept;
106    struct usb_ifc_info info;
107
108    int in, out;
109    unsigned i;
110    unsigned e;
111
112    struct stat st;
113    int result;
114
115    if(check(ptr, len, USB_DT_DEVICE, USB_DT_DEVICE_SIZE))
116        return -1;
117    dev = (void*) ptr;
118    len -= dev->bLength;
119    ptr += dev->bLength;
120
121    if(check(ptr, len, USB_DT_CONFIG, USB_DT_CONFIG_SIZE))
122        return -1;
123    cfg = (void*) ptr;
124    len -= cfg->bLength;
125    ptr += cfg->bLength;
126
127    info.dev_vendor = dev->idVendor;
128    info.dev_product = dev->idProduct;
129    info.dev_class = dev->bDeviceClass;
130    info.dev_subclass = dev->bDeviceSubClass;
131    info.dev_protocol = dev->bDeviceProtocol;
132    info.writable = writable;
133
134    // read device serial number (if there is one)
135    info.serial_number[0] = 0;
136    if (dev->iSerialNumber) {
137        struct usbdevfs_ctrltransfer  ctrl;
138        __u16 buffer[128];
139
140        memset(buffer, 0, sizeof(buffer));
141
142        ctrl.bRequestType = USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE;
143        ctrl.bRequest = USB_REQ_GET_DESCRIPTOR;
144        ctrl.wValue = (USB_DT_STRING << 8) | dev->iSerialNumber;
145        ctrl.wIndex = 0;
146        ctrl.wLength = sizeof(buffer);
147        ctrl.data = buffer;
148	ctrl.timeout = 50;
149
150        result = ioctl(fd, USBDEVFS_CONTROL, &ctrl);
151        if (result > 0) {
152            int i;
153            // skip first word, and copy the rest to the serial string, changing shorts to bytes.
154            result /= 2;
155            for (i = 1; i < result; i++)
156                info.serial_number[i - 1] = buffer[i];
157            info.serial_number[i - 1] = 0;
158        }
159    }
160
161    /* We need to get a path that represents a particular port on a particular
162     * hub.  We are passed an fd that was obtained by opening an entry under
163     * /dev/bus/usb.  Unfortunately, the names of those entries change each
164     * time devices are plugged and unplugged.  So how to get a repeatable
165     * path?  udevadm provided the inspiration.  We can get the major and
166     * minor of the device file, read the symlink that can be found here:
167     *   /sys/dev/char/<major>:<minor>
168     * and then use the last element of that path.  As a concrete example, I
169     * have an Android device at /dev/bus/usb/001/027 so working with bash:
170     *   $ ls -l /dev/bus/usb/001/027
171     *   crw-rw-r-- 1 root plugdev 189, 26 Apr  9 11:03 /dev/bus/usb/001/027
172     *   $ ls -l /sys/dev/char/189:26
173     *   lrwxrwxrwx 1 root root 0 Apr  9 11:03 /sys/dev/char/189:26 ->
174     *           ../../devices/pci0000:00/0000:00:1a.7/usb1/1-4/1-4.2/1-4.2.3
175     * So our device_path would be 1-4.2.3 which says my device is connected
176     * to port 3 of a hub on port 2 of a hub on port 4 of bus 1 (per
177     * http://www.linux-usb.org/FAQ.html).
178     */
179    info.device_path[0] = '\0';
180    result = fstat(fd, &st);
181    if (!result && S_ISCHR(st.st_mode)) {
182        char cdev[128];
183        char link[256];
184        char *slash;
185        ssize_t link_len;
186        snprintf(cdev, sizeof(cdev), "/sys/dev/char/%d:%d",
187                 major(st.st_rdev), minor(st.st_rdev));
188        link_len = readlink(cdev, link, sizeof(link) - 1);
189        if (link_len > 0) {
190            link[link_len] = '\0';
191            slash = strrchr(link, '/');
192            if (slash)
193                snprintf(info.device_path, sizeof(info.device_path), "usb:%s", slash+1);
194        }
195    }
196
197    for(i = 0; i < cfg->bNumInterfaces; i++) {
198        if(check(ptr, len, USB_DT_INTERFACE, USB_DT_INTERFACE_SIZE))
199            return -1;
200        ifc = (void*) ptr;
201        len -= ifc->bLength;
202        ptr += ifc->bLength;
203
204        in = -1;
205        out = -1;
206        info.ifc_class = ifc->bInterfaceClass;
207        info.ifc_subclass = ifc->bInterfaceSubClass;
208        info.ifc_protocol = ifc->bInterfaceProtocol;
209
210        for(e = 0; e < ifc->bNumEndpoints; e++) {
211            if(check(ptr, len, USB_DT_ENDPOINT, USB_DT_ENDPOINT_SIZE))
212                return -1;
213            ept = (void*) ptr;
214            len -= ept->bLength;
215            ptr += ept->bLength;
216
217            if((ept->bmAttributes & 0x03) != 0x02)
218                continue;
219
220            if(ept->bEndpointAddress & 0x80) {
221                in = ept->bEndpointAddress;
222            } else {
223                out = ept->bEndpointAddress;
224            }
225        }
226
227        info.has_bulk_in = (in != -1);
228        info.has_bulk_out = (out != -1);
229
230        if(callback(&info) == 0) {
231            *ept_in_id = in;
232            *ept_out_id = out;
233            *ifc_id = ifc->bInterfaceNumber;
234            return 0;
235        }
236    }
237
238    return -1;
239}
240
241static usb_handle *find_usb_device(const char *base, ifc_match_func callback)
242{
243    usb_handle *usb = 0;
244    char busname[64], devname[64];
245    char desc[1024];
246    int n, in, out, ifc;
247
248    DIR *busdir, *devdir;
249    struct dirent *de;
250    int fd;
251    int writable;
252
253    busdir = opendir(base);
254    if(busdir == 0) return 0;
255
256    while((de = readdir(busdir)) && (usb == 0)) {
257        if(badname(de->d_name)) continue;
258
259        sprintf(busname, "%s/%s", base, de->d_name);
260        devdir = opendir(busname);
261        if(devdir == 0) continue;
262
263//        DBG("[ scanning %s ]\n", busname);
264        while((de = readdir(devdir)) && (usb == 0)) {
265
266            if(badname(de->d_name)) continue;
267            sprintf(devname, "%s/%s", busname, de->d_name);
268
269//            DBG("[ scanning %s ]\n", devname);
270            writable = 1;
271            if((fd = open(devname, O_RDWR)) < 0) {
272                // Check if we have read-only access, so we can give a helpful
273                // diagnostic like "adb devices" does.
274                writable = 0;
275                if((fd = open(devname, O_RDONLY)) < 0) {
276                    continue;
277                }
278            }
279
280            n = read(fd, desc, sizeof(desc));
281
282            if(filter_usb_device(fd, desc, n, writable, callback,
283                                 &in, &out, &ifc) == 0) {
284                usb = calloc(1, sizeof(usb_handle));
285                strcpy(usb->fname, devname);
286                usb->ep_in = in;
287                usb->ep_out = out;
288                usb->desc = fd;
289
290                n = ioctl(fd, USBDEVFS_CLAIMINTERFACE, &ifc);
291                if(n != 0) {
292                    close(fd);
293                    free(usb);
294                    usb = 0;
295                    continue;
296                }
297            } else {
298                close(fd);
299            }
300        }
301        closedir(devdir);
302    }
303    closedir(busdir);
304
305    return usb;
306}
307
308int usb_write(usb_handle *h, const void *_data, int len)
309{
310    unsigned char *data = (unsigned char*) _data;
311    unsigned count = 0;
312    struct usbdevfs_bulktransfer bulk;
313    int n;
314
315    if(h->ep_out == 0) {
316        return -1;
317    }
318
319    if(len == 0) {
320        bulk.ep = h->ep_out;
321        bulk.len = 0;
322        bulk.data = data;
323        bulk.timeout = 0;
324
325        n = ioctl(h->desc, USBDEVFS_BULK, &bulk);
326        if(n != 0) {
327            fprintf(stderr,"ERROR: n = %d, errno = %d (%s)\n",
328                    n, errno, strerror(errno));
329            return -1;
330        }
331        return 0;
332    }
333
334    while(len > 0) {
335        int xfer;
336        xfer = (len > MAX_USBFS_BULK_SIZE) ? MAX_USBFS_BULK_SIZE : len;
337
338        bulk.ep = h->ep_out;
339        bulk.len = xfer;
340        bulk.data = data;
341        bulk.timeout = 0;
342
343        n = ioctl(h->desc, USBDEVFS_BULK, &bulk);
344        if(n != xfer) {
345            DBG("ERROR: n = %d, errno = %d (%s)\n",
346                n, errno, strerror(errno));
347            return -1;
348        }
349
350        count += xfer;
351        len -= xfer;
352        data += xfer;
353    }
354
355    return count;
356}
357
358int usb_read(usb_handle *h, void *_data, int len)
359{
360    unsigned char *data = (unsigned char*) _data;
361    unsigned count = 0;
362    struct usbdevfs_bulktransfer bulk;
363    int n, retry;
364
365    if(h->ep_in == 0) {
366        return -1;
367    }
368
369    while(len > 0) {
370        int xfer = (len > MAX_USBFS_BULK_SIZE) ? MAX_USBFS_BULK_SIZE : len;
371
372        bulk.ep = h->ep_in;
373        bulk.len = xfer;
374        bulk.data = data;
375        bulk.timeout = 0;
376        retry = 0;
377
378        do{
379           DBG("[ usb read %d fd = %d], fname=%s\n", xfer, h->desc, h->fname);
380           n = ioctl(h->desc, USBDEVFS_BULK, &bulk);
381           DBG("[ usb read %d ] = %d, fname=%s, Retry %d \n", xfer, n, h->fname, retry);
382
383           if( n < 0 ) {
384            DBG1("ERROR: n = %d, errno = %d (%s)\n",n, errno, strerror(errno));
385            if ( ++retry > MAX_RETRIES ) return -1;
386            sleep( 1 );
387           }
388        }
389        while( n < 0 );
390
391        count += n;
392        len -= n;
393        data += n;
394
395        if(n < xfer) {
396            break;
397        }
398    }
399
400    return count;
401}
402
403void usb_kick(usb_handle *h)
404{
405    int fd;
406
407    fd = h->desc;
408    h->desc = -1;
409    if(fd >= 0) {
410        close(fd);
411        DBG("[ usb closed %d ]\n", fd);
412    }
413}
414
415int usb_close(usb_handle *h)
416{
417    int fd;
418
419    fd = h->desc;
420    h->desc = -1;
421    if(fd >= 0) {
422        close(fd);
423        DBG("[ usb closed %d ]\n", fd);
424    }
425
426    return 0;
427}
428
429usb_handle *usb_open(ifc_match_func callback)
430{
431    return find_usb_device("/dev/bus/usb", callback);
432}
433