usb_linux.c revision f8ff3a5ae21ce34f22928709cc6f992ff2fdd56e
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        // Keep it short enough because some bootloaders are borked if the URB len is > 255
135        // 128 is too big by 1.
136        __u16 buffer[127];
137        int result;
138
139        memset(buffer, 0, sizeof(buffer));
140
141        ctrl.bRequestType = USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE;
142        ctrl.bRequest = USB_REQ_GET_DESCRIPTOR;
143        ctrl.wValue = (USB_DT_STRING << 8) | dev->iSerialNumber;
144        //language ID (en-us) for serial number string
145        ctrl.wIndex = 0x0409;
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    for(i = 0; i < cfg->bNumInterfaces; i++) {
162        if(check(ptr, len, USB_DT_INTERFACE, USB_DT_INTERFACE_SIZE))
163            return -1;
164        ifc = (void*) ptr;
165        len -= ifc->bLength;
166        ptr += ifc->bLength;
167
168        in = -1;
169        out = -1;
170        info.ifc_class = ifc->bInterfaceClass;
171        info.ifc_subclass = ifc->bInterfaceSubClass;
172        info.ifc_protocol = ifc->bInterfaceProtocol;
173
174        for(e = 0; e < ifc->bNumEndpoints; e++) {
175            if(check(ptr, len, USB_DT_ENDPOINT, USB_DT_ENDPOINT_SIZE))
176                return -1;
177            ept = (void*) ptr;
178            len -= ept->bLength;
179            ptr += ept->bLength;
180
181            if((ept->bmAttributes & 0x03) != 0x02)
182                continue;
183
184            if(ept->bEndpointAddress & 0x80) {
185                in = ept->bEndpointAddress;
186            } else {
187                out = ept->bEndpointAddress;
188            }
189        }
190
191        info.has_bulk_in = (in != -1);
192        info.has_bulk_out = (out != -1);
193
194        if(callback(&info) == 0) {
195            *ept_in_id = in;
196            *ept_out_id = out;
197            *ifc_id = ifc->bInterfaceNumber;
198            return 0;
199        }
200    }
201
202    return -1;
203}
204
205static usb_handle *find_usb_device(const char *base, ifc_match_func callback)
206{
207    usb_handle *usb = 0;
208    char busname[64], devname[64];
209    char desc[1024];
210    int n, in, out, ifc;
211
212    DIR *busdir, *devdir;
213    struct dirent *de;
214    int fd;
215    int writable;
216
217    busdir = opendir(base);
218    if(busdir == 0) return 0;
219
220    while((de = readdir(busdir)) && (usb == 0)) {
221        if(badname(de->d_name)) continue;
222
223        sprintf(busname, "%s/%s", base, de->d_name);
224        devdir = opendir(busname);
225        if(devdir == 0) continue;
226
227//        DBG("[ scanning %s ]\n", busname);
228        while((de = readdir(devdir)) && (usb == 0)) {
229
230            if(badname(de->d_name)) continue;
231            sprintf(devname, "%s/%s", busname, de->d_name);
232
233//            DBG("[ scanning %s ]\n", devname);
234            writable = 1;
235            if((fd = open(devname, O_RDWR)) < 0) {
236                // Check if we have read-only access, so we can give a helpful
237                // diagnostic like "adb devices" does.
238                writable = 0;
239                if((fd = open(devname, O_RDONLY)) < 0) {
240                    continue;
241                }
242            }
243
244            n = read(fd, desc, sizeof(desc));
245
246            if(filter_usb_device(fd, desc, n, writable, callback,
247                                 &in, &out, &ifc) == 0) {
248                usb = calloc(1, sizeof(usb_handle));
249                strcpy(usb->fname, devname);
250                usb->ep_in = in;
251                usb->ep_out = out;
252                usb->desc = fd;
253
254                n = ioctl(fd, USBDEVFS_CLAIMINTERFACE, &ifc);
255                if(n != 0) {
256                    close(fd);
257                    free(usb);
258                    usb = 0;
259                    continue;
260                }
261            } else {
262                close(fd);
263            }
264        }
265        closedir(devdir);
266    }
267    closedir(busdir);
268
269    return usb;
270}
271
272int usb_write(usb_handle *h, const void *_data, int len)
273{
274    unsigned char *data = (unsigned char*) _data;
275    unsigned count = 0;
276    struct usbdevfs_bulktransfer bulk;
277    int n;
278
279    if(h->ep_out == 0) {
280        return -1;
281    }
282
283    if(len == 0) {
284        bulk.ep = h->ep_out;
285        bulk.len = 0;
286        bulk.data = data;
287        bulk.timeout = 0;
288
289        n = ioctl(h->desc, USBDEVFS_BULK, &bulk);
290        if(n != 0) {
291            fprintf(stderr,"ERROR: n = %d, errno = %d (%s)\n",
292                    n, errno, strerror(errno));
293            return -1;
294        }
295        return 0;
296    }
297
298    while(len > 0) {
299        int xfer;
300        xfer = (len > MAX_USBFS_BULK_SIZE) ? MAX_USBFS_BULK_SIZE : len;
301
302        bulk.ep = h->ep_out;
303        bulk.len = xfer;
304        bulk.data = data;
305        bulk.timeout = 0;
306
307        n = ioctl(h->desc, USBDEVFS_BULK, &bulk);
308        if(n != xfer) {
309            DBG("ERROR: n = %d, errno = %d (%s)\n",
310                n, errno, strerror(errno));
311            return -1;
312        }
313
314        count += xfer;
315        len -= xfer;
316        data += xfer;
317    }
318
319    return count;
320}
321
322int usb_read(usb_handle *h, void *_data, int len)
323{
324    unsigned char *data = (unsigned char*) _data;
325    unsigned count = 0;
326    struct usbdevfs_bulktransfer bulk;
327    int n, retry;
328
329    if(h->ep_in == 0) {
330        return -1;
331    }
332
333    while(len > 0) {
334        int xfer = (len > MAX_USBFS_BULK_SIZE) ? MAX_USBFS_BULK_SIZE : len;
335
336        bulk.ep = h->ep_in;
337        bulk.len = xfer;
338        bulk.data = data;
339        bulk.timeout = 0;
340        retry = 0;
341
342        do{
343           DBG("[ usb read %d fd = %d], fname=%s\n", xfer, h->desc, h->fname);
344           n = ioctl(h->desc, USBDEVFS_BULK, &bulk);
345           DBG("[ usb read %d ] = %d, fname=%s, Retry %d \n", xfer, n, h->fname, retry);
346
347           if( n < 0 ) {
348            DBG1("ERROR: n = %d, errno = %d (%s)\n",n, errno, strerror(errno));
349            if ( ++retry > MAX_RETRIES ) return -1;
350            sleep( 1 );
351           }
352        }
353        while( n < 0 );
354
355        count += n;
356        len -= n;
357        data += n;
358
359        if(n < xfer) {
360            break;
361        }
362    }
363
364    return count;
365}
366
367void usb_kick(usb_handle *h)
368{
369    int fd;
370
371    fd = h->desc;
372    h->desc = -1;
373    if(fd >= 0) {
374        close(fd);
375        DBG("[ usb closed %d ]\n", fd);
376    }
377}
378
379int usb_close(usb_handle *h)
380{
381    int fd;
382
383    fd = h->desc;
384    h->desc = -1;
385    if(fd >= 0) {
386        close(fd);
387        DBG("[ usb closed %d ]\n", fd);
388    }
389
390    return 0;
391}
392
393usb_handle *usb_open(ifc_match_func callback)
394{
395    return find_usb_device("/dev/bus/usb", callback);
396}
397