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