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