usb_linux.cpp revision 93f65faee85facd14fa58993bbcb98c357217fcb
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 <ctype.h>
30#include <dirent.h>
31#include <errno.h>
32#include <fcntl.h>
33#include <pthread.h>
34#include <stdio.h>
35#include <stdlib.h>
36#include <string.h>
37#include <sys/ioctl.h>
38#include <sys/stat.h>
39#include <sys/types.h>
40#include <unistd.h>
41
42#include <linux/usbdevice_fs.h>
43#include <linux/version.h>
44#include <linux/usb/ch9.h>
45
46#include "fastboot.h"
47#include "usb.h"
48
49#define MAX_RETRIES 5
50
51/* Timeout in seconds for usb_wait_for_disconnect.
52 * It doesn't usually take long for a device to disconnect (almost always
53 * under 2 seconds) but we'll time out after 3 seconds just in case.
54 */
55#define WAIT_FOR_DISCONNECT_TIMEOUT  3
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// Kernels before 3.3 have a 16KiB transfer limit. That limit was replaced
66// with a 16MiB global limit in 3.3, but each URB submitted required a
67// contiguous kernel allocation, so you would get ENOMEM if you tried to
68// send something larger than the biggest available contiguous kernel
69// memory region. 256KiB contiguous allocations are generally not reliable
70// on a device kernel that has been running for a while fragmenting its
71// memory, but that shouldn't be a problem for fastboot on the host.
72// In 3.6, the contiguous buffer limit was removed by allocating multiple
73// 16KiB chunks and having the USB driver stitch them back together while
74// transmitting using a scatter-gather list, so 256KiB bulk transfers should
75// be reliable.
76// 256KiB seems to work, but 1MiB bulk transfers lock up my z620 with a 3.13
77// kernel.
78#define MAX_USBFS_BULK_SIZE (16 * 1024)
79
80struct usb_handle
81{
82    char fname[64];
83    int desc;
84    unsigned char ep_in;
85    unsigned char ep_out;
86};
87
88/* True if name isn't a valid name for a USB device in /sys/bus/usb/devices.
89 * Device names are made up of numbers, dots, and dashes, e.g., '7-1.5'.
90 * We reject interfaces (e.g., '7-1.5:1.0') and host controllers (e.g. 'usb1').
91 * The name must also start with a digit, to disallow '.' and '..'
92 */
93static inline int badname(const char *name)
94{
95    if (!isdigit(*name))
96      return 1;
97    while(*++name) {
98        if(!isdigit(*name) && *name != '.' && *name != '-')
99            return 1;
100    }
101    return 0;
102}
103
104static int check(void *_desc, int len, unsigned type, int size)
105{
106    struct usb_descriptor_header *hdr = (struct usb_descriptor_header *)_desc;
107
108    if(len < size) return -1;
109    if(hdr->bLength < size) return -1;
110    if(hdr->bLength > len) return -1;
111    if(hdr->bDescriptorType != type) return -1;
112
113    return 0;
114}
115
116static int filter_usb_device(char* sysfs_name,
117                             char *ptr, int len, int writable,
118                             ifc_match_func callback,
119                             int *ept_in_id, int *ept_out_id, int *ifc_id)
120{
121    struct usb_device_descriptor *dev;
122    struct usb_config_descriptor *cfg;
123    struct usb_interface_descriptor *ifc;
124    struct usb_endpoint_descriptor *ept;
125    struct usb_ifc_info info;
126
127    int in, out;
128    unsigned i;
129    unsigned e;
130
131    if (check(ptr, len, USB_DT_DEVICE, USB_DT_DEVICE_SIZE))
132        return -1;
133    dev = (struct usb_device_descriptor *)ptr;
134    len -= dev->bLength;
135    ptr += dev->bLength;
136
137    if (check(ptr, len, USB_DT_CONFIG, USB_DT_CONFIG_SIZE))
138        return -1;
139    cfg = (struct usb_config_descriptor *)ptr;
140    len -= cfg->bLength;
141    ptr += cfg->bLength;
142
143    info.dev_vendor = dev->idVendor;
144    info.dev_product = dev->idProduct;
145    info.dev_class = dev->bDeviceClass;
146    info.dev_subclass = dev->bDeviceSubClass;
147    info.dev_protocol = dev->bDeviceProtocol;
148    info.writable = writable;
149
150    snprintf(info.device_path, sizeof(info.device_path), "usb:%s", sysfs_name);
151
152    /* Read device serial number (if there is one).
153     * We read the serial number from sysfs, since it's faster and more
154     * reliable than issuing a control pipe read, and also won't
155     * cause problems for devices which don't like getting descriptor
156     * requests while they're in the middle of flashing.
157     */
158    info.serial_number[0] = '\0';
159    if (dev->iSerialNumber) {
160        char path[80];
161        int fd;
162
163        snprintf(path, sizeof(path),
164                 "/sys/bus/usb/devices/%s/serial", sysfs_name);
165        path[sizeof(path) - 1] = '\0';
166
167        fd = open(path, O_RDONLY);
168        if (fd >= 0) {
169            int chars_read = read(fd, info.serial_number,
170                                  sizeof(info.serial_number) - 1);
171            close(fd);
172
173            if (chars_read <= 0)
174                info.serial_number[0] = '\0';
175            else if (info.serial_number[chars_read - 1] == '\n') {
176                // strip trailing newline
177                info.serial_number[chars_read - 1] = '\0';
178            }
179        }
180    }
181
182    for(i = 0; i < cfg->bNumInterfaces; i++) {
183
184        while (len > 0) {
185	        struct usb_descriptor_header *hdr = (struct usb_descriptor_header *)ptr;
186            if (check(hdr, len, USB_DT_INTERFACE, USB_DT_INTERFACE_SIZE) == 0)
187                break;
188            len -= hdr->bLength;
189            ptr += hdr->bLength;
190        }
191
192        if (len <= 0)
193            return -1;
194
195        ifc = (struct usb_interface_descriptor *)ptr;
196        len -= ifc->bLength;
197        ptr += ifc->bLength;
198
199        in = -1;
200        out = -1;
201        info.ifc_class = ifc->bInterfaceClass;
202        info.ifc_subclass = ifc->bInterfaceSubClass;
203        info.ifc_protocol = ifc->bInterfaceProtocol;
204
205        for(e = 0; e < ifc->bNumEndpoints; e++) {
206            while (len > 0) {
207	            struct usb_descriptor_header *hdr = (struct usb_descriptor_header *)ptr;
208                if (check(hdr, len, USB_DT_ENDPOINT, USB_DT_ENDPOINT_SIZE) == 0)
209                    break;
210                len -= hdr->bLength;
211                ptr += hdr->bLength;
212            }
213            if (len < 0) {
214                break;
215            }
216
217            ept = (struct usb_endpoint_descriptor *)ptr;
218            len -= ept->bLength;
219            ptr += ept->bLength;
220
221            if((ept->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) != USB_ENDPOINT_XFER_BULK)
222                continue;
223
224            if(ept->bEndpointAddress & USB_ENDPOINT_DIR_MASK) {
225                in = ept->bEndpointAddress;
226            } else {
227                out = ept->bEndpointAddress;
228            }
229
230            // For USB 3.0 devices skip the SS Endpoint Companion descriptor
231            if (check((struct usb_descriptor_hdr *)ptr, len,
232                      USB_DT_SS_ENDPOINT_COMP, USB_DT_SS_EP_COMP_SIZE) == 0) {
233                len -= USB_DT_SS_EP_COMP_SIZE;
234                ptr += USB_DT_SS_EP_COMP_SIZE;
235            }
236        }
237
238        info.has_bulk_in = (in != -1);
239        info.has_bulk_out = (out != -1);
240
241        if(callback(&info) == 0) {
242            *ept_in_id = in;
243            *ept_out_id = out;
244            *ifc_id = ifc->bInterfaceNumber;
245            return 0;
246        }
247    }
248
249    return -1;
250}
251
252static int read_sysfs_string(const char *sysfs_name, const char *sysfs_node,
253                             char* buf, int bufsize)
254{
255    char path[80];
256    int fd, n;
257
258    snprintf(path, sizeof(path),
259             "/sys/bus/usb/devices/%s/%s", sysfs_name, sysfs_node);
260    path[sizeof(path) - 1] = '\0';
261
262    fd = open(path, O_RDONLY);
263    if (fd < 0)
264        return -1;
265
266    n = read(fd, buf, bufsize - 1);
267    close(fd);
268
269    if (n < 0)
270        return -1;
271
272    buf[n] = '\0';
273
274    return n;
275}
276
277static int read_sysfs_number(const char *sysfs_name, const char *sysfs_node)
278{
279    char buf[16];
280    int value;
281
282    if (read_sysfs_string(sysfs_name, sysfs_node, buf, sizeof(buf)) < 0)
283        return -1;
284
285    if (sscanf(buf, "%d", &value) != 1)
286        return -1;
287
288    return value;
289}
290
291/* Given the name of a USB device in sysfs, get the name for the same
292 * device in devfs. Returns 0 for success, -1 for failure.
293 */
294static int convert_to_devfs_name(const char* sysfs_name,
295                                 char* devname, int devname_size)
296{
297    int busnum, devnum;
298
299    busnum = read_sysfs_number(sysfs_name, "busnum");
300    if (busnum < 0)
301        return -1;
302
303    devnum = read_sysfs_number(sysfs_name, "devnum");
304    if (devnum < 0)
305        return -1;
306
307    snprintf(devname, devname_size, "/dev/bus/usb/%03d/%03d", busnum, devnum);
308    return 0;
309}
310
311static usb_handle *find_usb_device(const char *base, ifc_match_func callback)
312{
313    usb_handle *usb = 0;
314    char devname[64];
315    char desc[1024];
316    int n, in, out, ifc;
317
318    DIR *busdir;
319    struct dirent *de;
320    int fd;
321    int writable;
322
323    busdir = opendir(base);
324    if(busdir == 0) return 0;
325
326    while((de = readdir(busdir)) && (usb == 0)) {
327        if(badname(de->d_name)) continue;
328
329        if(!convert_to_devfs_name(de->d_name, devname, sizeof(devname))) {
330
331//            DBG("[ scanning %s ]\n", devname);
332            writable = 1;
333            if((fd = open(devname, O_RDWR)) < 0) {
334                // Check if we have read-only access, so we can give a helpful
335                // diagnostic like "adb devices" does.
336                writable = 0;
337                if((fd = open(devname, O_RDONLY)) < 0) {
338                    continue;
339                }
340            }
341
342            n = read(fd, desc, sizeof(desc));
343
344            if(filter_usb_device(de->d_name, desc, n, writable, callback,
345                                 &in, &out, &ifc) == 0) {
346                usb = reinterpret_cast<usb_handle*>(calloc(1, sizeof(usb_handle)));
347                strcpy(usb->fname, devname);
348                usb->ep_in = in;
349                usb->ep_out = out;
350                usb->desc = fd;
351
352                n = ioctl(fd, USBDEVFS_CLAIMINTERFACE, &ifc);
353                if(n != 0) {
354                    close(fd);
355                    free(usb);
356                    usb = 0;
357                    continue;
358                }
359            } else {
360                close(fd);
361            }
362        }
363    }
364    closedir(busdir);
365
366    return usb;
367}
368
369int usb_write(usb_handle *h, const void *_data, int len)
370{
371    unsigned char *data = (unsigned char*) _data;
372    unsigned count = 0;
373    struct usbdevfs_bulktransfer bulk;
374    int n;
375
376    if(h->ep_out == 0 || h->desc == -1) {
377        return -1;
378    }
379
380    do {
381        int xfer;
382        xfer = (len > MAX_USBFS_BULK_SIZE) ? MAX_USBFS_BULK_SIZE : len;
383
384        bulk.ep = h->ep_out;
385        bulk.len = xfer;
386        bulk.data = data;
387        bulk.timeout = 0;
388
389        n = ioctl(h->desc, USBDEVFS_BULK, &bulk);
390        if(n != xfer) {
391            DBG("ERROR: n = %d, errno = %d (%s)\n",
392                n, errno, strerror(errno));
393            return -1;
394        }
395
396        count += xfer;
397        len -= xfer;
398        data += xfer;
399    } while(len > 0);
400
401    return count;
402}
403
404int usb_read(usb_handle *h, void *_data, int len)
405{
406    unsigned char *data = (unsigned char*) _data;
407    unsigned count = 0;
408    struct usbdevfs_bulktransfer bulk;
409    int n, retry;
410
411    if(h->ep_in == 0 || h->desc == -1) {
412        return -1;
413    }
414
415    while(len > 0) {
416        int xfer = (len > MAX_USBFS_BULK_SIZE) ? MAX_USBFS_BULK_SIZE : len;
417
418        bulk.ep = h->ep_in;
419        bulk.len = xfer;
420        bulk.data = data;
421        bulk.timeout = 0;
422        retry = 0;
423
424        do{
425           DBG("[ usb read %d fd = %d], fname=%s\n", xfer, h->desc, h->fname);
426           n = ioctl(h->desc, USBDEVFS_BULK, &bulk);
427           DBG("[ usb read %d ] = %d, fname=%s, Retry %d \n", xfer, n, h->fname, retry);
428
429           if( n < 0 ) {
430            DBG1("ERROR: n = %d, errno = %d (%s)\n",n, errno, strerror(errno));
431            if ( ++retry > MAX_RETRIES ) return -1;
432            sleep( 1 );
433           }
434        }
435        while( n < 0 );
436
437        count += n;
438        len -= n;
439        data += n;
440
441        if(n < xfer) {
442            break;
443        }
444    }
445
446    return count;
447}
448
449void usb_kick(usb_handle *h)
450{
451    int fd;
452
453    fd = h->desc;
454    h->desc = -1;
455    if(fd >= 0) {
456        close(fd);
457        DBG("[ usb closed %d ]\n", fd);
458    }
459}
460
461int usb_close(usb_handle *h)
462{
463    int fd;
464
465    fd = h->desc;
466    h->desc = -1;
467    if(fd >= 0) {
468        close(fd);
469        DBG("[ usb closed %d ]\n", fd);
470    }
471
472    return 0;
473}
474
475usb_handle *usb_open(ifc_match_func callback)
476{
477    return find_usb_device("/sys/bus/usb/devices", callback);
478}
479
480/* Wait for the system to notice the device is gone, so that a subsequent
481 * fastboot command won't try to access the device before it's rebooted.
482 * Returns 0 for success, -1 for timeout.
483 */
484int usb_wait_for_disconnect(usb_handle *usb)
485{
486  double deadline = now() + WAIT_FOR_DISCONNECT_TIMEOUT;
487  while (now() < deadline) {
488    if (access(usb->fname, F_OK))
489      return 0;
490    usleep(50000);
491  }
492  return -1;
493}
494