1 /*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #define TRACE_TAG USB
18
19 #include "sysdeps.h"
20
21 #include "client/usb.h"
22
23 #include <ctype.h>
24 #include <dirent.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <linux/usb/ch9.h>
28 #include <linux/usbdevice_fs.h>
29 #include <linux/version.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <sys/ioctl.h>
34 #include <sys/time.h>
35 #include <sys/sysmacros.h>
36 #include <sys/types.h>
37 #include <unistd.h>
38
39 #include <chrono>
40 #include <condition_variable>
41 #include <list>
42 #include <mutex>
43 #include <string>
44 #include <string_view>
45 #include <thread>
46
47 #include <android-base/file.h>
48 #include <android-base/stringprintf.h>
49 #include <android-base/strings.h>
50
51 #include "adb.h"
52 #include "transport.h"
53
54 using namespace std::chrono_literals;
55 using namespace std::literals;
56
57 /* usb scan debugging is waaaay too verbose */
58 #define DBGX(x...)
59
60 struct usb_handle {
~usb_handleusb_handle61 ~usb_handle() {
62 if (fd != -1) unix_close(fd);
63 }
64
65 std::string path;
66 int fd = -1;
67 unsigned char ep_in;
68 unsigned char ep_out;
69
70 size_t max_packet_size;
71 unsigned zero_mask;
72 unsigned writeable = 1;
73
74 // The usbdevfs_urb structure ends in a variable length array of
75 // usbdevfs_iso_packet_desc. Since none of the usb calls ever attempt
76 // to fill in those values, ignore this warning.
77 #pragma clang diagnostic push
78 #pragma clang diagnostic ignored "-Wgnu-variable-sized-type-not-at-end"
79 usbdevfs_urb urb_in;
80 usbdevfs_urb urb_out;
81 #pragma clang diagnostic pop
82
83 bool urb_in_busy = false;
84 bool urb_out_busy = false;
85 bool dead = false;
86
87 std::condition_variable cv;
88 std::mutex mutex;
89
90 // for garbage collecting disconnected devices
91 bool mark;
92
93 // ID of thread currently in REAPURB
94 pthread_t reaper_thread = 0;
95 };
96
97 static auto& g_usb_handles_mutex = *new std::mutex();
98 static auto& g_usb_handles = *new std::list<usb_handle*>();
99
is_known_device(std::string_view dev_name)100 static int is_known_device(std::string_view dev_name) {
101 std::lock_guard<std::mutex> lock(g_usb_handles_mutex);
102 for (usb_handle* usb : g_usb_handles) {
103 if (usb->path == dev_name) {
104 // set mark flag to indicate this device is still alive
105 usb->mark = true;
106 return 1;
107 }
108 }
109 return 0;
110 }
111
kick_disconnected_devices()112 static void kick_disconnected_devices() {
113 std::lock_guard<std::mutex> lock(g_usb_handles_mutex);
114 // kick any devices in the device list that were not found in the device scan
115 for (usb_handle* usb : g_usb_handles) {
116 if (!usb->mark) {
117 usb_kick(usb);
118 } else {
119 usb->mark = false;
120 }
121 }
122 }
123
contains_non_digit(const char * name)124 static inline bool contains_non_digit(const char* name) {
125 while (*name) {
126 if (!isdigit(*name++)) return true;
127 }
128 return false;
129 }
130
find_usb_device(const std::string & base,void (* register_device_callback)(const char *,const char *,unsigned char,unsigned char,int,int,unsigned,size_t))131 static void find_usb_device(const std::string& base,
132 void (*register_device_callback)(const char*, const char*,
133 unsigned char, unsigned char, int, int,
134 unsigned, size_t)) {
135 std::unique_ptr<DIR, int(*)(DIR*)> bus_dir(opendir(base.c_str()), closedir);
136 if (!bus_dir) return;
137
138 dirent* de;
139 while ((de = readdir(bus_dir.get())) != nullptr) {
140 if (contains_non_digit(de->d_name)) continue;
141
142 std::string bus_name = base + "/" + de->d_name;
143
144 std::unique_ptr<DIR, int(*)(DIR*)> dev_dir(opendir(bus_name.c_str()), closedir);
145 if (!dev_dir) continue;
146
147 while ((de = readdir(dev_dir.get()))) {
148 unsigned char devdesc[4096];
149 unsigned char* bufptr = devdesc;
150 unsigned char* bufend;
151 struct usb_device_descriptor* device;
152 struct usb_config_descriptor* config;
153 struct usb_interface_descriptor* interface;
154 struct usb_endpoint_descriptor *ep1, *ep2;
155 unsigned zero_mask = 0;
156 size_t max_packet_size = 0;
157
158 if (contains_non_digit(de->d_name)) continue;
159
160 std::string dev_name = bus_name + "/" + de->d_name;
161 if (is_known_device(dev_name)) {
162 continue;
163 }
164
165 int fd = unix_open(dev_name, O_RDONLY | O_CLOEXEC);
166 if (fd == -1) {
167 continue;
168 }
169
170 size_t desclength = unix_read(fd, devdesc, sizeof(devdesc));
171 bufend = bufptr + desclength;
172
173 // should have device and configuration descriptors, and atleast two endpoints
174 if (desclength < USB_DT_DEVICE_SIZE + USB_DT_CONFIG_SIZE) {
175 D("desclength %zu is too small", desclength);
176 unix_close(fd);
177 continue;
178 }
179
180 device = (struct usb_device_descriptor*)bufptr;
181 bufptr += USB_DT_DEVICE_SIZE;
182
183 if((device->bLength != USB_DT_DEVICE_SIZE) || (device->bDescriptorType != USB_DT_DEVICE)) {
184 unix_close(fd);
185 continue;
186 }
187
188 DBGX("[ %s is V:%04x P:%04x ]\n", dev_name.c_str(), device->idVendor,
189 device->idProduct);
190
191 // should have config descriptor next
192 config = (struct usb_config_descriptor *)bufptr;
193 bufptr += USB_DT_CONFIG_SIZE;
194 if (config->bLength != USB_DT_CONFIG_SIZE || config->bDescriptorType != USB_DT_CONFIG) {
195 D("usb_config_descriptor not found");
196 unix_close(fd);
197 continue;
198 }
199
200 // loop through all the descriptors and look for the ADB interface
201 while (bufptr < bufend) {
202 unsigned char length = bufptr[0];
203 unsigned char type = bufptr[1];
204
205 if (type == USB_DT_INTERFACE) {
206 interface = (struct usb_interface_descriptor *)bufptr;
207 bufptr += length;
208
209 if (length != USB_DT_INTERFACE_SIZE) {
210 D("interface descriptor has wrong size");
211 break;
212 }
213
214 DBGX("bInterfaceClass: %d, bInterfaceSubClass: %d,"
215 "bInterfaceProtocol: %d, bNumEndpoints: %d\n",
216 interface->bInterfaceClass, interface->bInterfaceSubClass,
217 interface->bInterfaceProtocol, interface->bNumEndpoints);
218
219 if (interface->bNumEndpoints == 2 &&
220 is_adb_interface(interface->bInterfaceClass, interface->bInterfaceSubClass,
221 interface->bInterfaceProtocol)) {
222 struct stat st;
223 char pathbuf[128];
224 char link[256];
225 char *devpath = nullptr;
226
227 DBGX("looking for bulk endpoints\n");
228 // looks like ADB...
229 ep1 = (struct usb_endpoint_descriptor *)bufptr;
230 bufptr += USB_DT_ENDPOINT_SIZE;
231 // For USB 3.0 SuperSpeed devices, skip potential
232 // USB 3.0 SuperSpeed Endpoint Companion descriptor
233 if (bufptr+2 <= devdesc + desclength &&
234 bufptr[0] == USB_DT_SS_EP_COMP_SIZE &&
235 bufptr[1] == USB_DT_SS_ENDPOINT_COMP) {
236 bufptr += USB_DT_SS_EP_COMP_SIZE;
237 }
238 ep2 = (struct usb_endpoint_descriptor *)bufptr;
239 bufptr += USB_DT_ENDPOINT_SIZE;
240 if (bufptr+2 <= devdesc + desclength &&
241 bufptr[0] == USB_DT_SS_EP_COMP_SIZE &&
242 bufptr[1] == USB_DT_SS_ENDPOINT_COMP) {
243 bufptr += USB_DT_SS_EP_COMP_SIZE;
244 }
245
246 if (bufptr > devdesc + desclength ||
247 ep1->bLength != USB_DT_ENDPOINT_SIZE ||
248 ep1->bDescriptorType != USB_DT_ENDPOINT ||
249 ep2->bLength != USB_DT_ENDPOINT_SIZE ||
250 ep2->bDescriptorType != USB_DT_ENDPOINT) {
251 D("endpoints not found");
252 break;
253 }
254
255 // both endpoints should be bulk
256 if (ep1->bmAttributes != USB_ENDPOINT_XFER_BULK ||
257 ep2->bmAttributes != USB_ENDPOINT_XFER_BULK) {
258 D("bulk endpoints not found");
259 continue;
260 }
261 /* aproto 01 needs 0 termination */
262 if (interface->bInterfaceProtocol == ADB_PROTOCOL) {
263 max_packet_size = ep1->wMaxPacketSize;
264 zero_mask = ep1->wMaxPacketSize - 1;
265 }
266
267 // we have a match. now we just need to figure out which is in and which is out.
268 unsigned char local_ep_in, local_ep_out;
269 if (ep1->bEndpointAddress & USB_ENDPOINT_DIR_MASK) {
270 local_ep_in = ep1->bEndpointAddress;
271 local_ep_out = ep2->bEndpointAddress;
272 } else {
273 local_ep_in = ep2->bEndpointAddress;
274 local_ep_out = ep1->bEndpointAddress;
275 }
276
277 // Determine the device path
278 if (!fstat(fd, &st) && S_ISCHR(st.st_mode)) {
279 snprintf(pathbuf, sizeof(pathbuf), "/sys/dev/char/%d:%d",
280 major(st.st_rdev), minor(st.st_rdev));
281 ssize_t link_len = readlink(pathbuf, link, sizeof(link) - 1);
282 if (link_len > 0) {
283 link[link_len] = '\0';
284 const char* slash = strrchr(link, '/');
285 if (slash) {
286 snprintf(pathbuf, sizeof(pathbuf),
287 "usb:%s", slash + 1);
288 devpath = pathbuf;
289 }
290 }
291 }
292
293 register_device_callback(dev_name.c_str(), devpath, local_ep_in,
294 local_ep_out, interface->bInterfaceNumber,
295 device->iSerialNumber, zero_mask, max_packet_size);
296 break;
297 }
298 } else if (!length) {
299 // Specific Corsair USB hubs seen in the wild report a zero-length
300 // descriptor (resulting in an uninitialized descriptor
301 // type: https://issuetracker.google.com/302212871).
302 // If we don't give up here, we'll never make progress.
303 D("interface descriptor has 0 length. type: %d", type);
304 break;
305 } else {
306 bufptr += length;
307 }
308 } // end of while
309
310 unix_close(fd);
311 }
312 }
313 }
314
usb_bulk_write(usb_handle * h,const void * data,int len)315 static int usb_bulk_write(usb_handle* h, const void* data, int len) {
316 std::unique_lock<std::mutex> lock(h->mutex);
317 D("++ usb_bulk_write ++");
318
319 usbdevfs_urb* urb = &h->urb_out;
320 memset(urb, 0, sizeof(*urb));
321 urb->type = USBDEVFS_URB_TYPE_BULK;
322 urb->endpoint = h->ep_out;
323 urb->status = -1;
324 urb->buffer = const_cast<void*>(data);
325 urb->buffer_length = len;
326
327 if (h->dead) {
328 errno = EINVAL;
329 return -1;
330 }
331
332 if (TEMP_FAILURE_RETRY(ioctl(h->fd, USBDEVFS_SUBMITURB, urb)) == -1) {
333 return -1;
334 }
335
336 h->urb_out_busy = true;
337 while (true) {
338 auto now = std::chrono::steady_clock::now();
339 if (h->cv.wait_until(lock, now + 5s) == std::cv_status::timeout || h->dead) {
340 // TODO: call USBDEVFS_DISCARDURB?
341 errno = ETIMEDOUT;
342 return -1;
343 }
344 if (!h->urb_out_busy) {
345 if (urb->status != 0) {
346 errno = -urb->status;
347 return -1;
348 }
349 return urb->actual_length;
350 }
351 }
352 }
353
usb_bulk_read(usb_handle * h,void * data,int len)354 static int usb_bulk_read(usb_handle* h, void* data, int len) {
355 std::unique_lock<std::mutex> lock(h->mutex);
356 D("++ usb_bulk_read ++");
357
358 usbdevfs_urb* urb = &h->urb_in;
359 memset(urb, 0, sizeof(*urb));
360 urb->type = USBDEVFS_URB_TYPE_BULK;
361 urb->endpoint = h->ep_in;
362 urb->status = -1;
363 urb->buffer = data;
364 urb->buffer_length = len;
365
366 if (h->dead) {
367 errno = EINVAL;
368 return -1;
369 }
370
371 if (TEMP_FAILURE_RETRY(ioctl(h->fd, USBDEVFS_SUBMITURB, urb)) == -1) {
372 return -1;
373 }
374
375 h->urb_in_busy = true;
376 while (true) {
377 D("[ reap urb - wait ]");
378 h->reaper_thread = pthread_self();
379 int fd = h->fd;
380 lock.unlock();
381
382 // This ioctl must not have TEMP_FAILURE_RETRY because we send SIGALRM to break out.
383 usbdevfs_urb* out = nullptr;
384 int res = ioctl(fd, USBDEVFS_REAPURB, &out);
385 int saved_errno = errno;
386
387 lock.lock();
388 h->reaper_thread = 0;
389 if (h->dead) {
390 errno = EINVAL;
391 return -1;
392 }
393 if (res < 0) {
394 if (saved_errno == EINTR) {
395 continue;
396 }
397 D("[ reap urb - error ]");
398 errno = saved_errno;
399 return -1;
400 }
401 D("[ urb @%p status = %d, actual = %d ]", out, out->status, out->actual_length);
402
403 if (out == &h->urb_in) {
404 D("[ reap urb - IN complete ]");
405 h->urb_in_busy = false;
406 if (urb->status != 0) {
407 errno = -urb->status;
408 return -1;
409 }
410 return urb->actual_length;
411 }
412 if (out == &h->urb_out) {
413 D("[ reap urb - OUT compelete ]");
414 h->urb_out_busy = false;
415 h->cv.notify_all();
416 }
417 }
418 }
419
usb_write_split(usb_handle * h,unsigned char * data,int len)420 static int usb_write_split(usb_handle* h, unsigned char* data, int len) {
421 for (int i = 0; i < len; i += 16384) {
422 int chunk_size = (i + 16384 > len) ? len - i : 16384;
423 int n = usb_bulk_write(h, data + i, chunk_size);
424 if (n != chunk_size) {
425 D("ERROR: n = %d, errno = %d (%s)", n, errno, strerror(errno));
426 return -1;
427 }
428 }
429
430 return len;
431 }
432
usb_write(usb_handle * h,const void * _data,int len)433 int usb_write(usb_handle* h, const void* _data, int len) {
434 D("++ usb_write ++");
435
436 unsigned char* data = (unsigned char*)_data;
437
438 // The kernel will attempt to allocate a contiguous buffer for each write we submit.
439 // This might fail due to heap fragmentation, so attempt a contiguous write once, and if that
440 // fails, retry after having split the data into 16kB chunks to avoid allocation failure.
441 int n = usb_bulk_write(h, data, len);
442 if (n == -1 && errno == ENOMEM) {
443 n = usb_write_split(h, data, len);
444 }
445
446 if (n == -1) {
447 return -1;
448 }
449
450 if (h->zero_mask && !(len & h->zero_mask)) {
451 // If we need 0-markers and our transfer is an even multiple of the packet size,
452 // then send a zero marker.
453 return usb_bulk_write(h, _data, 0) == 0 ? len : -1;
454 }
455
456 D("-- usb_write --");
457 return len;
458 }
459
usb_read(usb_handle * h,void * _data,int len)460 int usb_read(usb_handle *h, void *_data, int len)
461 {
462 unsigned char *data = (unsigned char*) _data;
463 int n;
464
465 D("++ usb_read ++");
466 int orig_len = len;
467 while (len == orig_len) {
468 int xfer = len;
469
470 D("[ usb read %d fd = %d], path=%s", xfer, h->fd, h->path.c_str());
471 n = usb_bulk_read(h, data, xfer);
472 D("[ usb read %d ] = %d, path=%s", xfer, n, h->path.c_str());
473 if (n <= 0) {
474 if((errno == ETIMEDOUT) && (h->fd != -1)) {
475 D("[ timeout ]");
476 continue;
477 }
478 D("ERROR: n = %d, errno = %d (%s)",
479 n, errno, strerror(errno));
480 return -1;
481 }
482
483 len -= n;
484 data += n;
485 }
486
487 D("-- usb_read --");
488 return orig_len - len;
489 }
490
usb_reset(usb_handle * h)491 void usb_reset(usb_handle* h) {
492 ioctl(h->fd, USBDEVFS_RESET);
493 usb_kick(h);
494 }
495
usb_kick(usb_handle * h)496 void usb_kick(usb_handle* h) {
497 std::lock_guard<std::mutex> lock(h->mutex);
498 D("[ kicking %p (fd = %d) ]", h, h->fd);
499 if (!h->dead) {
500 h->dead = true;
501
502 if (h->writeable) {
503 /* HACK ALERT!
504 ** Sometimes we get stuck in ioctl(USBDEVFS_REAPURB).
505 ** This is a workaround for that problem.
506 */
507 if (h->reaper_thread) {
508 pthread_kill(h->reaper_thread, SIGALRM);
509 }
510
511 /* cancel any pending transactions
512 ** these will quietly fail if the txns are not active,
513 ** but this ensures that a reader blocked on REAPURB
514 ** will get unblocked
515 */
516 ioctl(h->fd, USBDEVFS_DISCARDURB, &h->urb_in);
517 ioctl(h->fd, USBDEVFS_DISCARDURB, &h->urb_out);
518 h->urb_in.status = -ENODEV;
519 h->urb_out.status = -ENODEV;
520 h->urb_in_busy = false;
521 h->urb_out_busy = false;
522 h->cv.notify_all();
523 } else {
524 unregister_usb_transport(h);
525 }
526 }
527 }
528
usb_close(usb_handle * h)529 int usb_close(usb_handle* h) {
530 std::lock_guard<std::mutex> lock(g_usb_handles_mutex);
531 g_usb_handles.remove(h);
532
533 D("-- usb close %p (fd = %d) --", h, h->fd);
534
535 delete h;
536
537 return 0;
538 }
539
usb_get_max_packet_size(usb_handle * h)540 size_t usb_get_max_packet_size(usb_handle* h) {
541 return h->max_packet_size;
542 }
543
register_device(const char * dev_name,const char * dev_path,unsigned char ep_in,unsigned char ep_out,int interface,int serial_index,unsigned zero_mask,size_t max_packet_size)544 static void register_device(const char* dev_name, const char* dev_path, unsigned char ep_in,
545 unsigned char ep_out, int interface, int serial_index,
546 unsigned zero_mask, size_t max_packet_size) {
547 // Read the device's serial number.
548 std::string serial_path =
549 android::base::StringPrintf("/sys/bus/usb/devices/%s/serial", dev_path + 4);
550 std::string serial;
551 if (!android::base::ReadFileToString(serial_path, &serial)) {
552 D("[ usb read %s failed: %s ]", serial_path.c_str(), strerror(errno));
553 // We don't actually want to treat an unknown serial as an error because
554 // devices aren't able to communicate a serial number in early bringup.
555 // http://b/20883914
556 serial = "";
557 }
558 serial = android::base::Trim(serial);
559
560 if (!transport_server_owns_device(dev_path, serial)) {
561 // We aren't allowed to communicate with this device. Don't open this device.
562 return;
563 }
564
565 // Since Linux will not reassign the device ID (and dev_name) as long as the
566 // device is open, we can add to the list here once we open it and remove
567 // from the list when we're finally closed and everything will work out
568 // fine.
569 //
570 // If we have a usb_handle on the list of handles with a matching name, we
571 // have no further work to do.
572 {
573 std::lock_guard<std::mutex> lock(g_usb_handles_mutex);
574 for (usb_handle* usb: g_usb_handles) {
575 if (usb->path == dev_name) {
576 return;
577 }
578 }
579 }
580
581 D("[ usb located new device %s (%d/%d/%d) ]", dev_name, ep_in, ep_out, interface);
582 std::unique_ptr<usb_handle> usb(new usb_handle);
583 usb->path = dev_name;
584 usb->ep_in = ep_in;
585 usb->ep_out = ep_out;
586 usb->zero_mask = zero_mask;
587 usb->max_packet_size = max_packet_size;
588
589 // Initialize mark so we don't get garbage collected after the device scan.
590 usb->mark = true;
591
592 usb->fd = unix_open(usb->path, O_RDWR | O_CLOEXEC);
593 if (usb->fd == -1) {
594 // Opening RW failed, so see if we have RO access.
595 usb->fd = unix_open(usb->path, O_RDONLY | O_CLOEXEC);
596 if (usb->fd == -1) {
597 D("[ usb open %s failed: %s]", usb->path.c_str(), strerror(errno));
598 return;
599 }
600 usb->writeable = 0;
601 }
602
603 D("[ usb opened %s%s, fd=%d]",
604 usb->path.c_str(), (usb->writeable ? "" : " (read-only)"), usb->fd);
605
606 if (usb->writeable) {
607 if (ioctl(usb->fd, USBDEVFS_CLAIMINTERFACE, &interface) != 0) {
608 D("[ usb ioctl(%d, USBDEVFS_CLAIMINTERFACE) failed: %s]", usb->fd, strerror(errno));
609 return;
610 }
611 }
612
613 // Add to the end of the active handles.
614 usb_handle* done_usb = usb.release();
615 {
616 std::lock_guard<std::mutex> lock(g_usb_handles_mutex);
617 g_usb_handles.push_back(done_usb);
618 }
619 register_usb_transport(done_usb, serial.c_str(), dev_path, done_usb->writeable);
620 }
621
device_poll_thread()622 static void device_poll_thread() {
623 adb_thread_setname("device poll");
624 D("Created device thread");
625 while (true) {
626 // TODO: Use inotify.
627 find_usb_device("/dev/bus/usb", register_device);
628 adb_notify_device_scan_complete();
629 kick_disconnected_devices();
630 std::this_thread::sleep_for(1s);
631 }
632 }
633
usb_init()634 void usb_init() {
635 struct sigaction actions;
636 memset(&actions, 0, sizeof(actions));
637 sigemptyset(&actions.sa_mask);
638 actions.sa_flags = 0;
639 actions.sa_handler = [](int) {};
640 sigaction(SIGALRM, &actions, nullptr);
641
642 std::thread(device_poll_thread).detach();
643 }
644
usb_cleanup()645 void usb_cleanup() {}
646