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