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