1 /*
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
43 using namespace std::literals;
44
45 using android::base::StringPrintf;
46
47 // RAII wrappers for libusb.
48 struct ConfigDescriptorDeleter {
operator ()ConfigDescriptorDeleter49 void operator()(libusb_config_descriptor* desc) {
50 libusb_free_config_descriptor(desc);
51 }
52 };
53
54 using unique_config_descriptor = std::unique_ptr<libusb_config_descriptor, ConfigDescriptorDeleter>;
55
56 struct DeviceHandleDeleter {
operator ()DeviceHandleDeleter57 void operator()(libusb_device_handle* h) {
58 libusb_close(h);
59 }
60 };
61
62 using unique_device_handle = std::unique_ptr<libusb_device_handle, DeviceHandleDeleter>;
63
64 struct transfer_info {
transfer_infotransfer_info65 transfer_info(const char* name, uint16_t zero_mask) :
66 name(name),
67 transfer(libusb_alloc_transfer(0)),
68 zero_mask(zero_mask)
69 {
70 }
71
~transfer_infotransfer_info72 ~transfer_info() {
73 libusb_free_transfer(transfer);
74 }
75
76 const char* name;
77 libusb_transfer* transfer;
78 bool transfer_complete;
79 std::condition_variable cv;
80 std::mutex mutex;
81 uint16_t zero_mask;
82
Notifytransfer_info83 void Notify() {
84 LOG(DEBUG) << "notifying " << name << " transfer complete";
85 transfer_complete = true;
86 cv.notify_one();
87 }
88 };
89
90 namespace libusb {
91 struct usb_handle : public ::usb_handle {
usb_handlelibusb::usb_handle92 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()),
99 read("read", zero_mask),
100 write("write", zero_mask),
101 interface(interface),
102 bulk_in(bulk_in),
103 bulk_out(bulk_out) {
104 }
105
~usb_handlelibusb::usb_handle106 ~usb_handle() {
107 Close();
108 }
109
Closelibusb::usb_handle110 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;
147 };
148
149 static auto& usb_handles = *new std::unordered_map<std::string, std::unique_ptr<usb_handle>>();
150 static auto& usb_handles_mutex = *new std::mutex();
151
152 static std::thread* device_poll_thread = nullptr;
153 static std::atomic<bool> terminate_device_poll_thread(false);
154
get_device_address(libusb_device * device)155 static std::string get_device_address(libusb_device* device) {
156 return StringPrintf("usb:%d:%d", libusb_get_bus_number(device),
157 libusb_get_device_address(device));
158 }
159
endpoint_is_output(uint8_t endpoint)160 static bool endpoint_is_output(uint8_t endpoint) {
161 return (endpoint & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_OUT;
162 }
163
should_perform_zero_transfer(uint8_t endpoint,size_t write_length,uint16_t zero_mask)164 static bool should_perform_zero_transfer(uint8_t endpoint, size_t write_length, uint16_t zero_mask) {
165 return endpoint_is_output(endpoint) && write_length != 0 && zero_mask != 0 &&
166 (write_length & zero_mask) == 0;
167 }
168
poll_for_devices()169 static void poll_for_devices() {
170 libusb_device** list;
171 adb_thread_setname("device poll");
172 while (!terminate_device_poll_thread) {
173 const ssize_t device_count = libusb_get_device_list(nullptr, &list);
174
175 LOG(VERBOSE) << "found " << device_count << " attached devices";
176
177 for (ssize_t i = 0; i < device_count; ++i) {
178 libusb_device* device = list[i];
179 std::string device_address = get_device_address(device);
180 std::string device_serial;
181
182 // Figure out if we want to open the device.
183 libusb_device_descriptor device_desc;
184 int rc = libusb_get_device_descriptor(device, &device_desc);
185 if (rc != 0) {
186 LOG(WARNING) << "failed to get device descriptor for device at " << device_address
187 << ": " << libusb_error_name(rc);
188 }
189
190 if (device_desc.bDeviceClass != LIBUSB_CLASS_PER_INTERFACE) {
191 // Assume that all Android devices have the device class set to per interface.
192 // TODO: Is this assumption valid?
193 LOG(VERBOSE) << "skipping device with incorrect class at " << device_address;
194 continue;
195 }
196
197 libusb_config_descriptor* config_raw;
198 rc = libusb_get_active_config_descriptor(device, &config_raw);
199 if (rc != 0) {
200 LOG(WARNING) << "failed to get active config descriptor for device at "
201 << device_address << ": " << libusb_error_name(rc);
202 continue;
203 }
204 const unique_config_descriptor config(config_raw);
205
206 // Use size_t for interface_num so <iostream>s don't mangle it.
207 size_t interface_num;
208 uint16_t zero_mask;
209 uint8_t bulk_in = 0, bulk_out = 0;
210 bool found_adb = false;
211
212 for (interface_num = 0; interface_num < config->bNumInterfaces; ++interface_num) {
213 const libusb_interface& interface = config->interface[interface_num];
214 if (interface.num_altsetting != 1) {
215 // Assume that interfaces with alternate settings aren't adb interfaces.
216 // TODO: Is this assumption valid?
217 LOG(VERBOSE) << "skipping interface with incorrect num_altsetting at "
218 << device_address << " (interface " << interface_num << ")";
219 continue;
220 }
221
222 const libusb_interface_descriptor& interface_desc = interface.altsetting[0];
223 if (!is_adb_interface(interface_desc.bInterfaceClass,
224 interface_desc.bInterfaceSubClass,
225 interface_desc.bInterfaceProtocol)) {
226 LOG(VERBOSE) << "skipping non-adb interface at " << device_address
227 << " (interface " << interface_num << ")";
228 continue;
229 }
230
231 LOG(VERBOSE) << "found potential adb interface at " << device_address
232 << " (interface " << interface_num << ")";
233
234 bool found_in = false;
235 bool found_out = false;
236 for (size_t endpoint_num = 0; endpoint_num < interface_desc.bNumEndpoints;
237 ++endpoint_num) {
238 const auto& endpoint_desc = interface_desc.endpoint[endpoint_num];
239 const uint8_t endpoint_addr = endpoint_desc.bEndpointAddress;
240 const uint8_t endpoint_attr = endpoint_desc.bmAttributes;
241
242 const uint8_t transfer_type = endpoint_attr & LIBUSB_TRANSFER_TYPE_MASK;
243
244 if (transfer_type != LIBUSB_TRANSFER_TYPE_BULK) {
245 continue;
246 }
247
248 if (endpoint_is_output(endpoint_addr) && !found_out) {
249 found_out = true;
250 bulk_out = endpoint_addr;
251 zero_mask = endpoint_desc.wMaxPacketSize - 1;
252 } else if (!endpoint_is_output(endpoint_addr) && !found_in) {
253 found_in = true;
254 bulk_in = endpoint_addr;
255 }
256 }
257
258 if (found_in && found_out) {
259 found_adb = true;
260 break;
261 } else {
262 LOG(VERBOSE) << "rejecting potential adb interface at " << device_address
263 << "(interface " << interface_num << "): missing bulk endpoints "
264 << "(found_in = " << found_in << ", found_out = " << found_out
265 << ")";
266 }
267 }
268
269 if (!found_adb) {
270 LOG(VERBOSE) << "skipping device with no adb interfaces at " << device_address;
271 continue;
272 }
273
274 {
275 std::unique_lock<std::mutex> lock(usb_handles_mutex);
276 if (usb_handles.find(device_address) != usb_handles.end()) {
277 LOG(VERBOSE) << "device at " << device_address
278 << " has already been registered, skipping";
279 continue;
280 }
281 }
282
283 libusb_device_handle* handle_raw;
284 rc = libusb_open(list[i], &handle_raw);
285 if (rc != 0) {
286 LOG(WARNING) << "failed to open usb device at " << device_address << ": "
287 << libusb_error_name(rc);
288 continue;
289 }
290
291 unique_device_handle handle(handle_raw);
292 LOG(DEBUG) << "successfully opened adb device at " << device_address << ", "
293 << StringPrintf("bulk_in = %#x, bulk_out = %#x", bulk_in, bulk_out);
294
295 device_serial.resize(255);
296 rc = libusb_get_string_descriptor_ascii(
297 handle_raw, device_desc.iSerialNumber,
298 reinterpret_cast<unsigned char*>(&device_serial[0]), device_serial.length());
299 if (rc == 0) {
300 LOG(WARNING) << "received empty serial from device at " << device_address;
301 continue;
302 } else if (rc < 0) {
303 LOG(WARNING) << "failed to get serial from device at " << device_address
304 << libusb_error_name(rc);
305 continue;
306 }
307 device_serial.resize(rc);
308
309 // Try to reset the device.
310 rc = libusb_reset_device(handle_raw);
311 if (rc != 0) {
312 LOG(WARNING) << "failed to reset opened device '" << device_serial
313 << "': " << libusb_error_name(rc);
314 continue;
315 }
316
317 // WARNING: this isn't released via RAII.
318 rc = libusb_claim_interface(handle.get(), interface_num);
319 if (rc != 0) {
320 LOG(WARNING) << "failed to claim adb interface for device '" << device_serial << "'"
321 << libusb_error_name(rc);
322 continue;
323 }
324
325 for (uint8_t endpoint : {bulk_in, bulk_out}) {
326 rc = libusb_clear_halt(handle.get(), endpoint);
327 if (rc != 0) {
328 LOG(WARNING) << "failed to clear halt on device '" << device_serial
329 << "' endpoint 0x" << std::hex << endpoint << ": "
330 << libusb_error_name(rc);
331 libusb_release_interface(handle.get(), interface_num);
332 continue;
333 }
334 }
335
336 auto result =
337 std::make_unique<usb_handle>(device_address, device_serial, std::move(handle),
338 interface_num, bulk_in, bulk_out, zero_mask);
339 usb_handle* usb_handle_raw = result.get();
340
341 {
342 std::unique_lock<std::mutex> lock(usb_handles_mutex);
343 usb_handles[device_address] = std::move(result);
344 }
345
346 register_usb_transport(usb_handle_raw, device_serial.c_str(), device_address.c_str(), 1);
347
348 LOG(INFO) << "registered new usb device '" << device_serial << "'";
349 }
350 libusb_free_device_list(list, 1);
351
352 std::this_thread::sleep_for(500ms);
353 }
354 }
355
usb_init()356 void usb_init() {
357 LOG(DEBUG) << "initializing libusb...";
358 int rc = libusb_init(nullptr);
359 if (rc != 0) {
360 LOG(FATAL) << "failed to initialize libusb: " << libusb_error_name(rc);
361 }
362
363 // Spawn a thread for libusb_handle_events.
364 std::thread([]() {
365 adb_thread_setname("libusb");
366 while (true) {
367 libusb_handle_events(nullptr);
368 }
369 }).detach();
370
371 // Spawn a thread to do device enumeration.
372 // TODO: Use libusb_hotplug_* instead?
373 device_poll_thread = new std::thread(poll_for_devices);
374 android::base::at_quick_exit([]() {
375 terminate_device_poll_thread = true;
376 std::unique_lock<std::mutex> lock(usb_handles_mutex);
377 for (auto& it : usb_handles) {
378 it.second->Close();
379 }
380 lock.unlock();
381 device_poll_thread->join();
382 });
383 }
384
385 // Dispatch a libusb transfer, unlock |device_lock|, and then wait for the result.
perform_usb_transfer(usb_handle * h,transfer_info * info,std::unique_lock<std::mutex> device_lock)386 static 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
408 if (transfer->actual_length != transfer->length) {
409 LOG(DEBUG) << info->name << " transfer incomplete, resubmitting";
410 transfer->length -= transfer->actual_length;
411 transfer->buffer += transfer->actual_length;
412 int rc = libusb_submit_transfer(transfer);
413 if (rc != 0) {
414 LOG(WARNING) << "failed to submit " << info->name
415 << " transfer: " << libusb_error_name(rc);
416 transfer->status = LIBUSB_TRANSFER_ERROR;
417 info->Notify();
418 }
419 return;
420 }
421
422 if (should_perform_zero_transfer(transfer->endpoint, transfer->length, info->zero_mask)) {
423 LOG(DEBUG) << "submitting zero-length write";
424 transfer->length = 0;
425 int rc = libusb_submit_transfer(transfer);
426 if (rc != 0) {
427 LOG(WARNING) << "failed to submit zero-length write: " << libusb_error_name(rc);
428 transfer->status = LIBUSB_TRANSFER_ERROR;
429 info->Notify();
430 }
431 return;
432 }
433
434 LOG(VERBOSE) << info->name << "transfer fully complete";
435 info->Notify();
436 };
437
438 LOG(DEBUG) << "locking " << info->name << " transfer_info mutex";
439 std::unique_lock<std::mutex> lock(info->mutex);
440 info->transfer_complete = false;
441 LOG(DEBUG) << "submitting " << info->name << " transfer";
442 int rc = libusb_submit_transfer(transfer);
443 if (rc != 0) {
444 LOG(WARNING) << "failed to submit " << info->name << " transfer: " << libusb_error_name(rc);
445 errno = EIO;
446 return -1;
447 }
448
449 LOG(DEBUG) << info->name << " transfer successfully submitted";
450 device_lock.unlock();
451 info->cv.wait(lock, [info]() { return info->transfer_complete; });
452 if (transfer->status != 0) {
453 errno = EIO;
454 return -1;
455 }
456
457 return 0;
458 }
459
usb_write(usb_handle * h,const void * d,int len)460 int usb_write(usb_handle* h, const void* d, int len) {
461 LOG(DEBUG) << "usb_write of length " << len;
462
463 std::unique_lock<std::mutex> lock(h->device_handle_mutex);
464 if (!h->device_handle) {
465 errno = EIO;
466 return -1;
467 }
468
469 transfer_info* info = &h->write;
470 info->transfer->dev_handle = h->device_handle;
471 info->transfer->flags = 0;
472 info->transfer->endpoint = h->bulk_out;
473 info->transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
474 info->transfer->length = len;
475 info->transfer->buffer = reinterpret_cast<unsigned char*>(const_cast<void*>(d));
476 info->transfer->num_iso_packets = 0;
477
478 int rc = perform_usb_transfer(h, info, std::move(lock));
479 LOG(DEBUG) << "usb_write(" << len << ") = " << rc;
480 return rc;
481 }
482
usb_read(usb_handle * h,void * d,int len)483 int usb_read(usb_handle* h, void* d, int len) {
484 LOG(DEBUG) << "usb_read of length " << len;
485
486 std::unique_lock<std::mutex> lock(h->device_handle_mutex);
487 if (!h->device_handle) {
488 errno = EIO;
489 return -1;
490 }
491
492 transfer_info* info = &h->read;
493 info->transfer->dev_handle = h->device_handle;
494 info->transfer->flags = 0;
495 info->transfer->endpoint = h->bulk_in;
496 info->transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
497 info->transfer->length = len;
498 info->transfer->buffer = reinterpret_cast<unsigned char*>(d);
499 info->transfer->num_iso_packets = 0;
500
501 int rc = perform_usb_transfer(h, info, std::move(lock));
502 LOG(DEBUG) << "usb_read(" << len << ") = " << rc;
503 return rc;
504 }
505
usb_close(usb_handle * h)506 int usb_close(usb_handle* h) {
507 std::unique_lock<std::mutex> lock(usb_handles_mutex);
508 auto it = usb_handles.find(h->device_address);
509 if (it == usb_handles.end()) {
510 LOG(FATAL) << "attempted to close unregistered usb_handle for '" << h->serial << "'";
511 }
512 usb_handles.erase(h->device_address);
513 return 0;
514 }
515
usb_kick(usb_handle * h)516 void usb_kick(usb_handle* h) {
517 h->Close();
518 }
519 } // namespace libusb
520