blob: 20610ee46518095f2a6a41b380527e0ee34a8546 [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
162static bool endpoint_is_output(uint8_t endpoint) {
163 return (endpoint & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_OUT;
164}
165
166static bool should_perform_zero_transfer(uint8_t endpoint, size_t write_length, uint16_t zero_mask) {
167 return endpoint_is_output(endpoint) && write_length != 0 && zero_mask != 0 &&
168 (write_length & zero_mask) == 0;
169}
170
171static void poll_for_devices() {
172 libusb_device** list;
173 adb_thread_setname("device poll");
174 while (!terminate_device_poll_thread) {
175 const ssize_t device_count = libusb_get_device_list(nullptr, &list);
176
177 LOG(VERBOSE) << "found " << device_count << " attached devices";
178
179 for (ssize_t i = 0; i < device_count; ++i) {
180 libusb_device* device = list[i];
181 std::string device_address = get_device_address(device);
182 std::string device_serial;
183
184 // Figure out if we want to open the device.
185 libusb_device_descriptor device_desc;
186 int rc = libusb_get_device_descriptor(device, &device_desc);
187 if (rc != 0) {
188 LOG(WARNING) << "failed to get device descriptor for device at " << device_address
189 << ": " << libusb_error_name(rc);
190 }
191
192 if (device_desc.bDeviceClass != LIBUSB_CLASS_PER_INTERFACE) {
193 // Assume that all Android devices have the device class set to per interface.
194 // TODO: Is this assumption valid?
195 LOG(VERBOSE) << "skipping device with incorrect class at " << device_address;
196 continue;
197 }
198
199 libusb_config_descriptor* config_raw;
200 rc = libusb_get_active_config_descriptor(device, &config_raw);
201 if (rc != 0) {
202 LOG(WARNING) << "failed to get active config descriptor for device at "
203 << device_address << ": " << libusb_error_name(rc);
204 continue;
205 }
206 const unique_config_descriptor config(config_raw);
207
208 // Use size_t for interface_num so <iostream>s don't mangle it.
209 size_t interface_num;
210 uint16_t zero_mask;
211 uint8_t bulk_in = 0, bulk_out = 0;
Josh Gao3734cf02017-05-02 15:01:09 -0700212 size_t packet_size = 0;
Josh Gaob7366922016-09-28 12:32:45 -0700213 bool found_adb = false;
214
215 for (interface_num = 0; interface_num < config->bNumInterfaces; ++interface_num) {
216 const libusb_interface& interface = config->interface[interface_num];
217 if (interface.num_altsetting != 1) {
218 // Assume that interfaces with alternate settings aren't adb interfaces.
219 // TODO: Is this assumption valid?
220 LOG(VERBOSE) << "skipping interface with incorrect num_altsetting at "
221 << device_address << " (interface " << interface_num << ")";
222 continue;
223 }
224
225 const libusb_interface_descriptor& interface_desc = interface.altsetting[0];
226 if (!is_adb_interface(interface_desc.bInterfaceClass,
227 interface_desc.bInterfaceSubClass,
228 interface_desc.bInterfaceProtocol)) {
229 LOG(VERBOSE) << "skipping non-adb interface at " << device_address
230 << " (interface " << interface_num << ")";
231 continue;
232 }
233
234 LOG(VERBOSE) << "found potential adb interface at " << device_address
235 << " (interface " << interface_num << ")";
236
237 bool found_in = false;
238 bool found_out = false;
239 for (size_t endpoint_num = 0; endpoint_num < interface_desc.bNumEndpoints;
240 ++endpoint_num) {
241 const auto& endpoint_desc = interface_desc.endpoint[endpoint_num];
242 const uint8_t endpoint_addr = endpoint_desc.bEndpointAddress;
243 const uint8_t endpoint_attr = endpoint_desc.bmAttributes;
244
245 const uint8_t transfer_type = endpoint_attr & LIBUSB_TRANSFER_TYPE_MASK;
246
247 if (transfer_type != LIBUSB_TRANSFER_TYPE_BULK) {
248 continue;
249 }
250
251 if (endpoint_is_output(endpoint_addr) && !found_out) {
252 found_out = true;
253 bulk_out = endpoint_addr;
254 zero_mask = endpoint_desc.wMaxPacketSize - 1;
255 } else if (!endpoint_is_output(endpoint_addr) && !found_in) {
256 found_in = true;
257 bulk_in = endpoint_addr;
258 }
Josh Gao3734cf02017-05-02 15:01:09 -0700259
260 size_t endpoint_packet_size = endpoint_desc.wMaxPacketSize;
261 CHECK(endpoint_packet_size != 0);
262 if (packet_size == 0) {
263 packet_size = endpoint_packet_size;
264 } else {
265 CHECK(packet_size == endpoint_packet_size);
266 }
Josh Gaob7366922016-09-28 12:32:45 -0700267 }
268
269 if (found_in && found_out) {
270 found_adb = true;
271 break;
272 } else {
273 LOG(VERBOSE) << "rejecting potential adb interface at " << device_address
274 << "(interface " << interface_num << "): missing bulk endpoints "
275 << "(found_in = " << found_in << ", found_out = " << found_out
276 << ")";
277 }
278 }
279
280 if (!found_adb) {
281 LOG(VERBOSE) << "skipping device with no adb interfaces at " << device_address;
282 continue;
283 }
284
285 {
286 std::unique_lock<std::mutex> lock(usb_handles_mutex);
287 if (usb_handles.find(device_address) != usb_handles.end()) {
288 LOG(VERBOSE) << "device at " << device_address
289 << " has already been registered, skipping";
290 continue;
291 }
292 }
293
294 libusb_device_handle* handle_raw;
Josh Gao3734cf02017-05-02 15:01:09 -0700295 rc = libusb_open(device, &handle_raw);
Josh Gaob7366922016-09-28 12:32:45 -0700296 if (rc != 0) {
297 LOG(WARNING) << "failed to open usb device at " << device_address << ": "
298 << libusb_error_name(rc);
299 continue;
300 }
301
302 unique_device_handle handle(handle_raw);
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(
308 handle_raw, device_desc.iSerialNumber,
309 reinterpret_cast<unsigned char*>(&device_serial[0]), device_serial.length());
310 if (rc == 0) {
311 LOG(WARNING) << "received empty serial from device at " << device_address;
312 continue;
313 } else if (rc < 0) {
314 LOG(WARNING) << "failed to get serial from device at " << device_address
315 << libusb_error_name(rc);
316 continue;
317 }
318 device_serial.resize(rc);
319
Josh Gaob7366922016-09-28 12:32:45 -0700320 // 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 continue;
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 continue;
336 }
337 }
338
Josh Gao3734cf02017-05-02 15:01:09 -0700339 auto result = std::make_unique<usb_handle>(device_address, device_serial,
340 std::move(handle), interface_num, bulk_in,
341 bulk_out, zero_mask, packet_size);
Josh Gaob7366922016-09-28 12:32:45 -0700342 usb_handle* usb_handle_raw = result.get();
343
344 {
345 std::unique_lock<std::mutex> lock(usb_handles_mutex);
346 usb_handles[device_address] = std::move(result);
347 }
348
349 register_usb_transport(usb_handle_raw, device_serial.c_str(), device_address.c_str(), 1);
350
351 LOG(INFO) << "registered new usb device '" << device_serial << "'";
352 }
353 libusb_free_device_list(list, 1);
354
Josh Gao1e3bf732017-05-03 22:37:10 -0700355 adb_notify_device_scan_complete();
356
Josh Gaob7366922016-09-28 12:32:45 -0700357 std::this_thread::sleep_for(500ms);
358 }
359}
360
361void usb_init() {
362 LOG(DEBUG) << "initializing libusb...";
363 int rc = libusb_init(nullptr);
364 if (rc != 0) {
365 LOG(FATAL) << "failed to initialize libusb: " << libusb_error_name(rc);
366 }
367
368 // Spawn a thread for libusb_handle_events.
369 std::thread([]() {
370 adb_thread_setname("libusb");
371 while (true) {
372 libusb_handle_events(nullptr);
373 }
374 }).detach();
375
376 // Spawn a thread to do device enumeration.
377 // TODO: Use libusb_hotplug_* instead?
378 device_poll_thread = new std::thread(poll_for_devices);
379 android::base::at_quick_exit([]() {
380 terminate_device_poll_thread = true;
Josh Gaob7366922016-09-28 12:32:45 -0700381 device_poll_thread->join();
382 });
383}
384
385// Dispatch a libusb transfer, unlock |device_lock|, and then wait for the result.
386static int perform_usb_transfer(usb_handle* h, transfer_info* info,
387 std::unique_lock<std::mutex> device_lock) {
388 libusb_transfer* transfer = info->transfer;
389
390 transfer->user_data = info;
391 transfer->callback = [](libusb_transfer* transfer) {
392 transfer_info* info = static_cast<transfer_info*>(transfer->user_data);
393
394 LOG(DEBUG) << info->name << " transfer callback entered";
395
396 // Make sure that the original submitter has made it to the condition_variable wait.
397 std::unique_lock<std::mutex> lock(info->mutex);
398
399 LOG(DEBUG) << info->name << " callback successfully acquired lock";
400
401 if (transfer->status != LIBUSB_TRANSFER_COMPLETED) {
402 LOG(WARNING) << info->name
403 << " transfer failed: " << libusb_error_name(transfer->status);
404 info->Notify();
405 return;
406 }
407
Yabin Cui3cf1b362017-03-10 16:01:01 -0800408 // usb_read() can return when receiving some data.
409 if (info->is_bulk_out && transfer->actual_length != transfer->length) {
Josh Gaob7366922016-09-28 12:32:45 -0700410 LOG(DEBUG) << info->name << " transfer incomplete, resubmitting";
411 transfer->length -= transfer->actual_length;
412 transfer->buffer += transfer->actual_length;
413 int rc = libusb_submit_transfer(transfer);
414 if (rc != 0) {
415 LOG(WARNING) << "failed to submit " << info->name
416 << " transfer: " << libusb_error_name(rc);
417 transfer->status = LIBUSB_TRANSFER_ERROR;
418 info->Notify();
419 }
420 return;
421 }
422
423 if (should_perform_zero_transfer(transfer->endpoint, transfer->length, info->zero_mask)) {
424 LOG(DEBUG) << "submitting zero-length write";
425 transfer->length = 0;
426 int rc = libusb_submit_transfer(transfer);
427 if (rc != 0) {
428 LOG(WARNING) << "failed to submit zero-length write: " << libusb_error_name(rc);
429 transfer->status = LIBUSB_TRANSFER_ERROR;
430 info->Notify();
431 }
432 return;
433 }
434
435 LOG(VERBOSE) << info->name << "transfer fully complete";
436 info->Notify();
437 };
438
439 LOG(DEBUG) << "locking " << info->name << " transfer_info mutex";
440 std::unique_lock<std::mutex> lock(info->mutex);
441 info->transfer_complete = false;
442 LOG(DEBUG) << "submitting " << info->name << " transfer";
443 int rc = libusb_submit_transfer(transfer);
444 if (rc != 0) {
445 LOG(WARNING) << "failed to submit " << info->name << " transfer: " << libusb_error_name(rc);
446 errno = EIO;
447 return -1;
448 }
449
450 LOG(DEBUG) << info->name << " transfer successfully submitted";
451 device_lock.unlock();
452 info->cv.wait(lock, [info]() { return info->transfer_complete; });
453 if (transfer->status != 0) {
454 errno = EIO;
455 return -1;
456 }
457
458 return 0;
459}
460
461int usb_write(usb_handle* h, const void* d, int len) {
462 LOG(DEBUG) << "usb_write of length " << len;
463
464 std::unique_lock<std::mutex> lock(h->device_handle_mutex);
465 if (!h->device_handle) {
466 errno = EIO;
467 return -1;
468 }
469
470 transfer_info* info = &h->write;
471 info->transfer->dev_handle = h->device_handle;
472 info->transfer->flags = 0;
473 info->transfer->endpoint = h->bulk_out;
474 info->transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
475 info->transfer->length = len;
476 info->transfer->buffer = reinterpret_cast<unsigned char*>(const_cast<void*>(d));
477 info->transfer->num_iso_packets = 0;
478
479 int rc = perform_usb_transfer(h, info, std::move(lock));
480 LOG(DEBUG) << "usb_write(" << len << ") = " << rc;
481 return rc;
482}
483
484int usb_read(usb_handle* h, void* d, int len) {
485 LOG(DEBUG) << "usb_read of length " << len;
486
487 std::unique_lock<std::mutex> lock(h->device_handle_mutex);
488 if (!h->device_handle) {
489 errno = EIO;
490 return -1;
491 }
492
493 transfer_info* info = &h->read;
494 info->transfer->dev_handle = h->device_handle;
495 info->transfer->flags = 0;
496 info->transfer->endpoint = h->bulk_in;
497 info->transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
498 info->transfer->length = len;
499 info->transfer->buffer = reinterpret_cast<unsigned char*>(d);
500 info->transfer->num_iso_packets = 0;
501
502 int rc = perform_usb_transfer(h, info, std::move(lock));
Yabin Cui3cf1b362017-03-10 16:01:01 -0800503 LOG(DEBUG) << "usb_read(" << len << ") = " << rc << ", actual_length "
504 << info->transfer->actual_length;
505 if (rc < 0) {
506 return rc;
507 }
508 return info->transfer->actual_length;
Josh Gaob7366922016-09-28 12:32:45 -0700509}
510
511int usb_close(usb_handle* h) {
512 std::unique_lock<std::mutex> lock(usb_handles_mutex);
513 auto it = usb_handles.find(h->device_address);
514 if (it == usb_handles.end()) {
515 LOG(FATAL) << "attempted to close unregistered usb_handle for '" << h->serial << "'";
516 }
517 usb_handles.erase(h->device_address);
518 return 0;
519}
520
521void usb_kick(usb_handle* h) {
522 h->Close();
523}
Josh Gao3734cf02017-05-02 15:01:09 -0700524
525size_t usb_get_max_packet_size(usb_handle* h) {
526 CHECK(h->max_packet_size != 0);
527 return h->max_packet_size;
528}
529
Josh Gaob7366922016-09-28 12:32:45 -0700530} // namespace libusb