blob: 5a65865969ce8e9084eb095f8dbed1b25697067b [file] [log] [blame]
Josh Gaob7366922016-09-28 12:32:45 -07001/*
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 {
Yabin Cui3cf1b362017-03-10 16:01:01 -080065 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) {}
Josh Gaob7366922016-09-28 12:32:45 -070070
71 ~transfer_info() {
72 libusb_free_transfer(transfer);
73 }
74
75 const char* name;
76 libusb_transfer* transfer;
Yabin Cui3cf1b362017-03-10 16:01:01 -080077 bool is_bulk_out;
Josh Gaob7366922016-09-28 12:32:45 -070078 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,
Josh Gao3734cf02017-05-02 15:01:09 -070094 uint8_t bulk_out, size_t zero_mask, size_t max_packet_size)
Josh Gaob7366922016-09-28 12:32:45 -070095 : device_address(device_address),
96 serial(serial),
97 closing(false),
98 device_handle(device_handle.release()),
Yabin Cui3cf1b362017-03-10 16:01:01 -080099 read("read", zero_mask, false),
100 write("write", zero_mask, true),
Josh Gaob7366922016-09-28 12:32:45 -0700101 interface(interface),
102 bulk_in(bulk_in),
Josh Gao3734cf02017-05-02 15:01:09 -0700103 bulk_out(bulk_out),
104 max_packet_size(max_packet_size) {}
Josh Gaob7366922016-09-28 12:32:45 -0700105
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;
Josh Gao3734cf02017-05-02 15:01:09 -0700147
148 size_t max_packet_size;
Josh Gaob7366922016-09-28 12:32:45 -0700149};
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 std::thread* device_poll_thread = nullptr;
Josh Gao1ec15cd2017-05-08 17:51:07 -0700155static bool terminate_device_poll_thread = false;
156static auto& device_poll_mutex = *new std::mutex();
157static auto& device_poll_cv = *new std::condition_variable();
Josh Gaob7366922016-09-28 12:32:45 -0700158
159static std::string get_device_address(libusb_device* device) {
160 return StringPrintf("usb:%d:%d", libusb_get_bus_number(device),
161 libusb_get_device_address(device));
162}
163
Elliott Hughesac16a0f2017-05-05 16:26:00 -0700164#if defined(__linux__)
Elliott Hughes3e9e74e2017-05-03 17:25:34 -0700165static std::string get_device_serial_path(libusb_device* device) {
166 uint8_t ports[7];
167 int port_count = libusb_get_port_numbers(device, ports, 7);
168 if (port_count < 0) return "";
169
170 std::string path =
171 StringPrintf("/sys/bus/usb/devices/%d-%d", libusb_get_bus_number(device), ports[0]);
172 for (int port = 1; port < port_count; ++port) {
173 path += StringPrintf(".%d", ports[port]);
174 }
175 path += "/serial";
176 return path;
177}
Elliott Hughesac16a0f2017-05-05 16:26:00 -0700178#endif
Elliott Hughes3e9e74e2017-05-03 17:25:34 -0700179
Josh Gaob7366922016-09-28 12:32:45 -0700180static bool endpoint_is_output(uint8_t endpoint) {
181 return (endpoint & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_OUT;
182}
183
184static bool should_perform_zero_transfer(uint8_t endpoint, size_t write_length, uint16_t zero_mask) {
185 return endpoint_is_output(endpoint) && write_length != 0 && zero_mask != 0 &&
186 (write_length & zero_mask) == 0;
187}
188
Josh Gao9a700fd2017-05-05 18:19:21 -0700189static void process_device(libusb_device* device) {
190 std::string device_address = get_device_address(device);
191 std::string device_serial;
192
193 // Figure out if we want to open the device.
194 libusb_device_descriptor device_desc;
195 int rc = libusb_get_device_descriptor(device, &device_desc);
196 if (rc != 0) {
197 LOG(WARNING) << "failed to get device descriptor for device at " << device_address << ": "
198 << libusb_error_name(rc);
199 return;
200 }
201
202 if (device_desc.bDeviceClass != LIBUSB_CLASS_PER_INTERFACE) {
203 // Assume that all Android devices have the device class set to per interface.
204 // TODO: Is this assumption valid?
205 LOG(VERBOSE) << "skipping device with incorrect class at " << device_address;
206 return;
207 }
208
209 libusb_config_descriptor* config_raw;
210 rc = libusb_get_active_config_descriptor(device, &config_raw);
211 if (rc != 0) {
212 LOG(WARNING) << "failed to get active config descriptor for device at " << device_address
213 << ": " << libusb_error_name(rc);
214 return;
215 }
216 const unique_config_descriptor config(config_raw);
217
218 // Use size_t for interface_num so <iostream>s don't mangle it.
219 size_t interface_num;
220 uint16_t zero_mask;
221 uint8_t bulk_in = 0, bulk_out = 0;
222 size_t packet_size = 0;
223 bool found_adb = false;
224
225 for (interface_num = 0; interface_num < config->bNumInterfaces; ++interface_num) {
226 const libusb_interface& interface = config->interface[interface_num];
227 if (interface.num_altsetting != 1) {
228 // Assume that interfaces with alternate settings aren't adb interfaces.
229 // TODO: Is this assumption valid?
230 LOG(VERBOSE) << "skipping interface with incorrect num_altsetting at " << device_address
231 << " (interface " << interface_num << ")";
232 return;
233 }
234
235 const libusb_interface_descriptor& interface_desc = interface.altsetting[0];
236 if (!is_adb_interface(interface_desc.bInterfaceClass, interface_desc.bInterfaceSubClass,
237 interface_desc.bInterfaceProtocol)) {
238 LOG(VERBOSE) << "skipping non-adb interface at " << device_address << " (interface "
239 << interface_num << ")";
240 return;
241 }
242
243 LOG(VERBOSE) << "found potential adb interface at " << device_address << " (interface "
244 << interface_num << ")";
245
246 bool found_in = false;
247 bool found_out = false;
248 for (size_t endpoint_num = 0; endpoint_num < interface_desc.bNumEndpoints; ++endpoint_num) {
249 const auto& endpoint_desc = interface_desc.endpoint[endpoint_num];
250 const uint8_t endpoint_addr = endpoint_desc.bEndpointAddress;
251 const uint8_t endpoint_attr = endpoint_desc.bmAttributes;
252
253 const uint8_t transfer_type = endpoint_attr & LIBUSB_TRANSFER_TYPE_MASK;
254
255 if (transfer_type != LIBUSB_TRANSFER_TYPE_BULK) {
256 return;
257 }
258
259 if (endpoint_is_output(endpoint_addr) && !found_out) {
260 found_out = true;
261 bulk_out = endpoint_addr;
262 zero_mask = endpoint_desc.wMaxPacketSize - 1;
263 } else if (!endpoint_is_output(endpoint_addr) && !found_in) {
264 found_in = true;
265 bulk_in = endpoint_addr;
266 }
267
268 size_t endpoint_packet_size = endpoint_desc.wMaxPacketSize;
269 CHECK(endpoint_packet_size != 0);
270 if (packet_size == 0) {
271 packet_size = endpoint_packet_size;
272 } else {
273 CHECK(packet_size == endpoint_packet_size);
274 }
275 }
276
277 if (found_in && found_out) {
278 found_adb = true;
279 break;
280 } else {
281 LOG(VERBOSE) << "rejecting potential adb interface at " << device_address
282 << "(interface " << interface_num << "): missing bulk endpoints "
283 << "(found_in = " << found_in << ", found_out = " << found_out << ")";
284 }
285 }
286
287 if (!found_adb) {
288 LOG(VERBOSE) << "skipping device with no adb interfaces at " << device_address;
289 return;
290 }
291
292 {
293 std::unique_lock<std::mutex> lock(usb_handles_mutex);
294 if (usb_handles.find(device_address) != usb_handles.end()) {
295 LOG(VERBOSE) << "device at " << device_address
296 << " has already been registered, skipping";
297 return;
298 }
299 }
300
301 bool writable = true;
302 libusb_device_handle* handle_raw = nullptr;
303 rc = libusb_open(device, &handle_raw);
304 unique_device_handle handle(handle_raw);
305 if (rc == 0) {
306 LOG(DEBUG) << "successfully opened adb device at " << device_address << ", "
307 << StringPrintf("bulk_in = %#x, bulk_out = %#x", bulk_in, bulk_out);
308
309 device_serial.resize(255);
310 rc = libusb_get_string_descriptor_ascii(handle_raw, device_desc.iSerialNumber,
311 reinterpret_cast<unsigned char*>(&device_serial[0]),
312 device_serial.length());
313 if (rc == 0) {
314 LOG(WARNING) << "received empty serial from device at " << device_address;
315 return;
316 } else if (rc < 0) {
317 LOG(WARNING) << "failed to get serial from device at " << device_address
318 << libusb_error_name(rc);
319 return;
320 }
321 device_serial.resize(rc);
322
323 // WARNING: this isn't released via RAII.
324 rc = libusb_claim_interface(handle.get(), interface_num);
325 if (rc != 0) {
326 LOG(WARNING) << "failed to claim adb interface for device '" << device_serial << "'"
327 << libusb_error_name(rc);
328 return;
329 }
330
331 for (uint8_t endpoint : {bulk_in, bulk_out}) {
332 rc = libusb_clear_halt(handle.get(), endpoint);
333 if (rc != 0) {
334 LOG(WARNING) << "failed to clear halt on device '" << device_serial
335 << "' endpoint 0x" << std::hex << endpoint << ": "
336 << libusb_error_name(rc);
337 libusb_release_interface(handle.get(), interface_num);
338 return;
339 }
340 }
341 } else {
342 LOG(WARNING) << "failed to open usb device at " << device_address << ": "
343 << libusb_error_name(rc);
344 writable = false;
345
346#if defined(__linux__)
347 // libusb doesn't think we should be messing around with devices we don't have
348 // write access to, but Linux at least lets us get the serial number anyway.
349 if (!android::base::ReadFileToString(get_device_serial_path(device), &device_serial)) {
350 // We don't actually want to treat an unknown serial as an error because
351 // devices aren't able to communicate a serial number in early bringup.
352 // http://b/20883914
353 device_serial = "unknown";
354 }
355 device_serial = android::base::Trim(device_serial);
356#else
357 // On Mac OS and Windows, we're screwed. But I don't think this situation actually
358 // happens on those OSes.
359 return;
360#endif
361 }
362
363 auto result =
364 std::make_unique<usb_handle>(device_address, device_serial, std::move(handle),
365 interface_num, bulk_in, bulk_out, zero_mask, packet_size);
366 usb_handle* usb_handle_raw = result.get();
367
368 {
369 std::unique_lock<std::mutex> lock(usb_handles_mutex);
370 usb_handles[device_address] = std::move(result);
371 }
372
373 register_usb_transport(usb_handle_raw, device_serial.c_str(), device_address.c_str(), writable);
374
375 LOG(INFO) << "registered new usb device '" << device_serial << "'";
376}
377
Josh Gaob7366922016-09-28 12:32:45 -0700378static void poll_for_devices() {
379 libusb_device** list;
380 adb_thread_setname("device poll");
Josh Gao1ec15cd2017-05-08 17:51:07 -0700381 while (true) {
Josh Gaob7366922016-09-28 12:32:45 -0700382 const ssize_t device_count = libusb_get_device_list(nullptr, &list);
383
384 LOG(VERBOSE) << "found " << device_count << " attached devices";
385
386 for (ssize_t i = 0; i < device_count; ++i) {
Josh Gao9a700fd2017-05-05 18:19:21 -0700387 process_device(list[i]);
Josh Gaob7366922016-09-28 12:32:45 -0700388 }
Josh Gao9a700fd2017-05-05 18:19:21 -0700389
Josh Gaob7366922016-09-28 12:32:45 -0700390 libusb_free_device_list(list, 1);
391
Josh Gao1e3bf732017-05-03 22:37:10 -0700392 adb_notify_device_scan_complete();
393
Josh Gao1ec15cd2017-05-08 17:51:07 -0700394 std::unique_lock<std::mutex> lock(device_poll_mutex);
395 if (device_poll_cv.wait_for(lock, 500ms, []() { return terminate_device_poll_thread; })) {
396 return;
397 }
Josh Gaob7366922016-09-28 12:32:45 -0700398 }
399}
400
401void usb_init() {
402 LOG(DEBUG) << "initializing libusb...";
403 int rc = libusb_init(nullptr);
404 if (rc != 0) {
405 LOG(FATAL) << "failed to initialize libusb: " << libusb_error_name(rc);
406 }
407
408 // Spawn a thread for libusb_handle_events.
409 std::thread([]() {
410 adb_thread_setname("libusb");
411 while (true) {
412 libusb_handle_events(nullptr);
413 }
414 }).detach();
415
416 // Spawn a thread to do device enumeration.
417 // TODO: Use libusb_hotplug_* instead?
418 device_poll_thread = new std::thread(poll_for_devices);
419 android::base::at_quick_exit([]() {
Josh Gao1ec15cd2017-05-08 17:51:07 -0700420 {
421 std::unique_lock<std::mutex> lock(device_poll_mutex);
422 terminate_device_poll_thread = true;
423 }
424 device_poll_cv.notify_all();
Josh Gaob7366922016-09-28 12:32:45 -0700425 device_poll_thread->join();
426 });
427}
428
429// Dispatch a libusb transfer, unlock |device_lock|, and then wait for the result.
430static int perform_usb_transfer(usb_handle* h, transfer_info* info,
431 std::unique_lock<std::mutex> device_lock) {
432 libusb_transfer* transfer = info->transfer;
433
434 transfer->user_data = info;
435 transfer->callback = [](libusb_transfer* transfer) {
436 transfer_info* info = static_cast<transfer_info*>(transfer->user_data);
437
438 LOG(DEBUG) << info->name << " transfer callback entered";
439
440 // Make sure that the original submitter has made it to the condition_variable wait.
441 std::unique_lock<std::mutex> lock(info->mutex);
442
443 LOG(DEBUG) << info->name << " callback successfully acquired lock";
444
445 if (transfer->status != LIBUSB_TRANSFER_COMPLETED) {
446 LOG(WARNING) << info->name
447 << " transfer failed: " << libusb_error_name(transfer->status);
448 info->Notify();
449 return;
450 }
451
Yabin Cui3cf1b362017-03-10 16:01:01 -0800452 // usb_read() can return when receiving some data.
453 if (info->is_bulk_out && transfer->actual_length != transfer->length) {
Josh Gaob7366922016-09-28 12:32:45 -0700454 LOG(DEBUG) << info->name << " transfer incomplete, resubmitting";
455 transfer->length -= transfer->actual_length;
456 transfer->buffer += transfer->actual_length;
457 int rc = libusb_submit_transfer(transfer);
458 if (rc != 0) {
459 LOG(WARNING) << "failed to submit " << info->name
460 << " transfer: " << libusb_error_name(rc);
461 transfer->status = LIBUSB_TRANSFER_ERROR;
462 info->Notify();
463 }
464 return;
465 }
466
467 if (should_perform_zero_transfer(transfer->endpoint, transfer->length, info->zero_mask)) {
468 LOG(DEBUG) << "submitting zero-length write";
469 transfer->length = 0;
470 int rc = libusb_submit_transfer(transfer);
471 if (rc != 0) {
472 LOG(WARNING) << "failed to submit zero-length write: " << libusb_error_name(rc);
473 transfer->status = LIBUSB_TRANSFER_ERROR;
474 info->Notify();
475 }
476 return;
477 }
478
479 LOG(VERBOSE) << info->name << "transfer fully complete";
480 info->Notify();
481 };
482
483 LOG(DEBUG) << "locking " << info->name << " transfer_info mutex";
484 std::unique_lock<std::mutex> lock(info->mutex);
485 info->transfer_complete = false;
486 LOG(DEBUG) << "submitting " << info->name << " transfer";
487 int rc = libusb_submit_transfer(transfer);
488 if (rc != 0) {
489 LOG(WARNING) << "failed to submit " << info->name << " transfer: " << libusb_error_name(rc);
490 errno = EIO;
491 return -1;
492 }
493
494 LOG(DEBUG) << info->name << " transfer successfully submitted";
495 device_lock.unlock();
496 info->cv.wait(lock, [info]() { return info->transfer_complete; });
497 if (transfer->status != 0) {
498 errno = EIO;
499 return -1;
500 }
501
502 return 0;
503}
504
505int usb_write(usb_handle* h, const void* d, int len) {
506 LOG(DEBUG) << "usb_write of length " << len;
507
508 std::unique_lock<std::mutex> lock(h->device_handle_mutex);
509 if (!h->device_handle) {
510 errno = EIO;
511 return -1;
512 }
513
514 transfer_info* info = &h->write;
515 info->transfer->dev_handle = h->device_handle;
516 info->transfer->flags = 0;
517 info->transfer->endpoint = h->bulk_out;
518 info->transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
519 info->transfer->length = len;
520 info->transfer->buffer = reinterpret_cast<unsigned char*>(const_cast<void*>(d));
521 info->transfer->num_iso_packets = 0;
522
523 int rc = perform_usb_transfer(h, info, std::move(lock));
524 LOG(DEBUG) << "usb_write(" << len << ") = " << rc;
525 return rc;
526}
527
528int usb_read(usb_handle* h, void* d, int len) {
529 LOG(DEBUG) << "usb_read of length " << len;
530
531 std::unique_lock<std::mutex> lock(h->device_handle_mutex);
532 if (!h->device_handle) {
533 errno = EIO;
534 return -1;
535 }
536
537 transfer_info* info = &h->read;
538 info->transfer->dev_handle = h->device_handle;
539 info->transfer->flags = 0;
540 info->transfer->endpoint = h->bulk_in;
541 info->transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
542 info->transfer->length = len;
543 info->transfer->buffer = reinterpret_cast<unsigned char*>(d);
544 info->transfer->num_iso_packets = 0;
545
546 int rc = perform_usb_transfer(h, info, std::move(lock));
Yabin Cui3cf1b362017-03-10 16:01:01 -0800547 LOG(DEBUG) << "usb_read(" << len << ") = " << rc << ", actual_length "
548 << info->transfer->actual_length;
549 if (rc < 0) {
550 return rc;
551 }
552 return info->transfer->actual_length;
Josh Gaob7366922016-09-28 12:32:45 -0700553}
554
555int usb_close(usb_handle* h) {
556 std::unique_lock<std::mutex> lock(usb_handles_mutex);
557 auto it = usb_handles.find(h->device_address);
558 if (it == usb_handles.end()) {
559 LOG(FATAL) << "attempted to close unregistered usb_handle for '" << h->serial << "'";
560 }
561 usb_handles.erase(h->device_address);
562 return 0;
563}
564
565void usb_kick(usb_handle* h) {
566 h->Close();
567}
Josh Gao3734cf02017-05-02 15:01:09 -0700568
569size_t usb_get_max_packet_size(usb_handle* h) {
570 CHECK(h->max_packet_size != 0);
571 return h->max_packet_size;
572}
573
Josh Gaob7366922016-09-28 12:32:45 -0700574} // namespace libusb