blob: d39884ac7f514b0592894b08c4fc8139da4580a2 [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
355 std::this_thread::sleep_for(500ms);
356 }
357}
358
359void usb_init() {
360 LOG(DEBUG) << "initializing libusb...";
361 int rc = libusb_init(nullptr);
362 if (rc != 0) {
363 LOG(FATAL) << "failed to initialize libusb: " << libusb_error_name(rc);
364 }
365
366 // Spawn a thread for libusb_handle_events.
367 std::thread([]() {
368 adb_thread_setname("libusb");
369 while (true) {
370 libusb_handle_events(nullptr);
371 }
372 }).detach();
373
374 // Spawn a thread to do device enumeration.
375 // TODO: Use libusb_hotplug_* instead?
376 device_poll_thread = new std::thread(poll_for_devices);
377 android::base::at_quick_exit([]() {
378 terminate_device_poll_thread = true;
Josh Gaob7366922016-09-28 12:32:45 -0700379 device_poll_thread->join();
380 });
381}
382
383// Dispatch a libusb transfer, unlock |device_lock|, and then wait for the result.
384static int perform_usb_transfer(usb_handle* h, transfer_info* info,
385 std::unique_lock<std::mutex> device_lock) {
386 libusb_transfer* transfer = info->transfer;
387
388 transfer->user_data = info;
389 transfer->callback = [](libusb_transfer* transfer) {
390 transfer_info* info = static_cast<transfer_info*>(transfer->user_data);
391
392 LOG(DEBUG) << info->name << " transfer callback entered";
393
394 // Make sure that the original submitter has made it to the condition_variable wait.
395 std::unique_lock<std::mutex> lock(info->mutex);
396
397 LOG(DEBUG) << info->name << " callback successfully acquired lock";
398
399 if (transfer->status != LIBUSB_TRANSFER_COMPLETED) {
400 LOG(WARNING) << info->name
401 << " transfer failed: " << libusb_error_name(transfer->status);
402 info->Notify();
403 return;
404 }
405
Yabin Cui3cf1b362017-03-10 16:01:01 -0800406 // usb_read() can return when receiving some data.
407 if (info->is_bulk_out && transfer->actual_length != transfer->length) {
Josh Gaob7366922016-09-28 12:32:45 -0700408 LOG(DEBUG) << info->name << " transfer incomplete, resubmitting";
409 transfer->length -= transfer->actual_length;
410 transfer->buffer += transfer->actual_length;
411 int rc = libusb_submit_transfer(transfer);
412 if (rc != 0) {
413 LOG(WARNING) << "failed to submit " << info->name
414 << " transfer: " << libusb_error_name(rc);
415 transfer->status = LIBUSB_TRANSFER_ERROR;
416 info->Notify();
417 }
418 return;
419 }
420
421 if (should_perform_zero_transfer(transfer->endpoint, transfer->length, info->zero_mask)) {
422 LOG(DEBUG) << "submitting zero-length write";
423 transfer->length = 0;
424 int rc = libusb_submit_transfer(transfer);
425 if (rc != 0) {
426 LOG(WARNING) << "failed to submit zero-length write: " << libusb_error_name(rc);
427 transfer->status = LIBUSB_TRANSFER_ERROR;
428 info->Notify();
429 }
430 return;
431 }
432
433 LOG(VERBOSE) << info->name << "transfer fully complete";
434 info->Notify();
435 };
436
437 LOG(DEBUG) << "locking " << info->name << " transfer_info mutex";
438 std::unique_lock<std::mutex> lock(info->mutex);
439 info->transfer_complete = false;
440 LOG(DEBUG) << "submitting " << info->name << " transfer";
441 int rc = libusb_submit_transfer(transfer);
442 if (rc != 0) {
443 LOG(WARNING) << "failed to submit " << info->name << " transfer: " << libusb_error_name(rc);
444 errno = EIO;
445 return -1;
446 }
447
448 LOG(DEBUG) << info->name << " transfer successfully submitted";
449 device_lock.unlock();
450 info->cv.wait(lock, [info]() { return info->transfer_complete; });
451 if (transfer->status != 0) {
452 errno = EIO;
453 return -1;
454 }
455
456 return 0;
457}
458
459int usb_write(usb_handle* h, const void* d, int len) {
460 LOG(DEBUG) << "usb_write of length " << len;
461
462 std::unique_lock<std::mutex> lock(h->device_handle_mutex);
463 if (!h->device_handle) {
464 errno = EIO;
465 return -1;
466 }
467
468 transfer_info* info = &h->write;
469 info->transfer->dev_handle = h->device_handle;
470 info->transfer->flags = 0;
471 info->transfer->endpoint = h->bulk_out;
472 info->transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
473 info->transfer->length = len;
474 info->transfer->buffer = reinterpret_cast<unsigned char*>(const_cast<void*>(d));
475 info->transfer->num_iso_packets = 0;
476
477 int rc = perform_usb_transfer(h, info, std::move(lock));
478 LOG(DEBUG) << "usb_write(" << len << ") = " << rc;
479 return rc;
480}
481
482int usb_read(usb_handle* h, void* d, int len) {
483 LOG(DEBUG) << "usb_read of length " << len;
484
485 std::unique_lock<std::mutex> lock(h->device_handle_mutex);
486 if (!h->device_handle) {
487 errno = EIO;
488 return -1;
489 }
490
491 transfer_info* info = &h->read;
492 info->transfer->dev_handle = h->device_handle;
493 info->transfer->flags = 0;
494 info->transfer->endpoint = h->bulk_in;
495 info->transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
496 info->transfer->length = len;
497 info->transfer->buffer = reinterpret_cast<unsigned char*>(d);
498 info->transfer->num_iso_packets = 0;
499
500 int rc = perform_usb_transfer(h, info, std::move(lock));
Yabin Cui3cf1b362017-03-10 16:01:01 -0800501 LOG(DEBUG) << "usb_read(" << len << ") = " << rc << ", actual_length "
502 << info->transfer->actual_length;
503 if (rc < 0) {
504 return rc;
505 }
506 return info->transfer->actual_length;
Josh Gaob7366922016-09-28 12:32:45 -0700507}
508
509int usb_close(usb_handle* h) {
510 std::unique_lock<std::mutex> lock(usb_handles_mutex);
511 auto it = usb_handles.find(h->device_address);
512 if (it == usb_handles.end()) {
513 LOG(FATAL) << "attempted to close unregistered usb_handle for '" << h->serial << "'";
514 }
515 usb_handles.erase(h->device_address);
516 return 0;
517}
518
519void usb_kick(usb_handle* h) {
520 h->Close();
521}
Josh Gao3734cf02017-05-02 15:01:09 -0700522
523size_t usb_get_max_packet_size(usb_handle* h) {
524 CHECK(h->max_packet_size != 0);
525 return h->max_packet_size;
526}
527
Josh Gaob7366922016-09-28 12:32:45 -0700528} // namespace libusb