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