usb_libusb.cpp revision 5d002b8d6ae0a1eeefe09309ae6687a16e82ed08
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) : 66 name(name), 67 transfer(libusb_alloc_transfer(0)), 68 zero_mask(zero_mask) 69 { 70 } 71 72 ~transfer_info() { 73 libusb_free_transfer(transfer); 74 } 75 76 const char* name; 77 libusb_transfer* transfer; 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) 95 : device_address(device_address), 96 serial(serial), 97 closing(false), 98 device_handle(device_handle.release()), 99 read("read", zero_mask), 100 write("write", zero_mask), 101 interface(interface), 102 bulk_in(bulk_in), 103 bulk_out(bulk_out) { 104 } 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 149static auto& usb_handles = *new std::unordered_map<std::string, std::unique_ptr<usb_handle>>(); 150static auto& usb_handles_mutex = *new std::mutex(); 151 152static std::thread* device_poll_thread = nullptr; 153static std::atomic<bool> terminate_device_poll_thread(false); 154 155static std::string get_device_address(libusb_device* device) { 156 return StringPrintf("usb:%d:%d", libusb_get_bus_number(device), 157 libusb_get_device_address(device)); 158} 159 160static bool endpoint_is_output(uint8_t endpoint) { 161 return (endpoint & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_OUT; 162} 163 164static bool should_perform_zero_transfer(uint8_t endpoint, size_t write_length, uint16_t zero_mask) { 165 return endpoint_is_output(endpoint) && write_length != 0 && zero_mask != 0 && 166 (write_length & zero_mask) == 0; 167} 168 169static void poll_for_devices() { 170 libusb_device** list; 171 adb_thread_setname("device poll"); 172 while (!terminate_device_poll_thread) { 173 const ssize_t device_count = libusb_get_device_list(nullptr, &list); 174 175 LOG(VERBOSE) << "found " << device_count << " attached devices"; 176 177 for (ssize_t i = 0; i < device_count; ++i) { 178 libusb_device* device = list[i]; 179 std::string device_address = get_device_address(device); 180 std::string device_serial; 181 182 // Figure out if we want to open the device. 183 libusb_device_descriptor device_desc; 184 int rc = libusb_get_device_descriptor(device, &device_desc); 185 if (rc != 0) { 186 LOG(WARNING) << "failed to get device descriptor for device at " << device_address 187 << ": " << libusb_error_name(rc); 188 } 189 190 if (device_desc.bDeviceClass != LIBUSB_CLASS_PER_INTERFACE) { 191 // Assume that all Android devices have the device class set to per interface. 192 // TODO: Is this assumption valid? 193 LOG(VERBOSE) << "skipping device with incorrect class at " << device_address; 194 continue; 195 } 196 197 libusb_config_descriptor* config_raw; 198 rc = libusb_get_active_config_descriptor(device, &config_raw); 199 if (rc != 0) { 200 LOG(WARNING) << "failed to get active config descriptor for device at " 201 << device_address << ": " << libusb_error_name(rc); 202 continue; 203 } 204 const unique_config_descriptor config(config_raw); 205 206 // Use size_t for interface_num so <iostream>s don't mangle it. 207 size_t interface_num; 208 uint16_t zero_mask; 209 uint8_t bulk_in = 0, bulk_out = 0; 210 bool found_adb = false; 211 212 for (interface_num = 0; interface_num < config->bNumInterfaces; ++interface_num) { 213 const libusb_interface& interface = config->interface[interface_num]; 214 if (interface.num_altsetting != 1) { 215 // Assume that interfaces with alternate settings aren't adb interfaces. 216 // TODO: Is this assumption valid? 217 LOG(VERBOSE) << "skipping interface with incorrect num_altsetting at " 218 << device_address << " (interface " << interface_num << ")"; 219 continue; 220 } 221 222 const libusb_interface_descriptor& interface_desc = interface.altsetting[0]; 223 if (!is_adb_interface(interface_desc.bInterfaceClass, 224 interface_desc.bInterfaceSubClass, 225 interface_desc.bInterfaceProtocol)) { 226 LOG(VERBOSE) << "skipping non-adb interface at " << device_address 227 << " (interface " << interface_num << ")"; 228 continue; 229 } 230 231 LOG(VERBOSE) << "found potential adb interface at " << device_address 232 << " (interface " << interface_num << ")"; 233 234 bool found_in = false; 235 bool found_out = false; 236 for (size_t endpoint_num = 0; endpoint_num < interface_desc.bNumEndpoints; 237 ++endpoint_num) { 238 const auto& endpoint_desc = interface_desc.endpoint[endpoint_num]; 239 const uint8_t endpoint_addr = endpoint_desc.bEndpointAddress; 240 const uint8_t endpoint_attr = endpoint_desc.bmAttributes; 241 242 const uint8_t transfer_type = endpoint_attr & LIBUSB_TRANSFER_TYPE_MASK; 243 244 if (transfer_type != LIBUSB_TRANSFER_TYPE_BULK) { 245 continue; 246 } 247 248 if (endpoint_is_output(endpoint_addr) && !found_out) { 249 found_out = true; 250 bulk_out = endpoint_addr; 251 zero_mask = endpoint_desc.wMaxPacketSize - 1; 252 } else if (!endpoint_is_output(endpoint_addr) && !found_in) { 253 found_in = true; 254 bulk_in = endpoint_addr; 255 } 256 } 257 258 if (found_in && found_out) { 259 found_adb = true; 260 break; 261 } else { 262 LOG(VERBOSE) << "rejecting potential adb interface at " << device_address 263 << "(interface " << interface_num << "): missing bulk endpoints " 264 << "(found_in = " << found_in << ", found_out = " << found_out 265 << ")"; 266 } 267 } 268 269 if (!found_adb) { 270 LOG(VERBOSE) << "skipping device with no adb interfaces at " << device_address; 271 continue; 272 } 273 274 { 275 std::unique_lock<std::mutex> lock(usb_handles_mutex); 276 if (usb_handles.find(device_address) != usb_handles.end()) { 277 LOG(VERBOSE) << "device at " << device_address 278 << " has already been registered, skipping"; 279 continue; 280 } 281 } 282 283 libusb_device_handle* handle_raw; 284 rc = libusb_open(list[i], &handle_raw); 285 if (rc != 0) { 286 LOG(WARNING) << "failed to open usb device at " << device_address << ": " 287 << libusb_error_name(rc); 288 continue; 289 } 290 291 unique_device_handle handle(handle_raw); 292 LOG(DEBUG) << "successfully opened adb device at " << device_address << ", " 293 << StringPrintf("bulk_in = %#x, bulk_out = %#x", bulk_in, bulk_out); 294 295 device_serial.resize(255); 296 rc = libusb_get_string_descriptor_ascii( 297 handle_raw, device_desc.iSerialNumber, 298 reinterpret_cast<unsigned char*>(&device_serial[0]), device_serial.length()); 299 if (rc == 0) { 300 LOG(WARNING) << "received empty serial from device at " << device_address; 301 continue; 302 } else if (rc < 0) { 303 LOG(WARNING) << "failed to get serial from device at " << device_address 304 << libusb_error_name(rc); 305 continue; 306 } 307 device_serial.resize(rc); 308 309 // WARNING: this isn't released via RAII. 310 rc = libusb_claim_interface(handle.get(), interface_num); 311 if (rc != 0) { 312 LOG(WARNING) << "failed to claim adb interface for device '" << device_serial << "'" 313 << libusb_error_name(rc); 314 continue; 315 } 316 317 for (uint8_t endpoint : {bulk_in, bulk_out}) { 318 rc = libusb_clear_halt(handle.get(), endpoint); 319 if (rc != 0) { 320 LOG(WARNING) << "failed to clear halt on device '" << device_serial 321 << "' endpoint 0x" << std::hex << endpoint << ": " 322 << libusb_error_name(rc); 323 libusb_release_interface(handle.get(), interface_num); 324 continue; 325 } 326 } 327 328 auto result = 329 std::make_unique<usb_handle>(device_address, device_serial, std::move(handle), 330 interface_num, bulk_in, bulk_out, zero_mask); 331 usb_handle* usb_handle_raw = result.get(); 332 333 { 334 std::unique_lock<std::mutex> lock(usb_handles_mutex); 335 usb_handles[device_address] = std::move(result); 336 } 337 338 register_usb_transport(usb_handle_raw, device_serial.c_str(), device_address.c_str(), 1); 339 340 LOG(INFO) << "registered new usb device '" << device_serial << "'"; 341 } 342 libusb_free_device_list(list, 1); 343 344 std::this_thread::sleep_for(500ms); 345 } 346} 347 348void usb_init() { 349 LOG(DEBUG) << "initializing libusb..."; 350 int rc = libusb_init(nullptr); 351 if (rc != 0) { 352 LOG(FATAL) << "failed to initialize libusb: " << libusb_error_name(rc); 353 } 354 355 // Spawn a thread for libusb_handle_events. 356 std::thread([]() { 357 adb_thread_setname("libusb"); 358 while (true) { 359 libusb_handle_events(nullptr); 360 } 361 }).detach(); 362 363 // Spawn a thread to do device enumeration. 364 // TODO: Use libusb_hotplug_* instead? 365 device_poll_thread = new std::thread(poll_for_devices); 366 android::base::at_quick_exit([]() { 367 terminate_device_poll_thread = true; 368 std::unique_lock<std::mutex> lock(usb_handles_mutex); 369 for (auto& it : usb_handles) { 370 it.second->Close(); 371 } 372 lock.unlock(); 373 device_poll_thread->join(); 374 }); 375} 376 377// Dispatch a libusb transfer, unlock |device_lock|, and then wait for the result. 378static int perform_usb_transfer(usb_handle* h, transfer_info* info, 379 std::unique_lock<std::mutex> device_lock) { 380 libusb_transfer* transfer = info->transfer; 381 382 transfer->user_data = info; 383 transfer->callback = [](libusb_transfer* transfer) { 384 transfer_info* info = static_cast<transfer_info*>(transfer->user_data); 385 386 LOG(DEBUG) << info->name << " transfer callback entered"; 387 388 // Make sure that the original submitter has made it to the condition_variable wait. 389 std::unique_lock<std::mutex> lock(info->mutex); 390 391 LOG(DEBUG) << info->name << " callback successfully acquired lock"; 392 393 if (transfer->status != LIBUSB_TRANSFER_COMPLETED) { 394 LOG(WARNING) << info->name 395 << " transfer failed: " << libusb_error_name(transfer->status); 396 info->Notify(); 397 return; 398 } 399 400 if (transfer->actual_length != transfer->length) { 401 LOG(DEBUG) << info->name << " transfer incomplete, resubmitting"; 402 transfer->length -= transfer->actual_length; 403 transfer->buffer += transfer->actual_length; 404 int rc = libusb_submit_transfer(transfer); 405 if (rc != 0) { 406 LOG(WARNING) << "failed to submit " << info->name 407 << " transfer: " << libusb_error_name(rc); 408 transfer->status = LIBUSB_TRANSFER_ERROR; 409 info->Notify(); 410 } 411 return; 412 } 413 414 if (should_perform_zero_transfer(transfer->endpoint, transfer->length, info->zero_mask)) { 415 LOG(DEBUG) << "submitting zero-length write"; 416 transfer->length = 0; 417 int rc = libusb_submit_transfer(transfer); 418 if (rc != 0) { 419 LOG(WARNING) << "failed to submit zero-length write: " << libusb_error_name(rc); 420 transfer->status = LIBUSB_TRANSFER_ERROR; 421 info->Notify(); 422 } 423 return; 424 } 425 426 LOG(VERBOSE) << info->name << "transfer fully complete"; 427 info->Notify(); 428 }; 429 430 LOG(DEBUG) << "locking " << info->name << " transfer_info mutex"; 431 std::unique_lock<std::mutex> lock(info->mutex); 432 info->transfer_complete = false; 433 LOG(DEBUG) << "submitting " << info->name << " transfer"; 434 int rc = libusb_submit_transfer(transfer); 435 if (rc != 0) { 436 LOG(WARNING) << "failed to submit " << info->name << " transfer: " << libusb_error_name(rc); 437 errno = EIO; 438 return -1; 439 } 440 441 LOG(DEBUG) << info->name << " transfer successfully submitted"; 442 device_lock.unlock(); 443 info->cv.wait(lock, [info]() { return info->transfer_complete; }); 444 if (transfer->status != 0) { 445 errno = EIO; 446 return -1; 447 } 448 449 return 0; 450} 451 452int usb_write(usb_handle* h, const void* d, int len) { 453 LOG(DEBUG) << "usb_write of length " << len; 454 455 std::unique_lock<std::mutex> lock(h->device_handle_mutex); 456 if (!h->device_handle) { 457 errno = EIO; 458 return -1; 459 } 460 461 transfer_info* info = &h->write; 462 info->transfer->dev_handle = h->device_handle; 463 info->transfer->flags = 0; 464 info->transfer->endpoint = h->bulk_out; 465 info->transfer->type = LIBUSB_TRANSFER_TYPE_BULK; 466 info->transfer->length = len; 467 info->transfer->buffer = reinterpret_cast<unsigned char*>(const_cast<void*>(d)); 468 info->transfer->num_iso_packets = 0; 469 470 int rc = perform_usb_transfer(h, info, std::move(lock)); 471 LOG(DEBUG) << "usb_write(" << len << ") = " << rc; 472 return rc; 473} 474 475int usb_read(usb_handle* h, void* d, int len) { 476 LOG(DEBUG) << "usb_read of length " << len; 477 478 std::unique_lock<std::mutex> lock(h->device_handle_mutex); 479 if (!h->device_handle) { 480 errno = EIO; 481 return -1; 482 } 483 484 transfer_info* info = &h->read; 485 info->transfer->dev_handle = h->device_handle; 486 info->transfer->flags = 0; 487 info->transfer->endpoint = h->bulk_in; 488 info->transfer->type = LIBUSB_TRANSFER_TYPE_BULK; 489 info->transfer->length = len; 490 info->transfer->buffer = reinterpret_cast<unsigned char*>(d); 491 info->transfer->num_iso_packets = 0; 492 493 int rc = perform_usb_transfer(h, info, std::move(lock)); 494 LOG(DEBUG) << "usb_read(" << len << ") = " << rc; 495 return rc; 496} 497 498int usb_close(usb_handle* h) { 499 std::unique_lock<std::mutex> lock(usb_handles_mutex); 500 auto it = usb_handles.find(h->device_address); 501 if (it == usb_handles.end()) { 502 LOG(FATAL) << "attempted to close unregistered usb_handle for '" << h->serial << "'"; 503 } 504 usb_handles.erase(h->device_address); 505 return 0; 506} 507 508void usb_kick(usb_handle* h) { 509 h->Close(); 510} 511} // namespace libusb 512