blob: 7e77b5ede7586b2db544ff127b662319f8babee7 [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"
Josh Gao4b640842017-05-31 11:54:56 -070040#include "adb_utils.h"
Josh Gaob7366922016-09-28 12:32:45 -070041#include "transport.h"
42#include "usb.h"
43
44using namespace std::literals;
45
46using android::base::StringPrintf;
47
48// RAII wrappers for libusb.
49struct ConfigDescriptorDeleter {
50 void operator()(libusb_config_descriptor* desc) {
51 libusb_free_config_descriptor(desc);
52 }
53};
54
55using unique_config_descriptor = std::unique_ptr<libusb_config_descriptor, ConfigDescriptorDeleter>;
56
57struct DeviceHandleDeleter {
58 void operator()(libusb_device_handle* h) {
59 libusb_close(h);
60 }
61};
62
63using unique_device_handle = std::unique_ptr<libusb_device_handle, DeviceHandleDeleter>;
64
65struct transfer_info {
Yabin Cui3cf1b362017-03-10 16:01:01 -080066 transfer_info(const char* name, uint16_t zero_mask, bool is_bulk_out)
67 : name(name),
68 transfer(libusb_alloc_transfer(0)),
69 is_bulk_out(is_bulk_out),
70 zero_mask(zero_mask) {}
Josh Gaob7366922016-09-28 12:32:45 -070071
72 ~transfer_info() {
73 libusb_free_transfer(transfer);
74 }
75
76 const char* name;
77 libusb_transfer* transfer;
Yabin Cui3cf1b362017-03-10 16:01:01 -080078 bool is_bulk_out;
Josh Gaob7366922016-09-28 12:32:45 -070079 bool transfer_complete;
80 std::condition_variable cv;
81 std::mutex mutex;
82 uint16_t zero_mask;
83
84 void Notify() {
85 LOG(DEBUG) << "notifying " << name << " transfer complete";
86 transfer_complete = true;
87 cv.notify_one();
88 }
89};
90
91namespace libusb {
92struct usb_handle : public ::usb_handle {
93 usb_handle(const std::string& device_address, const std::string& serial,
94 unique_device_handle&& device_handle, uint8_t interface, uint8_t bulk_in,
Josh Gao3734cf02017-05-02 15:01:09 -070095 uint8_t bulk_out, size_t zero_mask, size_t max_packet_size)
Josh Gaob7366922016-09-28 12:32:45 -070096 : device_address(device_address),
97 serial(serial),
98 closing(false),
99 device_handle(device_handle.release()),
Yabin Cui3cf1b362017-03-10 16:01:01 -0800100 read("read", zero_mask, false),
101 write("write", zero_mask, true),
Josh Gaob7366922016-09-28 12:32:45 -0700102 interface(interface),
103 bulk_in(bulk_in),
Josh Gao3734cf02017-05-02 15:01:09 -0700104 bulk_out(bulk_out),
105 max_packet_size(max_packet_size) {}
Josh Gaob7366922016-09-28 12:32:45 -0700106
107 ~usb_handle() {
108 Close();
109 }
110
111 void Close() {
112 std::unique_lock<std::mutex> lock(device_handle_mutex);
113 // Cancelling transfers will trigger more Closes, so make sure this only happens once.
114 if (closing) {
115 return;
116 }
117 closing = true;
118
119 // Make sure that no new transfers come in.
120 libusb_device_handle* handle = device_handle;
121 if (!handle) {
122 return;
123 }
124
125 device_handle = nullptr;
126
127 // Cancel already dispatched transfers.
128 libusb_cancel_transfer(read.transfer);
129 libusb_cancel_transfer(write.transfer);
130
131 libusb_release_interface(handle, interface);
132 libusb_close(handle);
133 }
134
135 std::string device_address;
136 std::string serial;
137
138 std::atomic<bool> closing;
139 std::mutex device_handle_mutex;
140 libusb_device_handle* device_handle;
141
142 transfer_info read;
143 transfer_info write;
144
145 uint8_t interface;
146 uint8_t bulk_in;
147 uint8_t bulk_out;
Josh Gao3734cf02017-05-02 15:01:09 -0700148
149 size_t max_packet_size;
Josh Gaob7366922016-09-28 12:32:45 -0700150};
151
152static auto& usb_handles = *new std::unordered_map<std::string, std::unique_ptr<usb_handle>>();
153static auto& usb_handles_mutex = *new std::mutex();
154
Josh Gao95238412017-05-12 11:21:30 -0700155static libusb_hotplug_callback_handle hotplug_handle;
Josh Gaob7366922016-09-28 12:32:45 -0700156
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}
Josh Gao70dc7372017-05-12 14:46:50 -0700176
177static std::string get_device_dev_path(libusb_device* device) {
178 uint8_t ports[7];
179 int port_count = libusb_get_port_numbers(device, ports, 7);
180 if (port_count < 0) return "";
181 return StringPrintf("/dev/bus/usb/%03u/%03u", libusb_get_bus_number(device), ports[0]);
182}
183
184static bool is_device_accessible(libusb_device* device) {
185 return access(get_device_dev_path(device).c_str(), R_OK | W_OK) == 0;
186}
Elliott Hughesac16a0f2017-05-05 16:26:00 -0700187#endif
Elliott Hughes3e9e74e2017-05-03 17:25:34 -0700188
Josh Gaob7366922016-09-28 12:32:45 -0700189static bool endpoint_is_output(uint8_t endpoint) {
190 return (endpoint & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_OUT;
191}
192
193static bool should_perform_zero_transfer(uint8_t endpoint, size_t write_length, uint16_t zero_mask) {
194 return endpoint_is_output(endpoint) && write_length != 0 && zero_mask != 0 &&
195 (write_length & zero_mask) == 0;
196}
197
Josh Gao9a700fd2017-05-05 18:19:21 -0700198static void process_device(libusb_device* device) {
199 std::string device_address = get_device_address(device);
200 std::string device_serial;
201
202 // Figure out if we want to open the device.
203 libusb_device_descriptor device_desc;
204 int rc = libusb_get_device_descriptor(device, &device_desc);
205 if (rc != 0) {
206 LOG(WARNING) << "failed to get device descriptor for device at " << device_address << ": "
207 << libusb_error_name(rc);
208 return;
209 }
210
211 if (device_desc.bDeviceClass != LIBUSB_CLASS_PER_INTERFACE) {
212 // Assume that all Android devices have the device class set to per interface.
213 // TODO: Is this assumption valid?
214 LOG(VERBOSE) << "skipping device with incorrect class at " << device_address;
215 return;
216 }
217
218 libusb_config_descriptor* config_raw;
219 rc = libusb_get_active_config_descriptor(device, &config_raw);
220 if (rc != 0) {
221 LOG(WARNING) << "failed to get active config descriptor for device at " << device_address
222 << ": " << libusb_error_name(rc);
223 return;
224 }
225 const unique_config_descriptor config(config_raw);
226
227 // Use size_t for interface_num so <iostream>s don't mangle it.
228 size_t interface_num;
229 uint16_t zero_mask;
230 uint8_t bulk_in = 0, bulk_out = 0;
231 size_t packet_size = 0;
232 bool found_adb = false;
233
234 for (interface_num = 0; interface_num < config->bNumInterfaces; ++interface_num) {
235 const libusb_interface& interface = config->interface[interface_num];
236 if (interface.num_altsetting != 1) {
237 // Assume that interfaces with alternate settings aren't adb interfaces.
238 // TODO: Is this assumption valid?
239 LOG(VERBOSE) << "skipping interface with incorrect num_altsetting at " << device_address
240 << " (interface " << interface_num << ")";
Josh Gaoa96dc5f2017-05-12 15:12:32 -0700241 continue;
Josh Gao9a700fd2017-05-05 18:19:21 -0700242 }
243
244 const libusb_interface_descriptor& interface_desc = interface.altsetting[0];
245 if (!is_adb_interface(interface_desc.bInterfaceClass, interface_desc.bInterfaceSubClass,
246 interface_desc.bInterfaceProtocol)) {
247 LOG(VERBOSE) << "skipping non-adb interface at " << device_address << " (interface "
248 << interface_num << ")";
Josh Gaoa96dc5f2017-05-12 15:12:32 -0700249 continue;
Josh Gao9a700fd2017-05-05 18:19:21 -0700250 }
251
252 LOG(VERBOSE) << "found potential adb interface at " << device_address << " (interface "
253 << interface_num << ")";
254
255 bool found_in = false;
256 bool found_out = false;
257 for (size_t endpoint_num = 0; endpoint_num < interface_desc.bNumEndpoints; ++endpoint_num) {
258 const auto& endpoint_desc = interface_desc.endpoint[endpoint_num];
259 const uint8_t endpoint_addr = endpoint_desc.bEndpointAddress;
260 const uint8_t endpoint_attr = endpoint_desc.bmAttributes;
261
262 const uint8_t transfer_type = endpoint_attr & LIBUSB_TRANSFER_TYPE_MASK;
263
264 if (transfer_type != LIBUSB_TRANSFER_TYPE_BULK) {
Josh Gaoa96dc5f2017-05-12 15:12:32 -0700265 continue;
Josh Gao9a700fd2017-05-05 18:19:21 -0700266 }
267
268 if (endpoint_is_output(endpoint_addr) && !found_out) {
269 found_out = true;
270 bulk_out = endpoint_addr;
271 zero_mask = endpoint_desc.wMaxPacketSize - 1;
272 } else if (!endpoint_is_output(endpoint_addr) && !found_in) {
273 found_in = true;
274 bulk_in = endpoint_addr;
275 }
276
277 size_t endpoint_packet_size = endpoint_desc.wMaxPacketSize;
278 CHECK(endpoint_packet_size != 0);
279 if (packet_size == 0) {
280 packet_size = endpoint_packet_size;
281 } else {
282 CHECK(packet_size == endpoint_packet_size);
283 }
284 }
285
286 if (found_in && found_out) {
287 found_adb = true;
288 break;
289 } else {
290 LOG(VERBOSE) << "rejecting potential adb interface at " << device_address
291 << "(interface " << interface_num << "): missing bulk endpoints "
292 << "(found_in = " << found_in << ", found_out = " << found_out << ")";
293 }
294 }
295
296 if (!found_adb) {
297 LOG(VERBOSE) << "skipping device with no adb interfaces at " << device_address;
298 return;
299 }
300
301 {
302 std::unique_lock<std::mutex> lock(usb_handles_mutex);
303 if (usb_handles.find(device_address) != usb_handles.end()) {
304 LOG(VERBOSE) << "device at " << device_address
305 << " has already been registered, skipping";
306 return;
307 }
308 }
309
310 bool writable = true;
311 libusb_device_handle* handle_raw = nullptr;
312 rc = libusb_open(device, &handle_raw);
313 unique_device_handle handle(handle_raw);
314 if (rc == 0) {
315 LOG(DEBUG) << "successfully opened adb device at " << device_address << ", "
316 << StringPrintf("bulk_in = %#x, bulk_out = %#x", bulk_in, bulk_out);
317
318 device_serial.resize(255);
319 rc = libusb_get_string_descriptor_ascii(handle_raw, device_desc.iSerialNumber,
320 reinterpret_cast<unsigned char*>(&device_serial[0]),
321 device_serial.length());
322 if (rc == 0) {
323 LOG(WARNING) << "received empty serial from device at " << device_address;
324 return;
325 } else if (rc < 0) {
326 LOG(WARNING) << "failed to get serial from device at " << device_address
327 << libusb_error_name(rc);
328 return;
329 }
330 device_serial.resize(rc);
331
332 // WARNING: this isn't released via RAII.
333 rc = libusb_claim_interface(handle.get(), interface_num);
334 if (rc != 0) {
335 LOG(WARNING) << "failed to claim adb interface for device '" << device_serial << "'"
336 << libusb_error_name(rc);
337 return;
338 }
339
340 for (uint8_t endpoint : {bulk_in, bulk_out}) {
341 rc = libusb_clear_halt(handle.get(), endpoint);
342 if (rc != 0) {
343 LOG(WARNING) << "failed to clear halt on device '" << device_serial
344 << "' endpoint 0x" << std::hex << endpoint << ": "
345 << libusb_error_name(rc);
346 libusb_release_interface(handle.get(), interface_num);
347 return;
348 }
349 }
350 } else {
351 LOG(WARNING) << "failed to open usb device at " << device_address << ": "
352 << libusb_error_name(rc);
353 writable = false;
354
355#if defined(__linux__)
356 // libusb doesn't think we should be messing around with devices we don't have
357 // write access to, but Linux at least lets us get the serial number anyway.
358 if (!android::base::ReadFileToString(get_device_serial_path(device), &device_serial)) {
359 // We don't actually want to treat an unknown serial as an error because
360 // devices aren't able to communicate a serial number in early bringup.
361 // http://b/20883914
362 device_serial = "unknown";
363 }
364 device_serial = android::base::Trim(device_serial);
365#else
366 // On Mac OS and Windows, we're screwed. But I don't think this situation actually
367 // happens on those OSes.
368 return;
369#endif
370 }
371
372 auto result =
373 std::make_unique<usb_handle>(device_address, device_serial, std::move(handle),
374 interface_num, bulk_in, bulk_out, zero_mask, packet_size);
375 usb_handle* usb_handle_raw = result.get();
376
377 {
378 std::unique_lock<std::mutex> lock(usb_handles_mutex);
379 usb_handles[device_address] = std::move(result);
380 }
381
382 register_usb_transport(usb_handle_raw, device_serial.c_str(), device_address.c_str(), writable);
Josh Gao9a700fd2017-05-05 18:19:21 -0700383 LOG(INFO) << "registered new usb device '" << device_serial << "'";
384}
385
Josh Gao70dc7372017-05-12 14:46:50 -0700386static std::atomic<int> connecting_devices(0);
387
388static void device_connected(libusb_device* device) {
389#if defined(__linux__)
390 // Android's host linux libusb uses netlink instead of udev for device hotplug notification,
Josh Gao4b640842017-05-31 11:54:56 -0700391 // which means we can get hotplug notifications before udev has updated ownership/perms on
392 // the device. Since we're not going to be able to link against the system's libudev any
393 // time soon, hack around this by checking for accessibility in a loop.
Josh Gao70dc7372017-05-12 14:46:50 -0700394 auto thread = std::thread([device]() {
395 std::string device_path = get_device_dev_path(device);
396 auto start = std::chrono::steady_clock::now();
397 while (std::chrono::steady_clock::now() - start < 500ms) {
398 if (is_device_accessible(device)) {
399 break;
400 }
401 std::this_thread::sleep_for(10ms);
402 }
403
404 process_device(device);
Josh Gao4b640842017-05-31 11:54:56 -0700405 if (--connecting_devices == 0) {
406 adb_notify_device_scan_complete();
407 }
Josh Gao70dc7372017-05-12 14:46:50 -0700408 });
409 thread.detach();
410#else
411 process_device(device);
412#endif
413}
414
415static void device_disconnected(libusb_device* device) {
Josh Gao95238412017-05-12 11:21:30 -0700416 std::string device_address = get_device_address(device);
Josh Gaob7366922016-09-28 12:32:45 -0700417
Josh Gao95238412017-05-12 11:21:30 -0700418 LOG(INFO) << "device disconnected: " << device_address;
419 std::unique_lock<std::mutex> lock(usb_handles_mutex);
420 auto it = usb_handles.find(device_address);
421 if (it != usb_handles.end()) {
422 if (!it->second->device_handle) {
423 // If the handle is null, we were never able to open the device.
424 unregister_usb_transport(it->second.get());
Josh Gaob7366922016-09-28 12:32:45 -0700425 }
Josh Gao95238412017-05-12 11:21:30 -0700426 usb_handles.erase(it);
Josh Gaob7366922016-09-28 12:32:45 -0700427 }
428}
429
Josh Gao4b640842017-05-31 11:54:56 -0700430static auto& hotplug_queue = *new BlockingQueue<std::pair<libusb_hotplug_event, libusb_device*>>();
431static void hotplug_thread() {
432 adb_thread_setname("libusb hotplug");
433 while (true) {
434 hotplug_queue.PopAll([](std::pair<libusb_hotplug_event, libusb_device*> pair) {
435 libusb_hotplug_event event = pair.first;
436 libusb_device* device = pair.second;
437 if (event == LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED) {
438 device_connected(device);
439 } else if (event == LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT) {
440 device_disconnected(device);
441 }
442 });
443 }
444}
445
Josh Gao95238412017-05-12 11:21:30 -0700446static int hotplug_callback(libusb_context*, libusb_device* device, libusb_hotplug_event event,
447 void*) {
Josh Gao4b640842017-05-31 11:54:56 -0700448 // We're called with the libusb lock taken. Call these on a separate thread outside of this
Josh Gao09628bb2017-05-30 17:03:41 -0700449 // function so that the usb_handle mutex is always taken before the libusb mutex.
Josh Gao4b640842017-05-31 11:54:56 -0700450 static std::once_flag once;
451 std::call_once(once, []() { std::thread(hotplug_thread).detach(); });
452
453 if (event == LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED) {
454 ++connecting_devices;
455 }
456 hotplug_queue.Push({event, device});
Josh Gao95238412017-05-12 11:21:30 -0700457 return 0;
458}
459
Josh Gaob7366922016-09-28 12:32:45 -0700460void usb_init() {
461 LOG(DEBUG) << "initializing libusb...";
462 int rc = libusb_init(nullptr);
463 if (rc != 0) {
464 LOG(FATAL) << "failed to initialize libusb: " << libusb_error_name(rc);
465 }
466
Josh Gao95238412017-05-12 11:21:30 -0700467 // Register the hotplug callback.
468 rc = libusb_hotplug_register_callback(
469 nullptr, static_cast<libusb_hotplug_event>(LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED |
470 LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT),
471 LIBUSB_HOTPLUG_ENUMERATE, LIBUSB_HOTPLUG_MATCH_ANY, LIBUSB_HOTPLUG_MATCH_ANY,
472 LIBUSB_CLASS_PER_INTERFACE, hotplug_callback, nullptr, &hotplug_handle);
473
474 if (rc != LIBUSB_SUCCESS) {
475 LOG(FATAL) << "failed to register libusb hotplug callback";
476 }
477
Josh Gaob7366922016-09-28 12:32:45 -0700478 // Spawn a thread for libusb_handle_events.
479 std::thread([]() {
480 adb_thread_setname("libusb");
481 while (true) {
482 libusb_handle_events(nullptr);
483 }
484 }).detach();
Josh Gao165460f2017-05-09 13:43:35 -0700485}
486
487void usb_cleanup() {
Josh Gao95238412017-05-12 11:21:30 -0700488 libusb_hotplug_deregister_callback(nullptr, hotplug_handle);
Josh Gaob7366922016-09-28 12:32:45 -0700489}
490
491// Dispatch a libusb transfer, unlock |device_lock|, and then wait for the result.
492static int perform_usb_transfer(usb_handle* h, transfer_info* info,
493 std::unique_lock<std::mutex> device_lock) {
494 libusb_transfer* transfer = info->transfer;
495
496 transfer->user_data = info;
497 transfer->callback = [](libusb_transfer* transfer) {
498 transfer_info* info = static_cast<transfer_info*>(transfer->user_data);
499
500 LOG(DEBUG) << info->name << " transfer callback entered";
501
502 // Make sure that the original submitter has made it to the condition_variable wait.
503 std::unique_lock<std::mutex> lock(info->mutex);
504
505 LOG(DEBUG) << info->name << " callback successfully acquired lock";
506
507 if (transfer->status != LIBUSB_TRANSFER_COMPLETED) {
508 LOG(WARNING) << info->name
509 << " transfer failed: " << libusb_error_name(transfer->status);
510 info->Notify();
511 return;
512 }
513
Yabin Cui3cf1b362017-03-10 16:01:01 -0800514 // usb_read() can return when receiving some data.
515 if (info->is_bulk_out && transfer->actual_length != transfer->length) {
Josh Gaob7366922016-09-28 12:32:45 -0700516 LOG(DEBUG) << info->name << " transfer incomplete, resubmitting";
517 transfer->length -= transfer->actual_length;
518 transfer->buffer += transfer->actual_length;
519 int rc = libusb_submit_transfer(transfer);
520 if (rc != 0) {
521 LOG(WARNING) << "failed to submit " << info->name
522 << " transfer: " << libusb_error_name(rc);
523 transfer->status = LIBUSB_TRANSFER_ERROR;
524 info->Notify();
525 }
526 return;
527 }
528
529 if (should_perform_zero_transfer(transfer->endpoint, transfer->length, info->zero_mask)) {
530 LOG(DEBUG) << "submitting zero-length write";
531 transfer->length = 0;
532 int rc = libusb_submit_transfer(transfer);
533 if (rc != 0) {
534 LOG(WARNING) << "failed to submit zero-length write: " << libusb_error_name(rc);
535 transfer->status = LIBUSB_TRANSFER_ERROR;
536 info->Notify();
537 }
538 return;
539 }
540
541 LOG(VERBOSE) << info->name << "transfer fully complete";
542 info->Notify();
543 };
544
545 LOG(DEBUG) << "locking " << info->name << " transfer_info mutex";
546 std::unique_lock<std::mutex> lock(info->mutex);
547 info->transfer_complete = false;
548 LOG(DEBUG) << "submitting " << info->name << " transfer";
549 int rc = libusb_submit_transfer(transfer);
550 if (rc != 0) {
551 LOG(WARNING) << "failed to submit " << info->name << " transfer: " << libusb_error_name(rc);
552 errno = EIO;
553 return -1;
554 }
555
556 LOG(DEBUG) << info->name << " transfer successfully submitted";
557 device_lock.unlock();
558 info->cv.wait(lock, [info]() { return info->transfer_complete; });
559 if (transfer->status != 0) {
560 errno = EIO;
561 return -1;
562 }
563
564 return 0;
565}
566
567int usb_write(usb_handle* h, const void* d, int len) {
568 LOG(DEBUG) << "usb_write of length " << len;
569
570 std::unique_lock<std::mutex> lock(h->device_handle_mutex);
571 if (!h->device_handle) {
572 errno = EIO;
573 return -1;
574 }
575
576 transfer_info* info = &h->write;
577 info->transfer->dev_handle = h->device_handle;
578 info->transfer->flags = 0;
579 info->transfer->endpoint = h->bulk_out;
580 info->transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
581 info->transfer->length = len;
582 info->transfer->buffer = reinterpret_cast<unsigned char*>(const_cast<void*>(d));
583 info->transfer->num_iso_packets = 0;
584
585 int rc = perform_usb_transfer(h, info, std::move(lock));
586 LOG(DEBUG) << "usb_write(" << len << ") = " << rc;
587 return rc;
588}
589
590int usb_read(usb_handle* h, void* d, int len) {
591 LOG(DEBUG) << "usb_read of length " << len;
592
593 std::unique_lock<std::mutex> lock(h->device_handle_mutex);
594 if (!h->device_handle) {
595 errno = EIO;
596 return -1;
597 }
598
599 transfer_info* info = &h->read;
600 info->transfer->dev_handle = h->device_handle;
601 info->transfer->flags = 0;
602 info->transfer->endpoint = h->bulk_in;
603 info->transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
604 info->transfer->length = len;
605 info->transfer->buffer = reinterpret_cast<unsigned char*>(d);
606 info->transfer->num_iso_packets = 0;
607
608 int rc = perform_usb_transfer(h, info, std::move(lock));
Yabin Cui3cf1b362017-03-10 16:01:01 -0800609 LOG(DEBUG) << "usb_read(" << len << ") = " << rc << ", actual_length "
610 << info->transfer->actual_length;
611 if (rc < 0) {
612 return rc;
613 }
614 return info->transfer->actual_length;
Josh Gaob7366922016-09-28 12:32:45 -0700615}
616
617int usb_close(usb_handle* h) {
618 std::unique_lock<std::mutex> lock(usb_handles_mutex);
619 auto it = usb_handles.find(h->device_address);
620 if (it == usb_handles.end()) {
621 LOG(FATAL) << "attempted to close unregistered usb_handle for '" << h->serial << "'";
622 }
623 usb_handles.erase(h->device_address);
624 return 0;
625}
626
627void usb_kick(usb_handle* h) {
628 h->Close();
629}
Josh Gao3734cf02017-05-02 15:01:09 -0700630
631size_t usb_get_max_packet_size(usb_handle* h) {
632 CHECK(h->max_packet_size != 0);
633 return h->max_packet_size;
634}
635
Josh Gaob7366922016-09-28 12:32:45 -0700636} // namespace libusb