usb_linux.c revision c840653efd8d05a33778d3e73c3521977564bde3
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/types.h>
36#include <dirent.h>
37#include <fcntl.h>
38#include <errno.h>
39#include <pthread.h>
40#include <ctype.h>
41
42#include <linux/usbdevice_fs.h>
43#include <linux/usbdevice_fs.h>
44#include <linux/version.h>
45#if LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 20)
46#include <linux/usb/ch9.h>
47#else
48#include <linux/usb_ch9.h>
49#endif
50#include <asm/byteorder.h>
51
52#include "usb.h"
53
54#define MAX_RETRIES 5
55
56#ifdef TRACE_USB
57#define DBG1(x...) fprintf(stderr, x)
58#define DBG(x...) fprintf(stderr, x)
59#else
60#define DBG(x...)
61#define DBG1(x...)
62#endif
63
64/* The max bulk size for linux is 16384 which is defined
65 * in drivers/usb/core/devio.c.
66 */
67#define MAX_USBFS_BULK_SIZE (16 * 1024)
68
69struct usb_handle
70{
71    char fname[64];
72    int desc;
73    unsigned char ep_in;
74    unsigned char ep_out;
75};
76
77static inline int badname(const char *name)
78{
79    while(*name) {
80        if(!isdigit(*name++)) return 1;
81    }
82    return 0;
83}
84
85static int check(void *_desc, int len, unsigned type, int size)
86{
87    unsigned char *desc = _desc;
88
89    if(len < size) return -1;
90    if(desc[0] < size) return -1;
91    if(desc[0] > len) return -1;
92    if(desc[1] != type) return -1;
93
94    return 0;
95}
96
97static int filter_usb_device(int fd, char *ptr, int len, int writable,
98                             ifc_match_func callback,
99                             int *ept_in_id, int *ept_out_id, int *ifc_id)
100{
101    struct usb_device_descriptor *dev;
102    struct usb_config_descriptor *cfg;
103    struct usb_interface_descriptor *ifc;
104    struct usb_endpoint_descriptor *ept;
105    struct usb_ifc_info info;
106
107    int in, out;
108    unsigned i;
109    unsigned e;
110
111    if(check(ptr, len, USB_DT_DEVICE, USB_DT_DEVICE_SIZE))
112        return -1;
113    dev = (void*) ptr;
114    len -= dev->bLength;
115    ptr += dev->bLength;
116
117    if(check(ptr, len, USB_DT_CONFIG, USB_DT_CONFIG_SIZE))
118        return -1;
119    cfg = (void*) ptr;
120    len -= cfg->bLength;
121    ptr += cfg->bLength;
122
123    info.dev_vendor = dev->idVendor;
124    info.dev_product = dev->idProduct;
125    info.dev_class = dev->bDeviceClass;
126    info.dev_subclass = dev->bDeviceSubClass;
127    info.dev_protocol = dev->bDeviceProtocol;
128    info.writable = writable;
129
130    // read device serial number (if there is one)
131    info.serial_number[0] = 0;
132    if (dev->iSerialNumber) {
133        struct usbdevfs_ctrltransfer  ctrl;
134        __u16 buffer[128];
135        int result;
136
137        memset(buffer, 0, sizeof(buffer));
138
139        ctrl.bRequestType = USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE;
140        ctrl.bRequest = USB_REQ_GET_DESCRIPTOR;
141        ctrl.wValue = (USB_DT_STRING << 8) | dev->iSerialNumber;
142        //language ID (en-us) for serial number string
143        ctrl.wIndex = 0x0409;
144        ctrl.wLength = sizeof(buffer);
145        ctrl.data = buffer;
146        ctrl.timeout = 50;
147
148        result = ioctl(fd, USBDEVFS_CONTROL, &ctrl);
149        if (result > 0) {
150            int i;
151            // skip first word, and copy the rest to the serial string, changing shorts to bytes.
152            result /= 2;
153            for (i = 1; i < result; i++)
154                info.serial_number[i - 1] = buffer[i];
155            info.serial_number[i - 1] = 0;
156        }
157    }
158
159    for(i = 0; i < cfg->bNumInterfaces; i++) {
160        if(check(ptr, len, USB_DT_INTERFACE, USB_DT_INTERFACE_SIZE))
161            return -1;
162        ifc = (void*) ptr;
163        len -= ifc->bLength;
164        ptr += ifc->bLength;
165
166        in = -1;
167        out = -1;
168        info.ifc_class = ifc->bInterfaceClass;
169        info.ifc_subclass = ifc->bInterfaceSubClass;
170        info.ifc_protocol = ifc->bInterfaceProtocol;
171
172        for(e = 0; e < ifc->bNumEndpoints; e++) {
173            if(check(ptr, len, USB_DT_ENDPOINT, USB_DT_ENDPOINT_SIZE))
174                return -1;
175            ept = (void*) ptr;
176            len -= ept->bLength;
177            ptr += ept->bLength;
178
179            if((ept->bmAttributes & 0x03) != 0x02)
180                continue;
181
182            if(ept->bEndpointAddress & 0x80) {
183                in = ept->bEndpointAddress;
184            } else {
185                out = ept->bEndpointAddress;
186            }
187        }
188
189        info.has_bulk_in = (in != -1);
190        info.has_bulk_out = (out != -1);
191
192        if(callback(&info) == 0) {
193            *ept_in_id = in;
194            *ept_out_id = out;
195            *ifc_id = ifc->bInterfaceNumber;
196            return 0;
197        }
198    }
199
200    return -1;
201}
202
203static usb_handle *find_usb_device(const char *base, ifc_match_func callback)
204{
205    usb_handle *usb = 0;
206    char busname[64], devname[64];
207    char desc[1024];
208    int n, in, out, ifc;
209
210    DIR *busdir, *devdir;
211    struct dirent *de;
212    int fd;
213    int writable;
214
215    busdir = opendir(base);
216    if(busdir == 0) return 0;
217
218    while((de = readdir(busdir)) && (usb == 0)) {
219        if(badname(de->d_name)) continue;
220
221        sprintf(busname, "%s/%s", base, de->d_name);
222        devdir = opendir(busname);
223        if(devdir == 0) continue;
224
225//        DBG("[ scanning %s ]\n", busname);
226        while((de = readdir(devdir)) && (usb == 0)) {
227
228            if(badname(de->d_name)) continue;
229            sprintf(devname, "%s/%s", busname, de->d_name);
230
231//            DBG("[ scanning %s ]\n", devname);
232            writable = 1;
233            if((fd = open(devname, O_RDWR)) < 0) {
234                // Check if we have read-only access, so we can give a helpful
235                // diagnostic like "adb devices" does.
236                writable = 0;
237                if((fd = open(devname, O_RDONLY)) < 0) {
238                    continue;
239                }
240            }
241
242            n = read(fd, desc, sizeof(desc));
243
244            if(filter_usb_device(fd, desc, n, writable, callback,
245                                 &in, &out, &ifc) == 0) {
246                usb = calloc(1, sizeof(usb_handle));
247                strcpy(usb->fname, devname);
248                usb->ep_in = in;
249                usb->ep_out = out;
250                usb->desc = fd;
251
252                n = ioctl(fd, USBDEVFS_CLAIMINTERFACE, &ifc);
253                if(n != 0) {
254                    close(fd);
255                    free(usb);
256                    usb = 0;
257                    continue;
258                }
259            } else {
260                close(fd);
261            }
262        }
263        closedir(devdir);
264    }
265    closedir(busdir);
266
267    return usb;
268}
269
270int usb_write(usb_handle *h, const void *_data, int len)
271{
272    unsigned char *data = (unsigned char*) _data;
273    unsigned count = 0;
274    struct usbdevfs_bulktransfer bulk;
275    int n;
276
277    if(h->ep_out == 0) {
278        return -1;
279    }
280
281    if(len == 0) {
282        bulk.ep = h->ep_out;
283        bulk.len = 0;
284        bulk.data = data;
285        bulk.timeout = 0;
286
287        n = ioctl(h->desc, USBDEVFS_BULK, &bulk);
288        if(n != 0) {
289            fprintf(stderr,"ERROR: n = %d, errno = %d (%s)\n",
290                    n, errno, strerror(errno));
291            return -1;
292        }
293        return 0;
294    }
295
296    while(len > 0) {
297        int xfer;
298        xfer = (len > MAX_USBFS_BULK_SIZE) ? MAX_USBFS_BULK_SIZE : len;
299
300        bulk.ep = h->ep_out;
301        bulk.len = xfer;
302        bulk.data = data;
303        bulk.timeout = 0;
304
305        n = ioctl(h->desc, USBDEVFS_BULK, &bulk);
306        if(n != xfer) {
307            DBG("ERROR: n = %d, errno = %d (%s)\n",
308                n, errno, strerror(errno));
309            return -1;
310        }
311
312        count += xfer;
313        len -= xfer;
314        data += xfer;
315    }
316
317    return count;
318}
319
320int usb_read(usb_handle *h, void *_data, int len)
321{
322    unsigned char *data = (unsigned char*) _data;
323    unsigned count = 0;
324    struct usbdevfs_bulktransfer bulk;
325    int n, retry;
326
327    if(h->ep_in == 0) {
328        return -1;
329    }
330
331    while(len > 0) {
332        int xfer = (len > MAX_USBFS_BULK_SIZE) ? MAX_USBFS_BULK_SIZE : len;
333
334        bulk.ep = h->ep_in;
335        bulk.len = xfer;
336        bulk.data = data;
337        bulk.timeout = 0;
338        retry = 0;
339
340        do{
341           DBG("[ usb read %d fd = %d], fname=%s\n", xfer, h->desc, h->fname);
342           n = ioctl(h->desc, USBDEVFS_BULK, &bulk);
343           DBG("[ usb read %d ] = %d, fname=%s, Retry %d \n", xfer, n, h->fname, retry);
344
345           if( n < 0 ) {
346            DBG1("ERROR: n = %d, errno = %d (%s)\n",n, errno, strerror(errno));
347            if ( ++retry > MAX_RETRIES ) return -1;
348            sleep( 1 );
349           }
350        }
351        while( n < 0 );
352
353        count += n;
354        len -= n;
355        data += n;
356
357        if(n < xfer) {
358            break;
359        }
360    }
361
362    return count;
363}
364
365void usb_kick(usb_handle *h)
366{
367    int fd;
368
369    fd = h->desc;
370    h->desc = -1;
371    if(fd >= 0) {
372        close(fd);
373        DBG("[ usb closed %d ]\n", fd);
374    }
375}
376
377int usb_close(usb_handle *h)
378{
379    int fd;
380
381    fd = h->desc;
382    h->desc = -1;
383    if(fd >= 0) {
384        close(fd);
385        DBG("[ usb closed %d ]\n", fd);
386    }
387
388    return 0;
389}
390
391usb_handle *usb_open(ifc_match_func callback)
392{
393    return find_usb_device("/dev/bus/usb", callback);
394}
395