usb_libusb.cpp revision 6da1cd49b5eaeabb3febe584845de6bb3ae45873
1/* 2 * Copyright (C) 2016 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#include "usb.h" 18 19#include "sysdeps.h" 20 21#include <stdint.h> 22 23#include <atomic> 24#include <chrono> 25#include <memory> 26#include <mutex> 27#include <string> 28#include <thread> 29#include <unordered_map> 30 31#include <libusb/libusb.h> 32 33#include <android-base/file.h> 34#include <android-base/logging.h> 35#include <android-base/quick_exit.h> 36#include <android-base/stringprintf.h> 37#include <android-base/strings.h> 38 39#include "adb.h" 40#include "transport.h" 41#include "usb.h" 42 43using namespace std::literals; 44 45using android::base::StringPrintf; 46 47// RAII wrappers for libusb. 48struct ConfigDescriptorDeleter { 49 void operator()(libusb_config_descriptor* desc) { 50 libusb_free_config_descriptor(desc); 51 } 52}; 53 54using unique_config_descriptor = std::unique_ptr<libusb_config_descriptor, ConfigDescriptorDeleter>; 55 56struct DeviceHandleDeleter { 57 void operator()(libusb_device_handle* h) { 58 libusb_close(h); 59 } 60}; 61 62using unique_device_handle = std::unique_ptr<libusb_device_handle, DeviceHandleDeleter>; 63 64struct transfer_info { 65 transfer_info(const char* name, uint16_t zero_mask, bool is_bulk_out) 66 : name(name), 67 transfer(libusb_alloc_transfer(0)), 68 is_bulk_out(is_bulk_out), 69 zero_mask(zero_mask) {} 70 71 ~transfer_info() { 72 libusb_free_transfer(transfer); 73 } 74 75 const char* name; 76 libusb_transfer* transfer; 77 bool is_bulk_out; 78 bool transfer_complete; 79 std::condition_variable cv; 80 std::mutex mutex; 81 uint16_t zero_mask; 82 83 void Notify() { 84 LOG(DEBUG) << "notifying " << name << " transfer complete"; 85 transfer_complete = true; 86 cv.notify_one(); 87 } 88}; 89 90namespace libusb { 91struct usb_handle : public ::usb_handle { 92 usb_handle(const std::string& device_address, const std::string& serial, 93 unique_device_handle&& device_handle, uint8_t interface, uint8_t bulk_in, 94 uint8_t bulk_out, size_t zero_mask, size_t max_packet_size) 95 : device_address(device_address), 96 serial(serial), 97 closing(false), 98 device_handle(device_handle.release()), 99 read("read", zero_mask, false), 100 write("write", zero_mask, true), 101 interface(interface), 102 bulk_in(bulk_in), 103 bulk_out(bulk_out), 104 max_packet_size(max_packet_size) {} 105 106 ~usb_handle() { 107 Close(); 108 } 109 110 void Close() { 111 std::unique_lock<std::mutex> lock(device_handle_mutex); 112 // Cancelling transfers will trigger more Closes, so make sure this only happens once. 113 if (closing) { 114 return; 115 } 116 closing = true; 117 118 // Make sure that no new transfers come in. 119 libusb_device_handle* handle = device_handle; 120 if (!handle) { 121 return; 122 } 123 124 device_handle = nullptr; 125 126 // Cancel already dispatched transfers. 127 libusb_cancel_transfer(read.transfer); 128 libusb_cancel_transfer(write.transfer); 129 130 libusb_release_interface(handle, interface); 131 libusb_close(handle); 132 } 133 134 std::string device_address; 135 std::string serial; 136 137 std::atomic<bool> closing; 138 std::mutex device_handle_mutex; 139 libusb_device_handle* device_handle; 140 141 transfer_info read; 142 transfer_info write; 143 144 uint8_t interface; 145 uint8_t bulk_in; 146 uint8_t bulk_out; 147 148 size_t max_packet_size; 149}; 150 151static auto& usb_handles = *new std::unordered_map<std::string, std::unique_ptr<usb_handle>>(); 152static auto& usb_handles_mutex = *new std::mutex(); 153 154static libusb_hotplug_callback_handle hotplug_handle; 155 156static std::string get_device_address(libusb_device* device) { 157 return StringPrintf("usb:%d:%d", libusb_get_bus_number(device), 158 libusb_get_device_address(device)); 159} 160 161#if defined(__linux__) 162static std::string get_device_serial_path(libusb_device* device) { 163 uint8_t ports[7]; 164 int port_count = libusb_get_port_numbers(device, ports, 7); 165 if (port_count < 0) return ""; 166 167 std::string path = 168 StringPrintf("/sys/bus/usb/devices/%d-%d", libusb_get_bus_number(device), ports[0]); 169 for (int port = 1; port < port_count; ++port) { 170 path += StringPrintf(".%d", ports[port]); 171 } 172 path += "/serial"; 173 return path; 174} 175#endif 176 177static bool endpoint_is_output(uint8_t endpoint) { 178 return (endpoint & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_OUT; 179} 180 181static bool should_perform_zero_transfer(uint8_t endpoint, size_t write_length, uint16_t zero_mask) { 182 return endpoint_is_output(endpoint) && write_length != 0 && zero_mask != 0 && 183 (write_length & zero_mask) == 0; 184} 185 186static void process_device(libusb_device* device) { 187 std::string device_address = get_device_address(device); 188 std::string device_serial; 189 190 // Figure out if we want to open the device. 191 libusb_device_descriptor device_desc; 192 int rc = libusb_get_device_descriptor(device, &device_desc); 193 if (rc != 0) { 194 LOG(WARNING) << "failed to get device descriptor for device at " << device_address << ": " 195 << libusb_error_name(rc); 196 return; 197 } 198 199 if (device_desc.bDeviceClass != LIBUSB_CLASS_PER_INTERFACE) { 200 // Assume that all Android devices have the device class set to per interface. 201 // TODO: Is this assumption valid? 202 LOG(VERBOSE) << "skipping device with incorrect class at " << device_address; 203 return; 204 } 205 206 libusb_config_descriptor* config_raw; 207 rc = libusb_get_active_config_descriptor(device, &config_raw); 208 if (rc != 0) { 209 LOG(WARNING) << "failed to get active config descriptor for device at " << device_address 210 << ": " << libusb_error_name(rc); 211 return; 212 } 213 const unique_config_descriptor config(config_raw); 214 215 // Use size_t for interface_num so <iostream>s don't mangle it. 216 size_t interface_num; 217 uint16_t zero_mask; 218 uint8_t bulk_in = 0, bulk_out = 0; 219 size_t packet_size = 0; 220 bool found_adb = false; 221 222 for (interface_num = 0; interface_num < config->bNumInterfaces; ++interface_num) { 223 const libusb_interface& interface = config->interface[interface_num]; 224 if (interface.num_altsetting != 1) { 225 // Assume that interfaces with alternate settings aren't adb interfaces. 226 // TODO: Is this assumption valid? 227 LOG(VERBOSE) << "skipping interface with incorrect num_altsetting at " << device_address 228 << " (interface " << interface_num << ")"; 229 return; 230 } 231 232 const libusb_interface_descriptor& interface_desc = interface.altsetting[0]; 233 if (!is_adb_interface(interface_desc.bInterfaceClass, interface_desc.bInterfaceSubClass, 234 interface_desc.bInterfaceProtocol)) { 235 LOG(VERBOSE) << "skipping non-adb interface at " << device_address << " (interface " 236 << interface_num << ")"; 237 return; 238 } 239 240 LOG(VERBOSE) << "found potential adb interface at " << device_address << " (interface " 241 << interface_num << ")"; 242 243 bool found_in = false; 244 bool found_out = false; 245 for (size_t endpoint_num = 0; endpoint_num < interface_desc.bNumEndpoints; ++endpoint_num) { 246 const auto& endpoint_desc = interface_desc.endpoint[endpoint_num]; 247 const uint8_t endpoint_addr = endpoint_desc.bEndpointAddress; 248 const uint8_t endpoint_attr = endpoint_desc.bmAttributes; 249 250 const uint8_t transfer_type = endpoint_attr & LIBUSB_TRANSFER_TYPE_MASK; 251 252 if (transfer_type != LIBUSB_TRANSFER_TYPE_BULK) { 253 return; 254 } 255 256 if (endpoint_is_output(endpoint_addr) && !found_out) { 257 found_out = true; 258 bulk_out = endpoint_addr; 259 zero_mask = endpoint_desc.wMaxPacketSize - 1; 260 } else if (!endpoint_is_output(endpoint_addr) && !found_in) { 261 found_in = true; 262 bulk_in = endpoint_addr; 263 } 264 265 size_t endpoint_packet_size = endpoint_desc.wMaxPacketSize; 266 CHECK(endpoint_packet_size != 0); 267 if (packet_size == 0) { 268 packet_size = endpoint_packet_size; 269 } else { 270 CHECK(packet_size == endpoint_packet_size); 271 } 272 } 273 274 if (found_in && found_out) { 275 found_adb = true; 276 break; 277 } else { 278 LOG(VERBOSE) << "rejecting potential adb interface at " << device_address 279 << "(interface " << interface_num << "): missing bulk endpoints " 280 << "(found_in = " << found_in << ", found_out = " << found_out << ")"; 281 } 282 } 283 284 if (!found_adb) { 285 LOG(VERBOSE) << "skipping device with no adb interfaces at " << device_address; 286 return; 287 } 288 289 { 290 std::unique_lock<std::mutex> lock(usb_handles_mutex); 291 if (usb_handles.find(device_address) != usb_handles.end()) { 292 LOG(VERBOSE) << "device at " << device_address 293 << " has already been registered, skipping"; 294 return; 295 } 296 } 297 298 bool writable = true; 299 libusb_device_handle* handle_raw = nullptr; 300 rc = libusb_open(device, &handle_raw); 301 unique_device_handle handle(handle_raw); 302 if (rc == 0) { 303 LOG(DEBUG) << "successfully opened adb device at " << device_address << ", " 304 << StringPrintf("bulk_in = %#x, bulk_out = %#x", bulk_in, bulk_out); 305 306 device_serial.resize(255); 307 rc = libusb_get_string_descriptor_ascii(handle_raw, device_desc.iSerialNumber, 308 reinterpret_cast<unsigned char*>(&device_serial[0]), 309 device_serial.length()); 310 if (rc == 0) { 311 LOG(WARNING) << "received empty serial from device at " << device_address; 312 return; 313 } else if (rc < 0) { 314 LOG(WARNING) << "failed to get serial from device at " << device_address 315 << libusb_error_name(rc); 316 return; 317 } 318 device_serial.resize(rc); 319 320 // WARNING: this isn't released via RAII. 321 rc = libusb_claim_interface(handle.get(), interface_num); 322 if (rc != 0) { 323 LOG(WARNING) << "failed to claim adb interface for device '" << device_serial << "'" 324 << libusb_error_name(rc); 325 return; 326 } 327 328 for (uint8_t endpoint : {bulk_in, bulk_out}) { 329 rc = libusb_clear_halt(handle.get(), endpoint); 330 if (rc != 0) { 331 LOG(WARNING) << "failed to clear halt on device '" << device_serial 332 << "' endpoint 0x" << std::hex << endpoint << ": " 333 << libusb_error_name(rc); 334 libusb_release_interface(handle.get(), interface_num); 335 return; 336 } 337 } 338 } else { 339 LOG(WARNING) << "failed to open usb device at " << device_address << ": " 340 << libusb_error_name(rc); 341 writable = false; 342 343#if defined(__linux__) 344 // libusb doesn't think we should be messing around with devices we don't have 345 // write access to, but Linux at least lets us get the serial number anyway. 346 if (!android::base::ReadFileToString(get_device_serial_path(device), &device_serial)) { 347 // We don't actually want to treat an unknown serial as an error because 348 // devices aren't able to communicate a serial number in early bringup. 349 // http://b/20883914 350 device_serial = "unknown"; 351 } 352 device_serial = android::base::Trim(device_serial); 353#else 354 // On Mac OS and Windows, we're screwed. But I don't think this situation actually 355 // happens on those OSes. 356 return; 357#endif 358 } 359 360 auto result = 361 std::make_unique<usb_handle>(device_address, device_serial, std::move(handle), 362 interface_num, bulk_in, bulk_out, zero_mask, packet_size); 363 usb_handle* usb_handle_raw = result.get(); 364 365 { 366 std::unique_lock<std::mutex> lock(usb_handles_mutex); 367 usb_handles[device_address] = std::move(result); 368 } 369 370 register_usb_transport(usb_handle_raw, device_serial.c_str(), device_address.c_str(), writable); 371 372 LOG(INFO) << "registered new usb device '" << device_serial << "'"; 373} 374 375static void remove_device(libusb_device* device) { 376 std::string device_address = get_device_address(device); 377 378 LOG(INFO) << "device disconnected: " << device_address; 379 std::unique_lock<std::mutex> lock(usb_handles_mutex); 380 auto it = usb_handles.find(device_address); 381 if (it != usb_handles.end()) { 382 if (!it->second->device_handle) { 383 // If the handle is null, we were never able to open the device. 384 unregister_usb_transport(it->second.get()); 385 } 386 usb_handles.erase(it); 387 } 388} 389 390static int hotplug_callback(libusb_context*, libusb_device* device, libusb_hotplug_event event, 391 void*) { 392 if (event == LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED) { 393 process_device(device); 394 } else if (event == LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT) { 395 remove_device(device); 396 } 397 return 0; 398} 399 400void usb_init() { 401 LOG(DEBUG) << "initializing libusb..."; 402 int rc = libusb_init(nullptr); 403 if (rc != 0) { 404 LOG(FATAL) << "failed to initialize libusb: " << libusb_error_name(rc); 405 } 406 407 // Register the hotplug callback. 408 rc = libusb_hotplug_register_callback( 409 nullptr, static_cast<libusb_hotplug_event>(LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED | 410 LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT), 411 LIBUSB_HOTPLUG_ENUMERATE, LIBUSB_HOTPLUG_MATCH_ANY, LIBUSB_HOTPLUG_MATCH_ANY, 412 LIBUSB_CLASS_PER_INTERFACE, hotplug_callback, nullptr, &hotplug_handle); 413 414 if (rc != LIBUSB_SUCCESS) { 415 LOG(FATAL) << "failed to register libusb hotplug callback"; 416 } 417 418 adb_notify_device_scan_complete(); 419 420 // Spawn a thread for libusb_handle_events. 421 std::thread([]() { 422 adb_thread_setname("libusb"); 423 while (true) { 424 libusb_handle_events(nullptr); 425 } 426 }).detach(); 427} 428 429void usb_cleanup() { 430 libusb_hotplug_deregister_callback(nullptr, hotplug_handle); 431} 432 433// Dispatch a libusb transfer, unlock |device_lock|, and then wait for the result. 434static int perform_usb_transfer(usb_handle* h, transfer_info* info, 435 std::unique_lock<std::mutex> device_lock) { 436 libusb_transfer* transfer = info->transfer; 437 438 transfer->user_data = info; 439 transfer->callback = [](libusb_transfer* transfer) { 440 transfer_info* info = static_cast<transfer_info*>(transfer->user_data); 441 442 LOG(DEBUG) << info->name << " transfer callback entered"; 443 444 // Make sure that the original submitter has made it to the condition_variable wait. 445 std::unique_lock<std::mutex> lock(info->mutex); 446 447 LOG(DEBUG) << info->name << " callback successfully acquired lock"; 448 449 if (transfer->status != LIBUSB_TRANSFER_COMPLETED) { 450 LOG(WARNING) << info->name 451 << " transfer failed: " << libusb_error_name(transfer->status); 452 info->Notify(); 453 return; 454 } 455 456 // usb_read() can return when receiving some data. 457 if (info->is_bulk_out && transfer->actual_length != transfer->length) { 458 LOG(DEBUG) << info->name << " transfer incomplete, resubmitting"; 459 transfer->length -= transfer->actual_length; 460 transfer->buffer += transfer->actual_length; 461 int rc = libusb_submit_transfer(transfer); 462 if (rc != 0) { 463 LOG(WARNING) << "failed to submit " << info->name 464 << " transfer: " << libusb_error_name(rc); 465 transfer->status = LIBUSB_TRANSFER_ERROR; 466 info->Notify(); 467 } 468 return; 469 } 470 471 if (should_perform_zero_transfer(transfer->endpoint, transfer->length, info->zero_mask)) { 472 LOG(DEBUG) << "submitting zero-length write"; 473 transfer->length = 0; 474 int rc = libusb_submit_transfer(transfer); 475 if (rc != 0) { 476 LOG(WARNING) << "failed to submit zero-length write: " << libusb_error_name(rc); 477 transfer->status = LIBUSB_TRANSFER_ERROR; 478 info->Notify(); 479 } 480 return; 481 } 482 483 LOG(VERBOSE) << info->name << "transfer fully complete"; 484 info->Notify(); 485 }; 486 487 LOG(DEBUG) << "locking " << info->name << " transfer_info mutex"; 488 std::unique_lock<std::mutex> lock(info->mutex); 489 info->transfer_complete = false; 490 LOG(DEBUG) << "submitting " << info->name << " transfer"; 491 int rc = libusb_submit_transfer(transfer); 492 if (rc != 0) { 493 LOG(WARNING) << "failed to submit " << info->name << " transfer: " << libusb_error_name(rc); 494 errno = EIO; 495 return -1; 496 } 497 498 LOG(DEBUG) << info->name << " transfer successfully submitted"; 499 device_lock.unlock(); 500 info->cv.wait(lock, [info]() { return info->transfer_complete; }); 501 if (transfer->status != 0) { 502 errno = EIO; 503 return -1; 504 } 505 506 return 0; 507} 508 509int usb_write(usb_handle* h, const void* d, int len) { 510 LOG(DEBUG) << "usb_write of length " << len; 511 512 std::unique_lock<std::mutex> lock(h->device_handle_mutex); 513 if (!h->device_handle) { 514 errno = EIO; 515 return -1; 516 } 517 518 transfer_info* info = &h->write; 519 info->transfer->dev_handle = h->device_handle; 520 info->transfer->flags = 0; 521 info->transfer->endpoint = h->bulk_out; 522 info->transfer->type = LIBUSB_TRANSFER_TYPE_BULK; 523 info->transfer->length = len; 524 info->transfer->buffer = reinterpret_cast<unsigned char*>(const_cast<void*>(d)); 525 info->transfer->num_iso_packets = 0; 526 527 int rc = perform_usb_transfer(h, info, std::move(lock)); 528 LOG(DEBUG) << "usb_write(" << len << ") = " << rc; 529 return rc; 530} 531 532int usb_read(usb_handle* h, void* d, int len) { 533 LOG(DEBUG) << "usb_read of length " << len; 534 535 std::unique_lock<std::mutex> lock(h->device_handle_mutex); 536 if (!h->device_handle) { 537 errno = EIO; 538 return -1; 539 } 540 541 transfer_info* info = &h->read; 542 info->transfer->dev_handle = h->device_handle; 543 info->transfer->flags = 0; 544 info->transfer->endpoint = h->bulk_in; 545 info->transfer->type = LIBUSB_TRANSFER_TYPE_BULK; 546 info->transfer->length = len; 547 info->transfer->buffer = reinterpret_cast<unsigned char*>(d); 548 info->transfer->num_iso_packets = 0; 549 550 int rc = perform_usb_transfer(h, info, std::move(lock)); 551 LOG(DEBUG) << "usb_read(" << len << ") = " << rc << ", actual_length " 552 << info->transfer->actual_length; 553 if (rc < 0) { 554 return rc; 555 } 556 return info->transfer->actual_length; 557} 558 559int usb_close(usb_handle* h) { 560 std::unique_lock<std::mutex> lock(usb_handles_mutex); 561 auto it = usb_handles.find(h->device_address); 562 if (it == usb_handles.end()) { 563 LOG(FATAL) << "attempted to close unregistered usb_handle for '" << h->serial << "'"; 564 } 565 usb_handles.erase(h->device_address); 566 return 0; 567} 568 569void usb_kick(usb_handle* h) { 570 h->Close(); 571} 572 573size_t usb_get_max_packet_size(usb_handle* h) { 574 CHECK(h->max_packet_size != 0); 575 return h->max_packet_size; 576} 577 578} // namespace libusb 579