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