blob: 2d23e076912c4039785264561bf5938ff7567485 [file] [log] [blame]
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001/*
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
Anatol Pomazau5ae3f932012-02-28 07:21:08 -080012 * the documentation and/or other materials provided with the
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080013 * 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
Anatol Pomazau5ae3f932012-02-28 07:21:08 -080022 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080023 * 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
Elliott Hughes93f65fa2015-07-24 14:09:44 -070029#include <ctype.h>
30#include <dirent.h>
31#include <errno.h>
32#include <fcntl.h>
33#include <pthread.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080034#include <stdio.h>
35#include <stdlib.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080036#include <string.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080037#include <sys/ioctl.h>
Scott Anderson13081c62012-04-06 12:39:30 -070038#include <sys/stat.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080039#include <sys/types.h>
Elliott Hughes93f65fa2015-07-24 14:09:44 -070040#include <unistd.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080041
42#include <linux/usbdevice_fs.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080043#include <linux/version.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080044#include <linux/usb/ch9.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080045
David Anderson4e058ca2020-05-28 04:39:37 +000046#include <android-base/file.h>
47#include <android-base/stringprintf.h>
Elliott Hughes290a2282016-11-14 17:08:47 -080048#include <chrono>
David Pursell0b156632015-10-30 11:22:01 -070049#include <memory>
Elliott Hughes290a2282016-11-14 17:08:47 -080050#include <thread>
David Pursell0b156632015-10-30 11:22:01 -070051
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080052#include "usb.h"
Aaron Wisnerdb511202018-06-26 15:38:35 -050053#include "util.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080054
Elliott Hughes290a2282016-11-14 17:08:47 -080055using namespace std::chrono_literals;
56
Aaron Wisneracf78d42018-07-26 10:56:09 -050057#define MAX_RETRIES 2
Dan Murphyb2de4db2009-08-18 09:41:09 -050058
Mark Wachsler157b0012013-10-02 09:35:38 -040059/* 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
Dan Murphyb2de4db2009-08-18 09:41:09 -050065#ifdef TRACE_USB
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080066#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
Elliott Hughes93f65fa2015-07-24 14:09:44 -070073// 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.
Peter Collingbourneab8cc2f2024-02-13 15:40:37 -080086// 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)
David Krause913eb8b2011-03-08 14:10:16 +080098
Anatol Pomazau5ae3f932012-02-28 07:21:08 -080099struct usb_handle
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800100{
101 char fname[64];
102 int desc;
103 unsigned char ep_in;
104 unsigned char ep_out;
105};
106
Aaron Wisneracf78d42018-07-26 10:56:09 -0500107class LinuxUsbTransport : public UsbTransport {
David Pursell0b156632015-10-30 11:22:01 -0700108 public:
Aaron Wisneracf78d42018-07-26 10:56:09 -0500109 explicit LinuxUsbTransport(std::unique_ptr<usb_handle> handle, uint32_t ms_timeout = 0)
110 : handle_(std::move(handle)), ms_timeout_(ms_timeout) {}
David Anderson03de6452018-09-04 14:32:54 -0700111 ~LinuxUsbTransport() override;
David Pursell0b156632015-10-30 11:22:01 -0700112
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;
Aaron Wisneracf78d42018-07-26 10:56:09 -0500116 int Reset() override;
David Pursell0b156632015-10-30 11:22:01 -0700117 int WaitForDisconnect() override;
118
119 private:
120 std::unique_ptr<usb_handle> handle_;
Aaron Wisneracf78d42018-07-26 10:56:09 -0500121 const uint32_t ms_timeout_;
Peter Collingbourneab8cc2f2024-02-13 15:40:37 -0800122 size_t max_usbfs_bulk_write_size_ = MAX_USBFS_BULK_WRITE_SIZE;
David Pursell0b156632015-10-30 11:22:01 -0700123
124 DISALLOW_COPY_AND_ASSIGN(LinuxUsbTransport);
125};
126
Mark Wachslerbd446c72013-09-11 18:23:31 -0400127/* 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 */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800132static inline int badname(const char *name)
133{
Mark Wachslerbd446c72013-09-11 18:23:31 -0400134 if (!isdigit(*name))
135 return 1;
136 while(*++name) {
137 if(!isdigit(*name) && *name != '.' && *name != '-')
138 return 1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800139 }
140 return 0;
141}
142
143static int check(void *_desc, int len, unsigned type, int size)
144{
Patrick Tjinaac89db2014-07-11 08:59:01 -0700145 struct usb_descriptor_header *hdr = (struct usb_descriptor_header *)_desc;
Anatol Pomazau5ae3f932012-02-28 07:21:08 -0800146
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800147 if(len < size) return -1;
Patrick Tjinaac89db2014-07-11 08:59:01 -0700148 if(hdr->bLength < size) return -1;
149 if(hdr->bLength > len) return -1;
150 if(hdr->bDescriptorType != type) return -1;
Anatol Pomazau5ae3f932012-02-28 07:21:08 -0800151
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800152 return 0;
153}
154
Mark Wachsler157b0012013-10-02 09:35:38 -0400155static int filter_usb_device(char* sysfs_name,
Mark Wachslerbd446c72013-09-11 18:23:31 -0400156 char *ptr, int len, int writable,
Elliott Hughesb4add9b2009-10-06 18:07:49 -0700157 ifc_match_func callback,
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800158 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;
Anatol Pomazau5ae3f932012-02-28 07:21:08 -0800165
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800166 int in, out;
167 unsigned i;
168 unsigned e;
James Hawkins588a2ca2016-02-18 14:52:46 -0800169
Patrick Tjinaac89db2014-07-11 08:59:01 -0700170 if (check(ptr, len, USB_DT_DEVICE, USB_DT_DEVICE_SIZE))
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800171 return -1;
Patrick Tjinaac89db2014-07-11 08:59:01 -0700172 dev = (struct usb_device_descriptor *)ptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800173 len -= dev->bLength;
174 ptr += dev->bLength;
Anatol Pomazau5ae3f932012-02-28 07:21:08 -0800175
Patrick Tjinaac89db2014-07-11 08:59:01 -0700176 if (check(ptr, len, USB_DT_CONFIG, USB_DT_CONFIG_SIZE))
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800177 return -1;
Patrick Tjinaac89db2014-07-11 08:59:01 -0700178 cfg = (struct usb_config_descriptor *)ptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800179 len -= cfg->bLength;
180 ptr += cfg->bLength;
Anatol Pomazau5ae3f932012-02-28 07:21:08 -0800181
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800182 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;
Elliott Hughesb4add9b2009-10-06 18:07:49 -0700187 info.writable = writable;
Anatol Pomazau5ae3f932012-02-28 07:21:08 -0800188
Mark Wachslerbd446c72013-09-11 18:23:31 -0400189 snprintf(info.device_path, sizeof(info.device_path), "usb:%s", sysfs_name);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800190
Mark Wachslerbd446c72013-09-11 18:23:31 -0400191 /* 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.
Scott Anderson13081c62012-04-06 12:39:30 -0700196 */
Mark Wachslerbd446c72013-09-11 18:23:31 -0400197 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 }
Scott Anderson13081c62012-04-06 12:39:30 -0700218 }
219 }
220
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800221 for(i = 0; i < cfg->bNumInterfaces; i++) {
Patrick Tjinaac89db2014-07-11 08:59:01 -0700222
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)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800232 return -1;
Patrick Tjinaac89db2014-07-11 08:59:01 -0700233
234 ifc = (struct usb_interface_descriptor *)ptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800235 len -= ifc->bLength;
236 ptr += ifc->bLength;
Anatol Pomazau5ae3f932012-02-28 07:21:08 -0800237
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800238 in = -1;
239 out = -1;
240 info.ifc_class = ifc->bInterfaceClass;
241 info.ifc_subclass = ifc->bInterfaceSubClass;
242 info.ifc_protocol = ifc->bInterfaceProtocol;
Anatol Pomazau5ae3f932012-02-28 07:21:08 -0800243
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800244 for(e = 0; e < ifc->bNumEndpoints; e++) {
Patrick Tjinaac89db2014-07-11 08:59:01 -0700245 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;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800257 len -= ept->bLength;
258 ptr += ept->bLength;
Anatol Pomazau5ae3f932012-02-28 07:21:08 -0800259
Patrick Tjinaac89db2014-07-11 08:59:01 -0700260 if((ept->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) != USB_ENDPOINT_XFER_BULK)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800261 continue;
Anatol Pomazau5ae3f932012-02-28 07:21:08 -0800262
Patrick Tjinaac89db2014-07-11 08:59:01 -0700263 if(ept->bEndpointAddress & USB_ENDPOINT_DIR_MASK) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800264 in = ept->bEndpointAddress;
265 } else {
266 out = ept->bEndpointAddress;
267 }
Jack Pham1c022132014-12-05 12:11:20 -0800268
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 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800275 }
276
277 info.has_bulk_in = (in != -1);
278 info.has_bulk_out = (out != -1);
Anatol Pomazau5ae3f932012-02-28 07:21:08 -0800279
David Anderson4e058ca2020-05-28 04:39:37 +0000280 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 snprintf(info.interface, sizeof(info.interface), "%s", interface.c_str());
285 }
286
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800287 if(callback(&info) == 0) {
288 *ept_in_id = in;
289 *ept_out_id = out;
290 *ifc_id = ifc->bInterfaceNumber;
291 return 0;
292 }
293 }
294
295 return -1;
296}
297
Mark Wachslerbd446c72013-09-11 18:23:31 -0400298static int read_sysfs_string(const char *sysfs_name, const char *sysfs_node,
299 char* buf, int bufsize)
300{
301 char path[80];
302 int fd, n;
303
304 snprintf(path, sizeof(path),
305 "/sys/bus/usb/devices/%s/%s", sysfs_name, sysfs_node);
306 path[sizeof(path) - 1] = '\0';
307
308 fd = open(path, O_RDONLY);
309 if (fd < 0)
310 return -1;
311
312 n = read(fd, buf, bufsize - 1);
313 close(fd);
314
315 if (n < 0)
316 return -1;
317
318 buf[n] = '\0';
319
320 return n;
321}
322
323static int read_sysfs_number(const char *sysfs_name, const char *sysfs_node)
324{
325 char buf[16];
326 int value;
327
328 if (read_sysfs_string(sysfs_name, sysfs_node, buf, sizeof(buf)) < 0)
329 return -1;
330
331 if (sscanf(buf, "%d", &value) != 1)
332 return -1;
333
334 return value;
335}
336
337/* Given the name of a USB device in sysfs, get the name for the same
338 * device in devfs. Returns 0 for success, -1 for failure.
339 */
340static int convert_to_devfs_name(const char* sysfs_name,
341 char* devname, int devname_size)
342{
343 int busnum, devnum;
344
345 busnum = read_sysfs_number(sysfs_name, "busnum");
346 if (busnum < 0)
347 return -1;
348
349 devnum = read_sysfs_number(sysfs_name, "devnum");
350 if (devnum < 0)
351 return -1;
352
353 snprintf(devname, devname_size, "/dev/bus/usb/%03d/%03d", busnum, devnum);
354 return 0;
355}
356
David Pursell0b156632015-10-30 11:22:01 -0700357static std::unique_ptr<usb_handle> find_usb_device(const char* base, ifc_match_func callback)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800358{
David Pursell0b156632015-10-30 11:22:01 -0700359 std::unique_ptr<usb_handle> usb;
Mark Wachslerbd446c72013-09-11 18:23:31 -0400360 char devname[64];
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800361 char desc[1024];
362 int n, in, out, ifc;
Anatol Pomazau5ae3f932012-02-28 07:21:08 -0800363
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800364 struct dirent *de;
365 int fd;
Elliott Hughesc500be92009-10-07 17:24:39 -0700366 int writable;
Anatol Pomazau5ae3f932012-02-28 07:21:08 -0800367
James Hawkins588a2ca2016-02-18 14:52:46 -0800368 std::unique_ptr<DIR, decltype(&closedir)> busdir(opendir(base), closedir);
David Pursell0b156632015-10-30 11:22:01 -0700369 if (busdir == 0) return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800370
James Hawkins588a2ca2016-02-18 14:52:46 -0800371 while ((de = readdir(busdir.get())) && (usb == nullptr)) {
David Pursell0b156632015-10-30 11:22:01 -0700372 if (badname(de->d_name)) continue;
Anatol Pomazau5ae3f932012-02-28 07:21:08 -0800373
David Pursell0b156632015-10-30 11:22:01 -0700374 if (!convert_to_devfs_name(de->d_name, devname, sizeof(devname))) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800375
376// DBG("[ scanning %s ]\n", devname);
Elliott Hughesc500be92009-10-07 17:24:39 -0700377 writable = 1;
David Pursell0b156632015-10-30 11:22:01 -0700378 if ((fd = open(devname, O_RDWR)) < 0) {
Elliott Hughesb4add9b2009-10-06 18:07:49 -0700379 // Check if we have read-only access, so we can give a helpful
380 // diagnostic like "adb devices" does.
381 writable = 0;
David Pursell0b156632015-10-30 11:22:01 -0700382 if ((fd = open(devname, O_RDONLY)) < 0) {
Elliott Hughesb4add9b2009-10-06 18:07:49 -0700383 continue;
384 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800385 }
386
387 n = read(fd, desc, sizeof(desc));
Anatol Pomazau5ae3f932012-02-28 07:21:08 -0800388
David Pursell0b156632015-10-30 11:22:01 -0700389 if (filter_usb_device(de->d_name, desc, n, writable, callback, &in, &out, &ifc) == 0) {
390 usb.reset(new usb_handle());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800391 strcpy(usb->fname, devname);
392 usb->ep_in = in;
393 usb->ep_out = out;
394 usb->desc = fd;
395
396 n = ioctl(fd, USBDEVFS_CLAIMINTERFACE, &ifc);
David Pursell0b156632015-10-30 11:22:01 -0700397 if (n != 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800398 close(fd);
David Pursell0b156632015-10-30 11:22:01 -0700399 usb.reset();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800400 continue;
401 }
402 } else {
403 close(fd);
404 }
405 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800406 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800407
408 return usb;
409}
410
David Anderson03de6452018-09-04 14:32:54 -0700411LinuxUsbTransport::~LinuxUsbTransport() {
412 Close();
413}
414
David Pursell0b156632015-10-30 11:22:01 -0700415ssize_t LinuxUsbTransport::Write(const void* _data, size_t len)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800416{
417 unsigned char *data = (unsigned char*) _data;
418 unsigned count = 0;
Peter Collingbourne8635c012024-02-05 14:59:44 -0800419 struct usbdevfs_urb urb[2] = {};
420 bool pending[2] = {};
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800421
David Pursell0b156632015-10-30 11:22:01 -0700422 if (handle_->ep_out == 0 || handle_->desc == -1) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800423 return -1;
424 }
Anatol Pomazau5ae3f932012-02-28 07:21:08 -0800425
Peter Collingbourne8635c012024-02-05 14:59:44 -0800426 auto submit_urb = [&](size_t i) {
Peter Collingbourneab8cc2f2024-02-13 15:40:37 -0800427 while (true) {
428 int xfer = (len > max_usbfs_bulk_write_size_) ? max_usbfs_bulk_write_size_ : len;
Anatol Pomazau5ae3f932012-02-28 07:21:08 -0800429
Peter Collingbourneab8cc2f2024-02-13 15:40:37 -0800430 urb[i].type = USBDEVFS_URB_TYPE_BULK;
431 urb[i].endpoint = handle_->ep_out;
432 urb[i].buffer_length = xfer;
433 urb[i].buffer = data;
434 urb[i].usercontext = (void *)i;
Anatol Pomazau5ae3f932012-02-28 07:21:08 -0800435
Peter Collingbourneab8cc2f2024-02-13 15:40:37 -0800436 int n = ioctl(handle_->desc, USBDEVFS_SUBMITURB, &urb[i]);
437 if (n != 0) {
438 if (errno == ENOMEM && max_usbfs_bulk_write_size_ > MIN_USBFS_BULK_WRITE_SIZE) {
439 max_usbfs_bulk_write_size_ /= 2;
440 continue;
441 }
442 DBG("ioctl(USBDEVFS_SUBMITURB) failed\n");
443 return false;
444 }
445
446 pending[i] = true;
447 count += xfer;
448 len -= xfer;
449 data += xfer;
450
451 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800452 }
Peter Collingbourne8635c012024-02-05 14:59:44 -0800453 };
454
455 auto reap_urb = [&](size_t i) {
456 while (pending[i]) {
457 struct usbdevfs_urb *urbp;
458 int res = ioctl(handle_->desc, USBDEVFS_REAPURB, &urbp);
459 if (res != 0) {
460 DBG("ioctl(USBDEVFS_REAPURB) failed\n");
461 return false;
462 }
463 size_t done = (size_t)urbp->usercontext;
464 if (done >= 2 || !pending[done]) {
465 DBG("unexpected urb\n");
466 return false;
467 }
468 if (urbp->status != 0 || urbp->actual_length != urbp->buffer_length) {
469 DBG("urb returned error\n");
470 return false;
471 }
472 pending[done] = false;
473 }
474 return true;
475 };
476
477 if (!submit_urb(0)) {
478 return -1;
479 }
480 while (len > 0) {
481 if (!submit_urb(1)) {
482 return -1;
483 }
484 if (!reap_urb(0)) {
485 return -1;
486 }
487 if (len <= 0) {
488 if (!reap_urb(1)) {
489 return -1;
490 }
491 return count;
492 }
493 if (!submit_urb(0)) {
494 return -1;
495 }
496 if (!reap_urb(1)) {
497 return -1;
498 }
499 }
500 if (!reap_urb(0)) {
501 return -1;
502 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800503 return count;
504}
505
David Pursell0b156632015-10-30 11:22:01 -0700506ssize_t LinuxUsbTransport::Read(void* _data, size_t len)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800507{
508 unsigned char *data = (unsigned char*) _data;
509 unsigned count = 0;
510 struct usbdevfs_bulktransfer bulk;
Dan Murphyb2de4db2009-08-18 09:41:09 -0500511 int n, retry;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800512
David Pursell0b156632015-10-30 11:22:01 -0700513 if (handle_->ep_in == 0 || handle_->desc == -1) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800514 return -1;
515 }
Anatol Pomazau5ae3f932012-02-28 07:21:08 -0800516
Elliott Hughes290a2282016-11-14 17:08:47 -0800517 while (len > 0) {
Peter Collingbourneab8cc2f2024-02-13 15:40:37 -0800518 int xfer = (len > MAX_USBFS_BULK_READ_SIZE) ? MAX_USBFS_BULK_READ_SIZE : len;
Anatol Pomazau5ae3f932012-02-28 07:21:08 -0800519
David Pursell0b156632015-10-30 11:22:01 -0700520 bulk.ep = handle_->ep_in;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800521 bulk.len = xfer;
522 bulk.data = data;
Aaron Wisneracf78d42018-07-26 10:56:09 -0500523 bulk.timeout = ms_timeout_;
Dan Murphyb2de4db2009-08-18 09:41:09 -0500524 retry = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800525
Elliott Hughes290a2282016-11-14 17:08:47 -0800526 do {
527 DBG("[ usb read %d fd = %d], fname=%s\n", xfer, handle_->desc, handle_->fname);
528 n = ioctl(handle_->desc, USBDEVFS_BULK, &bulk);
529 DBG("[ usb read %d ] = %d, fname=%s, Retry %d \n", xfer, n, handle_->fname, retry);
Dan Murphyb2de4db2009-08-18 09:41:09 -0500530
Elliott Hughes290a2282016-11-14 17:08:47 -0800531 if (n < 0) {
532 DBG1("ERROR: n = %d, errno = %d (%s)\n",n, errno, strerror(errno));
533 if (++retry > MAX_RETRIES) return -1;
Aaron Wisneracf78d42018-07-26 10:56:09 -0500534 std::this_thread::sleep_for(100ms);
Elliott Hughes290a2282016-11-14 17:08:47 -0800535 }
536 } while (n < 0);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800537
538 count += n;
539 len -= n;
540 data += n;
Anatol Pomazau5ae3f932012-02-28 07:21:08 -0800541
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800542 if(n < xfer) {
543 break;
544 }
545 }
Anatol Pomazau5ae3f932012-02-28 07:21:08 -0800546
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800547 return count;
548}
549
David Pursell0b156632015-10-30 11:22:01 -0700550int LinuxUsbTransport::Close()
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800551{
552 int fd;
553
David Pursell0b156632015-10-30 11:22:01 -0700554 fd = handle_->desc;
555 handle_->desc = -1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800556 if(fd >= 0) {
557 close(fd);
558 DBG("[ usb closed %d ]\n", fd);
559 }
560
561 return 0;
562}
563
Aaron Wisneracf78d42018-07-26 10:56:09 -0500564int LinuxUsbTransport::Reset() {
565 int ret = 0;
566 // We reset the USB connection
567 if ((ret = ioctl(handle_->desc, USBDEVFS_RESET, 0))) {
568 return ret;
569 }
570
571 return 0;
572}
573
Dmitrii Merkurev0b627d92023-09-03 17:30:46 +0100574std::unique_ptr<UsbTransport> usb_open(ifc_match_func callback, uint32_t timeout_ms) {
575 std::unique_ptr<UsbTransport> result;
David Pursell0b156632015-10-30 11:22:01 -0700576 std::unique_ptr<usb_handle> handle = find_usb_device("/sys/bus/usb/devices", callback);
Dmitrii Merkurev0b627d92023-09-03 17:30:46 +0100577
578 if (handle) {
579 result = std::make_unique<LinuxUsbTransport>(std::move(handle), timeout_ms);
580 }
581
582 return result;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800583}
Mark Wachsler157b0012013-10-02 09:35:38 -0400584
585/* Wait for the system to notice the device is gone, so that a subsequent
586 * fastboot command won't try to access the device before it's rebooted.
587 * Returns 0 for success, -1 for timeout.
588 */
David Pursell0b156632015-10-30 11:22:01 -0700589int LinuxUsbTransport::WaitForDisconnect()
Mark Wachsler157b0012013-10-02 09:35:38 -0400590{
591 double deadline = now() + WAIT_FOR_DISCONNECT_TIMEOUT;
592 while (now() < deadline) {
Elliott Hughes290a2282016-11-14 17:08:47 -0800593 if (access(handle_->fname, F_OK)) return 0;
594 std::this_thread::sleep_for(50ms);
Mark Wachsler157b0012013-10-02 09:35:38 -0400595 }
596 return -1;
597}