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 { 61 ~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 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 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 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 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 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::steady_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 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 409 static int usb_write_split(usb_handle* h, unsigned char* data, int len) { 410 for (int i = 0; i < len; i += 16384) { 411 int chunk_size = (i + 16384 > len) ? len - i : 16384; 412 int n = usb_bulk_write(h, data + i, chunk_size); 413 if (n != chunk_size) { 414 D("ERROR: n = %d, errno = %d (%s)", n, errno, strerror(errno)); 415 return -1; 416 } 417 } 418 419 return len; 420 } 421 422 int usb_write(usb_handle* h, const void* _data, int len) { 423 D("++ usb_write ++"); 424 425 unsigned char* data = (unsigned char*)_data; 426 427 // The kernel will attempt to allocate a contiguous buffer for each write we submit. 428 // This might fail due to heap fragmentation, so attempt a contiguous write once, and if that 429 // fails, retry after having split the data into 16kB chunks to avoid allocation failure. 430 int n = usb_bulk_write(h, data, len); 431 if (n == -1 && errno == ENOMEM) { 432 n = usb_write_split(h, data, len); 433 } 434 435 if (n == -1) { 436 return -1; 437 } 438 439 if (h->zero_mask && !(len & h->zero_mask)) { 440 // If we need 0-markers and our transfer is an even multiple of the packet size, 441 // then send a zero marker. 442 return usb_bulk_write(h, _data, 0) == 0 ? len : -1; 443 } 444 445 D("-- usb_write --"); 446 return len; 447 } 448 449 int usb_read(usb_handle *h, void *_data, int len) 450 { 451 unsigned char *data = (unsigned char*) _data; 452 int n; 453 454 D("++ usb_read ++"); 455 int orig_len = len; 456 while (len == orig_len) { 457 int xfer = len; 458 459 D("[ usb read %d fd = %d], path=%s", xfer, h->fd, h->path.c_str()); 460 n = usb_bulk_read(h, data, xfer); 461 D("[ usb read %d ] = %d, path=%s", xfer, n, h->path.c_str()); 462 if (n <= 0) { 463 if((errno == ETIMEDOUT) && (h->fd != -1)) { 464 D("[ timeout ]"); 465 continue; 466 } 467 D("ERROR: n = %d, errno = %d (%s)", 468 n, errno, strerror(errno)); 469 return -1; 470 } 471 472 len -= n; 473 data += n; 474 } 475 476 D("-- usb_read --"); 477 return orig_len - len; 478 } 479 480 void usb_reset(usb_handle* h) { 481 ioctl(h->fd, USBDEVFS_RESET); 482 usb_kick(h); 483 } 484 485 void usb_kick(usb_handle* h) { 486 std::lock_guard<std::mutex> lock(h->mutex); 487 D("[ kicking %p (fd = %d) ]", h, h->fd); 488 if (!h->dead) { 489 h->dead = true; 490 491 if (h->writeable) { 492 /* HACK ALERT! 493 ** Sometimes we get stuck in ioctl(USBDEVFS_REAPURB). 494 ** This is a workaround for that problem. 495 */ 496 if (h->reaper_thread) { 497 pthread_kill(h->reaper_thread, SIGALRM); 498 } 499 500 /* cancel any pending transactions 501 ** these will quietly fail if the txns are not active, 502 ** but this ensures that a reader blocked on REAPURB 503 ** will get unblocked 504 */ 505 ioctl(h->fd, USBDEVFS_DISCARDURB, &h->urb_in); 506 ioctl(h->fd, USBDEVFS_DISCARDURB, &h->urb_out); 507 h->urb_in.status = -ENODEV; 508 h->urb_out.status = -ENODEV; 509 h->urb_in_busy = false; 510 h->urb_out_busy = false; 511 h->cv.notify_all(); 512 } else { 513 unregister_usb_transport(h); 514 } 515 } 516 } 517 518 int usb_close(usb_handle* h) { 519 std::lock_guard<std::mutex> lock(g_usb_handles_mutex); 520 g_usb_handles.remove(h); 521 522 D("-- usb close %p (fd = %d) --", h, h->fd); 523 524 delete h; 525 526 return 0; 527 } 528 529 size_t usb_get_max_packet_size(usb_handle* h) { 530 return h->max_packet_size; 531 } 532 533 static void register_device(const char* dev_name, const char* dev_path, unsigned char ep_in, 534 unsigned char ep_out, int interface, int serial_index, 535 unsigned zero_mask, size_t max_packet_size) { 536 // Since Linux will not reassign the device ID (and dev_name) as long as the 537 // device is open, we can add to the list here once we open it and remove 538 // from the list when we're finally closed and everything will work out 539 // fine. 540 // 541 // If we have a usb_handle on the list of handles with a matching name, we 542 // have no further work to do. 543 { 544 std::lock_guard<std::mutex> lock(g_usb_handles_mutex); 545 for (usb_handle* usb: g_usb_handles) { 546 if (usb->path == dev_name) { 547 return; 548 } 549 } 550 } 551 552 D("[ usb located new device %s (%d/%d/%d) ]", dev_name, ep_in, ep_out, interface); 553 std::unique_ptr<usb_handle> usb(new usb_handle); 554 usb->path = dev_name; 555 usb->ep_in = ep_in; 556 usb->ep_out = ep_out; 557 usb->zero_mask = zero_mask; 558 usb->max_packet_size = max_packet_size; 559 560 // Initialize mark so we don't get garbage collected after the device scan. 561 usb->mark = true; 562 563 usb->fd = unix_open(usb->path, O_RDWR | O_CLOEXEC); 564 if (usb->fd == -1) { 565 // Opening RW failed, so see if we have RO access. 566 usb->fd = unix_open(usb->path, O_RDONLY | O_CLOEXEC); 567 if (usb->fd == -1) { 568 D("[ usb open %s failed: %s]", usb->path.c_str(), strerror(errno)); 569 return; 570 } 571 usb->writeable = 0; 572 } 573 574 D("[ usb opened %s%s, fd=%d]", 575 usb->path.c_str(), (usb->writeable ? "" : " (read-only)"), usb->fd); 576 577 if (usb->writeable) { 578 if (ioctl(usb->fd, USBDEVFS_CLAIMINTERFACE, &interface) != 0) { 579 D("[ usb ioctl(%d, USBDEVFS_CLAIMINTERFACE) failed: %s]", usb->fd, strerror(errno)); 580 return; 581 } 582 } 583 584 // Read the device's serial number. 585 std::string serial_path = android::base::StringPrintf( 586 "/sys/bus/usb/devices/%s/serial", dev_path + 4); 587 std::string serial; 588 if (!android::base::ReadFileToString(serial_path, &serial)) { 589 D("[ usb read %s failed: %s ]", serial_path.c_str(), strerror(errno)); 590 // We don't actually want to treat an unknown serial as an error because 591 // devices aren't able to communicate a serial number in early bringup. 592 // http://b/20883914 593 serial = ""; 594 } 595 serial = android::base::Trim(serial); 596 597 // Add to the end of the active handles. 598 usb_handle* done_usb = usb.release(); 599 { 600 std::lock_guard<std::mutex> lock(g_usb_handles_mutex); 601 g_usb_handles.push_back(done_usb); 602 } 603 register_usb_transport(done_usb, serial.c_str(), dev_path, done_usb->writeable); 604 } 605 606 static void device_poll_thread() { 607 adb_thread_setname("device poll"); 608 D("Created device thread"); 609 while (true) { 610 // TODO: Use inotify. 611 find_usb_device("/dev/bus/usb", register_device); 612 adb_notify_device_scan_complete(); 613 kick_disconnected_devices(); 614 std::this_thread::sleep_for(1s); 615 } 616 } 617 618 void usb_init() { 619 struct sigaction actions; 620 memset(&actions, 0, sizeof(actions)); 621 sigemptyset(&actions.sa_mask); 622 actions.sa_flags = 0; 623 actions.sa_handler = [](int) {}; 624 sigaction(SIGALRM, &actions, nullptr); 625 626 std::thread(device_poll_thread).detach(); 627 } 628 629 void usb_cleanup() {} 630