blob: 03af8f76b4fbea138ef89a542e456ab5ed617ea8 [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)) {
Matt Schulte28f48072024-02-07 16:24:26 -0800284 if (!interface.empty() && interface.back() == '\n') {
285 interface.pop_back();
286 }
David Anderson4e058ca2020-05-28 04:39:37 +0000287 snprintf(info.interface, sizeof(info.interface), "%s", interface.c_str());
288 }
289
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800290 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
Mark Wachslerbd446c72013-09-11 18:23:31 -0400301static 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
326static 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 */
343static 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
David Pursell0b156632015-10-30 11:22:01 -0700360static 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 -0800361{
David Pursell0b156632015-10-30 11:22:01 -0700362 std::unique_ptr<usb_handle> usb;
Mark Wachslerbd446c72013-09-11 18:23:31 -0400363 char devname[64];
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800364 char desc[1024];
365 int n, in, out, ifc;
Anatol Pomazau5ae3f932012-02-28 07:21:08 -0800366
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800367 struct dirent *de;
368 int fd;
Elliott Hughesc500be92009-10-07 17:24:39 -0700369 int writable;
Anatol Pomazau5ae3f932012-02-28 07:21:08 -0800370
James Hawkins588a2ca2016-02-18 14:52:46 -0800371 std::unique_ptr<DIR, decltype(&closedir)> busdir(opendir(base), closedir);
David Pursell0b156632015-10-30 11:22:01 -0700372 if (busdir == 0) return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800373
James Hawkins588a2ca2016-02-18 14:52:46 -0800374 while ((de = readdir(busdir.get())) && (usb == nullptr)) {
David Pursell0b156632015-10-30 11:22:01 -0700375 if (badname(de->d_name)) continue;
Anatol Pomazau5ae3f932012-02-28 07:21:08 -0800376
David Pursell0b156632015-10-30 11:22:01 -0700377 if (!convert_to_devfs_name(de->d_name, devname, sizeof(devname))) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800378
379// DBG("[ scanning %s ]\n", devname);
Elliott Hughesc500be92009-10-07 17:24:39 -0700380 writable = 1;
David Pursell0b156632015-10-30 11:22:01 -0700381 if ((fd = open(devname, O_RDWR)) < 0) {
Elliott Hughesb4add9b2009-10-06 18:07:49 -0700382 // Check if we have read-only access, so we can give a helpful
383 // diagnostic like "adb devices" does.
384 writable = 0;
David Pursell0b156632015-10-30 11:22:01 -0700385 if ((fd = open(devname, O_RDONLY)) < 0) {
Elliott Hughesb4add9b2009-10-06 18:07:49 -0700386 continue;
387 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800388 }
389
390 n = read(fd, desc, sizeof(desc));
Anatol Pomazau5ae3f932012-02-28 07:21:08 -0800391
David Pursell0b156632015-10-30 11:22:01 -0700392 if (filter_usb_device(de->d_name, desc, n, writable, callback, &in, &out, &ifc) == 0) {
393 usb.reset(new usb_handle());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800394 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);
David Pursell0b156632015-10-30 11:22:01 -0700400 if (n != 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800401 close(fd);
David Pursell0b156632015-10-30 11:22:01 -0700402 usb.reset();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800403 continue;
404 }
405 } else {
406 close(fd);
407 }
408 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800409 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800410
411 return usb;
412}
413
David Anderson03de6452018-09-04 14:32:54 -0700414LinuxUsbTransport::~LinuxUsbTransport() {
415 Close();
416}
417
David Pursell0b156632015-10-30 11:22:01 -0700418ssize_t LinuxUsbTransport::Write(const void* _data, size_t len)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800419{
420 unsigned char *data = (unsigned char*) _data;
421 unsigned count = 0;
Peter Collingbourne8635c012024-02-05 14:59:44 -0800422 struct usbdevfs_urb urb[2] = {};
423 bool pending[2] = {};
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800424
David Pursell0b156632015-10-30 11:22:01 -0700425 if (handle_->ep_out == 0 || handle_->desc == -1) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800426 return -1;
427 }
Anatol Pomazau5ae3f932012-02-28 07:21:08 -0800428
Peter Collingbourne8635c012024-02-05 14:59:44 -0800429 auto submit_urb = [&](size_t i) {
Peter Collingbourneab8cc2f2024-02-13 15:40:37 -0800430 while (true) {
431 int xfer = (len > max_usbfs_bulk_write_size_) ? max_usbfs_bulk_write_size_ : len;
Anatol Pomazau5ae3f932012-02-28 07:21:08 -0800432
Peter Collingbourneab8cc2f2024-02-13 15:40:37 -0800433 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;
Anatol Pomazau5ae3f932012-02-28 07:21:08 -0800438
Peter Collingbourneab8cc2f2024-02-13 15:40:37 -0800439 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;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800455 }
Peter Collingbourne8635c012024-02-05 14:59:44 -0800456 };
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 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800506 return count;
507}
508
David Pursell0b156632015-10-30 11:22:01 -0700509ssize_t LinuxUsbTransport::Read(void* _data, size_t len)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800510{
511 unsigned char *data = (unsigned char*) _data;
512 unsigned count = 0;
513 struct usbdevfs_bulktransfer bulk;
Dan Murphyb2de4db2009-08-18 09:41:09 -0500514 int n, retry;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800515
David Pursell0b156632015-10-30 11:22:01 -0700516 if (handle_->ep_in == 0 || handle_->desc == -1) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800517 return -1;
518 }
Anatol Pomazau5ae3f932012-02-28 07:21:08 -0800519
Elliott Hughes290a2282016-11-14 17:08:47 -0800520 while (len > 0) {
Peter Collingbourneab8cc2f2024-02-13 15:40:37 -0800521 int xfer = (len > MAX_USBFS_BULK_READ_SIZE) ? MAX_USBFS_BULK_READ_SIZE : len;
Anatol Pomazau5ae3f932012-02-28 07:21:08 -0800522
David Pursell0b156632015-10-30 11:22:01 -0700523 bulk.ep = handle_->ep_in;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800524 bulk.len = xfer;
525 bulk.data = data;
Aaron Wisneracf78d42018-07-26 10:56:09 -0500526 bulk.timeout = ms_timeout_;
Dan Murphyb2de4db2009-08-18 09:41:09 -0500527 retry = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800528
Elliott Hughes290a2282016-11-14 17:08:47 -0800529 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);
Dan Murphyb2de4db2009-08-18 09:41:09 -0500533
Elliott Hughes290a2282016-11-14 17:08:47 -0800534 if (n < 0) {
535 DBG1("ERROR: n = %d, errno = %d (%s)\n",n, errno, strerror(errno));
536 if (++retry > MAX_RETRIES) return -1;
Aaron Wisneracf78d42018-07-26 10:56:09 -0500537 std::this_thread::sleep_for(100ms);
Elliott Hughes290a2282016-11-14 17:08:47 -0800538 }
539 } while (n < 0);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800540
541 count += n;
542 len -= n;
543 data += n;
Anatol Pomazau5ae3f932012-02-28 07:21:08 -0800544
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800545 if(n < xfer) {
546 break;
547 }
548 }
Anatol Pomazau5ae3f932012-02-28 07:21:08 -0800549
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800550 return count;
551}
552
David Pursell0b156632015-10-30 11:22:01 -0700553int LinuxUsbTransport::Close()
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800554{
555 int fd;
556
David Pursell0b156632015-10-30 11:22:01 -0700557 fd = handle_->desc;
558 handle_->desc = -1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800559 if(fd >= 0) {
560 close(fd);
561 DBG("[ usb closed %d ]\n", fd);
562 }
563
564 return 0;
565}
566
Aaron Wisneracf78d42018-07-26 10:56:09 -0500567int 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
Dmitrii Merkurev0b627d92023-09-03 17:30:46 +0100577std::unique_ptr<UsbTransport> usb_open(ifc_match_func callback, uint32_t timeout_ms) {
578 std::unique_ptr<UsbTransport> result;
David Pursell0b156632015-10-30 11:22:01 -0700579 std::unique_ptr<usb_handle> handle = find_usb_device("/sys/bus/usb/devices", callback);
Dmitrii Merkurev0b627d92023-09-03 17:30:46 +0100580
581 if (handle) {
582 result = std::make_unique<LinuxUsbTransport>(std::move(handle), timeout_ms);
583 }
584
585 return result;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800586}
Mark Wachsler157b0012013-10-02 09:35:38 -0400587
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 */
David Pursell0b156632015-10-30 11:22:01 -0700592int LinuxUsbTransport::WaitForDisconnect()
Mark Wachsler157b0012013-10-02 09:35:38 -0400593{
594 double deadline = now() + WAIT_FOR_DISCONNECT_TIMEOUT;
595 while (now() < deadline) {
Elliott Hughes290a2282016-11-14 17:08:47 -0800596 if (access(handle_->fname, F_OK)) return 0;
597 std::this_thread::sleep_for(50ms);
Mark Wachsler157b0012013-10-02 09:35:38 -0400598 }
599 return -1;
600}