blob: fec4742b2236bab0c1975bb223c1c2f3b0f0b057 [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,
94 uint8_t bulk_out, size_t zero_mask)
95 : 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),
Yabin Cui3cf1b362017-03-10 16:01:01 -0800103 bulk_out(bulk_out) {}
Josh Gaob7366922016-09-28 12:32:45 -0700104
105 ~usb_handle() {
106 Close();
107 }
108
109 void Close() {
110 std::unique_lock<std::mutex> lock(device_handle_mutex);
111 // Cancelling transfers will trigger more Closes, so make sure this only happens once.
112 if (closing) {
113 return;
114 }
115 closing = true;
116
117 // Make sure that no new transfers come in.
118 libusb_device_handle* handle = device_handle;
119 if (!handle) {
120 return;
121 }
122
123 device_handle = nullptr;
124
125 // Cancel already dispatched transfers.
126 libusb_cancel_transfer(read.transfer);
127 libusb_cancel_transfer(write.transfer);
128
129 libusb_release_interface(handle, interface);
130 libusb_close(handle);
131 }
132
133 std::string device_address;
134 std::string serial;
135
136 std::atomic<bool> closing;
137 std::mutex device_handle_mutex;
138 libusb_device_handle* device_handle;
139
140 transfer_info read;
141 transfer_info write;
142
143 uint8_t interface;
144 uint8_t bulk_in;
145 uint8_t bulk_out;
146};
147
148static auto& usb_handles = *new std::unordered_map<std::string, std::unique_ptr<usb_handle>>();
149static auto& usb_handles_mutex = *new std::mutex();
150
151static std::thread* device_poll_thread = nullptr;
152static std::atomic<bool> terminate_device_poll_thread(false);
153
154static std::string get_device_address(libusb_device* device) {
155 return StringPrintf("usb:%d:%d", libusb_get_bus_number(device),
156 libusb_get_device_address(device));
157}
158
159static bool endpoint_is_output(uint8_t endpoint) {
160 return (endpoint & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_OUT;
161}
162
163static bool should_perform_zero_transfer(uint8_t endpoint, size_t write_length, uint16_t zero_mask) {
164 return endpoint_is_output(endpoint) && write_length != 0 && zero_mask != 0 &&
165 (write_length & zero_mask) == 0;
166}
167
168static void poll_for_devices() {
169 libusb_device** list;
170 adb_thread_setname("device poll");
171 while (!terminate_device_poll_thread) {
172 const ssize_t device_count = libusb_get_device_list(nullptr, &list);
173
174 LOG(VERBOSE) << "found " << device_count << " attached devices";
175
176 for (ssize_t i = 0; i < device_count; ++i) {
177 libusb_device* device = list[i];
178 std::string device_address = get_device_address(device);
179 std::string device_serial;
180
181 // Figure out if we want to open the device.
182 libusb_device_descriptor device_desc;
183 int rc = libusb_get_device_descriptor(device, &device_desc);
184 if (rc != 0) {
185 LOG(WARNING) << "failed to get device descriptor for device at " << device_address
186 << ": " << libusb_error_name(rc);
187 }
188
189 if (device_desc.bDeviceClass != LIBUSB_CLASS_PER_INTERFACE) {
190 // Assume that all Android devices have the device class set to per interface.
191 // TODO: Is this assumption valid?
192 LOG(VERBOSE) << "skipping device with incorrect class at " << device_address;
193 continue;
194 }
195
196 libusb_config_descriptor* config_raw;
197 rc = libusb_get_active_config_descriptor(device, &config_raw);
198 if (rc != 0) {
199 LOG(WARNING) << "failed to get active config descriptor for device at "
200 << device_address << ": " << libusb_error_name(rc);
201 continue;
202 }
203 const unique_config_descriptor config(config_raw);
204
205 // Use size_t for interface_num so <iostream>s don't mangle it.
206 size_t interface_num;
207 uint16_t zero_mask;
208 uint8_t bulk_in = 0, bulk_out = 0;
209 bool found_adb = false;
210
211 for (interface_num = 0; interface_num < config->bNumInterfaces; ++interface_num) {
212 const libusb_interface& interface = config->interface[interface_num];
213 if (interface.num_altsetting != 1) {
214 // Assume that interfaces with alternate settings aren't adb interfaces.
215 // TODO: Is this assumption valid?
216 LOG(VERBOSE) << "skipping interface with incorrect num_altsetting at "
217 << device_address << " (interface " << interface_num << ")";
218 continue;
219 }
220
221 const libusb_interface_descriptor& interface_desc = interface.altsetting[0];
222 if (!is_adb_interface(interface_desc.bInterfaceClass,
223 interface_desc.bInterfaceSubClass,
224 interface_desc.bInterfaceProtocol)) {
225 LOG(VERBOSE) << "skipping non-adb interface at " << device_address
226 << " (interface " << interface_num << ")";
227 continue;
228 }
229
230 LOG(VERBOSE) << "found potential adb interface at " << device_address
231 << " (interface " << interface_num << ")";
232
233 bool found_in = false;
234 bool found_out = false;
235 for (size_t endpoint_num = 0; endpoint_num < interface_desc.bNumEndpoints;
236 ++endpoint_num) {
237 const auto& endpoint_desc = interface_desc.endpoint[endpoint_num];
238 const uint8_t endpoint_addr = endpoint_desc.bEndpointAddress;
239 const uint8_t endpoint_attr = endpoint_desc.bmAttributes;
240
241 const uint8_t transfer_type = endpoint_attr & LIBUSB_TRANSFER_TYPE_MASK;
242
243 if (transfer_type != LIBUSB_TRANSFER_TYPE_BULK) {
244 continue;
245 }
246
247 if (endpoint_is_output(endpoint_addr) && !found_out) {
248 found_out = true;
249 bulk_out = endpoint_addr;
250 zero_mask = endpoint_desc.wMaxPacketSize - 1;
251 } else if (!endpoint_is_output(endpoint_addr) && !found_in) {
252 found_in = true;
253 bulk_in = endpoint_addr;
254 }
255 }
256
257 if (found_in && found_out) {
258 found_adb = true;
259 break;
260 } else {
261 LOG(VERBOSE) << "rejecting potential adb interface at " << device_address
262 << "(interface " << interface_num << "): missing bulk endpoints "
263 << "(found_in = " << found_in << ", found_out = " << found_out
264 << ")";
265 }
266 }
267
268 if (!found_adb) {
269 LOG(VERBOSE) << "skipping device with no adb interfaces at " << device_address;
270 continue;
271 }
272
273 {
274 std::unique_lock<std::mutex> lock(usb_handles_mutex);
275 if (usb_handles.find(device_address) != usb_handles.end()) {
276 LOG(VERBOSE) << "device at " << device_address
277 << " has already been registered, skipping";
278 continue;
279 }
280 }
281
282 libusb_device_handle* handle_raw;
283 rc = libusb_open(list[i], &handle_raw);
284 if (rc != 0) {
285 LOG(WARNING) << "failed to open usb device at " << device_address << ": "
286 << libusb_error_name(rc);
287 continue;
288 }
289
290 unique_device_handle handle(handle_raw);
291 LOG(DEBUG) << "successfully opened adb device at " << device_address << ", "
292 << StringPrintf("bulk_in = %#x, bulk_out = %#x", bulk_in, bulk_out);
293
294 device_serial.resize(255);
295 rc = libusb_get_string_descriptor_ascii(
296 handle_raw, device_desc.iSerialNumber,
297 reinterpret_cast<unsigned char*>(&device_serial[0]), device_serial.length());
298 if (rc == 0) {
299 LOG(WARNING) << "received empty serial from device at " << device_address;
300 continue;
301 } else if (rc < 0) {
302 LOG(WARNING) << "failed to get serial from device at " << device_address
303 << libusb_error_name(rc);
304 continue;
305 }
306 device_serial.resize(rc);
307
Josh Gaob7366922016-09-28 12:32:45 -0700308 // WARNING: this isn't released via RAII.
309 rc = libusb_claim_interface(handle.get(), interface_num);
310 if (rc != 0) {
311 LOG(WARNING) << "failed to claim adb interface for device '" << device_serial << "'"
312 << libusb_error_name(rc);
313 continue;
314 }
315
316 for (uint8_t endpoint : {bulk_in, bulk_out}) {
317 rc = libusb_clear_halt(handle.get(), endpoint);
318 if (rc != 0) {
319 LOG(WARNING) << "failed to clear halt on device '" << device_serial
320 << "' endpoint 0x" << std::hex << endpoint << ": "
321 << libusb_error_name(rc);
322 libusb_release_interface(handle.get(), interface_num);
323 continue;
324 }
325 }
326
327 auto result =
328 std::make_unique<usb_handle>(device_address, device_serial, std::move(handle),
329 interface_num, bulk_in, bulk_out, zero_mask);
330 usb_handle* usb_handle_raw = result.get();
331
332 {
333 std::unique_lock<std::mutex> lock(usb_handles_mutex);
334 usb_handles[device_address] = std::move(result);
335 }
336
337 register_usb_transport(usb_handle_raw, device_serial.c_str(), device_address.c_str(), 1);
338
339 LOG(INFO) << "registered new usb device '" << device_serial << "'";
340 }
341 libusb_free_device_list(list, 1);
342
343 std::this_thread::sleep_for(500ms);
344 }
345}
346
347void usb_init() {
348 LOG(DEBUG) << "initializing libusb...";
349 int rc = libusb_init(nullptr);
350 if (rc != 0) {
351 LOG(FATAL) << "failed to initialize libusb: " << libusb_error_name(rc);
352 }
353
354 // Spawn a thread for libusb_handle_events.
355 std::thread([]() {
356 adb_thread_setname("libusb");
357 while (true) {
358 libusb_handle_events(nullptr);
359 }
360 }).detach();
361
362 // Spawn a thread to do device enumeration.
363 // TODO: Use libusb_hotplug_* instead?
364 device_poll_thread = new std::thread(poll_for_devices);
365 android::base::at_quick_exit([]() {
366 terminate_device_poll_thread = true;
Josh Gaob7366922016-09-28 12:32:45 -0700367 device_poll_thread->join();
368 });
369}
370
371// Dispatch a libusb transfer, unlock |device_lock|, and then wait for the result.
372static int perform_usb_transfer(usb_handle* h, transfer_info* info,
373 std::unique_lock<std::mutex> device_lock) {
374 libusb_transfer* transfer = info->transfer;
375
376 transfer->user_data = info;
377 transfer->callback = [](libusb_transfer* transfer) {
378 transfer_info* info = static_cast<transfer_info*>(transfer->user_data);
379
380 LOG(DEBUG) << info->name << " transfer callback entered";
381
382 // Make sure that the original submitter has made it to the condition_variable wait.
383 std::unique_lock<std::mutex> lock(info->mutex);
384
385 LOG(DEBUG) << info->name << " callback successfully acquired lock";
386
387 if (transfer->status != LIBUSB_TRANSFER_COMPLETED) {
388 LOG(WARNING) << info->name
389 << " transfer failed: " << libusb_error_name(transfer->status);
390 info->Notify();
391 return;
392 }
393
Yabin Cui3cf1b362017-03-10 16:01:01 -0800394 // usb_read() can return when receiving some data.
395 if (info->is_bulk_out && transfer->actual_length != transfer->length) {
Josh Gaob7366922016-09-28 12:32:45 -0700396 LOG(DEBUG) << info->name << " transfer incomplete, resubmitting";
397 transfer->length -= transfer->actual_length;
398 transfer->buffer += transfer->actual_length;
399 int rc = libusb_submit_transfer(transfer);
400 if (rc != 0) {
401 LOG(WARNING) << "failed to submit " << info->name
402 << " transfer: " << libusb_error_name(rc);
403 transfer->status = LIBUSB_TRANSFER_ERROR;
404 info->Notify();
405 }
406 return;
407 }
408
409 if (should_perform_zero_transfer(transfer->endpoint, transfer->length, info->zero_mask)) {
410 LOG(DEBUG) << "submitting zero-length write";
411 transfer->length = 0;
412 int rc = libusb_submit_transfer(transfer);
413 if (rc != 0) {
414 LOG(WARNING) << "failed to submit zero-length write: " << libusb_error_name(rc);
415 transfer->status = LIBUSB_TRANSFER_ERROR;
416 info->Notify();
417 }
418 return;
419 }
420
421 LOG(VERBOSE) << info->name << "transfer fully complete";
422 info->Notify();
423 };
424
425 LOG(DEBUG) << "locking " << info->name << " transfer_info mutex";
426 std::unique_lock<std::mutex> lock(info->mutex);
427 info->transfer_complete = false;
428 LOG(DEBUG) << "submitting " << info->name << " transfer";
429 int rc = libusb_submit_transfer(transfer);
430 if (rc != 0) {
431 LOG(WARNING) << "failed to submit " << info->name << " transfer: " << libusb_error_name(rc);
432 errno = EIO;
433 return -1;
434 }
435
436 LOG(DEBUG) << info->name << " transfer successfully submitted";
437 device_lock.unlock();
438 info->cv.wait(lock, [info]() { return info->transfer_complete; });
439 if (transfer->status != 0) {
440 errno = EIO;
441 return -1;
442 }
443
444 return 0;
445}
446
447int usb_write(usb_handle* h, const void* d, int len) {
448 LOG(DEBUG) << "usb_write of length " << len;
449
450 std::unique_lock<std::mutex> lock(h->device_handle_mutex);
451 if (!h->device_handle) {
452 errno = EIO;
453 return -1;
454 }
455
456 transfer_info* info = &h->write;
457 info->transfer->dev_handle = h->device_handle;
458 info->transfer->flags = 0;
459 info->transfer->endpoint = h->bulk_out;
460 info->transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
461 info->transfer->length = len;
462 info->transfer->buffer = reinterpret_cast<unsigned char*>(const_cast<void*>(d));
463 info->transfer->num_iso_packets = 0;
464
465 int rc = perform_usb_transfer(h, info, std::move(lock));
466 LOG(DEBUG) << "usb_write(" << len << ") = " << rc;
467 return rc;
468}
469
470int usb_read(usb_handle* h, void* d, int len) {
471 LOG(DEBUG) << "usb_read of length " << len;
472
473 std::unique_lock<std::mutex> lock(h->device_handle_mutex);
474 if (!h->device_handle) {
475 errno = EIO;
476 return -1;
477 }
478
479 transfer_info* info = &h->read;
480 info->transfer->dev_handle = h->device_handle;
481 info->transfer->flags = 0;
482 info->transfer->endpoint = h->bulk_in;
483 info->transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
484 info->transfer->length = len;
485 info->transfer->buffer = reinterpret_cast<unsigned char*>(d);
486 info->transfer->num_iso_packets = 0;
487
488 int rc = perform_usb_transfer(h, info, std::move(lock));
Yabin Cui3cf1b362017-03-10 16:01:01 -0800489 LOG(DEBUG) << "usb_read(" << len << ") = " << rc << ", actual_length "
490 << info->transfer->actual_length;
491 if (rc < 0) {
492 return rc;
493 }
494 return info->transfer->actual_length;
Josh Gaob7366922016-09-28 12:32:45 -0700495}
496
497int usb_close(usb_handle* h) {
498 std::unique_lock<std::mutex> lock(usb_handles_mutex);
499 auto it = usb_handles.find(h->device_address);
500 if (it == usb_handles.end()) {
501 LOG(FATAL) << "attempted to close unregistered usb_handle for '" << h->serial << "'";
502 }
503 usb_handles.erase(h->device_address);
504 return 0;
505}
506
507void usb_kick(usb_handle* h) {
508 h->Close();
509}
510} // namespace libusb