1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "device/usb/usb_device_handle_impl.h"
10 #include "base/bind.h"
11 #include "base/location.h"
12 #include "base/single_thread_task_runner.h"
13 #include "base/stl_util.h"
14 #include "base/strings/string16.h"
15 #include "base/synchronization/lock.h"
16 #include "base/thread_task_runner_handle.h"
17 #include "device/usb/usb_context.h"
18 #include "device/usb/usb_descriptors.h"
19 #include "device/usb/usb_device_impl.h"
20 #include "device/usb/usb_error.h"
21 #include "device/usb/usb_service.h"
22 #include "third_party/libusb/src/libusb/libusb.h"
26 typedef libusb_device
* PlatformUsbDevice
;
28 void HandleTransferCompletion(PlatformUsbTransferHandle transfer
);
32 static uint8
ConvertTransferDirection(const UsbEndpointDirection direction
) {
34 case USB_DIRECTION_INBOUND
:
35 return LIBUSB_ENDPOINT_IN
;
36 case USB_DIRECTION_OUTBOUND
:
37 return LIBUSB_ENDPOINT_OUT
;
40 return LIBUSB_ENDPOINT_IN
;
44 static uint8
CreateRequestType(
45 const UsbEndpointDirection direction
,
46 const UsbDeviceHandle::TransferRequestType request_type
,
47 const UsbDeviceHandle::TransferRecipient recipient
) {
48 uint8 result
= ConvertTransferDirection(direction
);
50 switch (request_type
) {
51 case UsbDeviceHandle::STANDARD
:
52 result
|= LIBUSB_REQUEST_TYPE_STANDARD
;
54 case UsbDeviceHandle::CLASS
:
55 result
|= LIBUSB_REQUEST_TYPE_CLASS
;
57 case UsbDeviceHandle::VENDOR
:
58 result
|= LIBUSB_REQUEST_TYPE_VENDOR
;
60 case UsbDeviceHandle::RESERVED
:
61 result
|= LIBUSB_REQUEST_TYPE_RESERVED
;
66 case UsbDeviceHandle::DEVICE
:
67 result
|= LIBUSB_RECIPIENT_DEVICE
;
69 case UsbDeviceHandle::INTERFACE
:
70 result
|= LIBUSB_RECIPIENT_INTERFACE
;
72 case UsbDeviceHandle::ENDPOINT
:
73 result
|= LIBUSB_RECIPIENT_ENDPOINT
;
75 case UsbDeviceHandle::OTHER
:
76 result
|= LIBUSB_RECIPIENT_OTHER
;
83 static UsbTransferStatus
ConvertTransferStatus(
84 const libusb_transfer_status status
) {
86 case LIBUSB_TRANSFER_COMPLETED
:
87 return USB_TRANSFER_COMPLETED
;
88 case LIBUSB_TRANSFER_ERROR
:
89 return USB_TRANSFER_ERROR
;
90 case LIBUSB_TRANSFER_TIMED_OUT
:
91 return USB_TRANSFER_TIMEOUT
;
92 case LIBUSB_TRANSFER_STALL
:
93 return USB_TRANSFER_STALLED
;
94 case LIBUSB_TRANSFER_NO_DEVICE
:
95 return USB_TRANSFER_DISCONNECT
;
96 case LIBUSB_TRANSFER_OVERFLOW
:
97 return USB_TRANSFER_OVERFLOW
;
98 case LIBUSB_TRANSFER_CANCELLED
:
99 return USB_TRANSFER_CANCELLED
;
102 return USB_TRANSFER_ERROR
;
108 class UsbDeviceHandleImpl::InterfaceClaimer
109 : public base::RefCountedThreadSafe
<UsbDeviceHandleImpl::InterfaceClaimer
> {
111 InterfaceClaimer(const scoped_refptr
<UsbDeviceHandleImpl
> handle
,
112 const int interface_number
);
116 int alternate_setting() const { return alternate_setting_
; }
117 void set_alternate_setting(const int alternate_setting
) {
118 alternate_setting_
= alternate_setting
;
122 friend class UsbDevice
;
123 friend class base::RefCountedThreadSafe
<InterfaceClaimer
>;
126 const scoped_refptr
<UsbDeviceHandleImpl
> handle_
;
127 const int interface_number_
;
128 int alternate_setting_
;
130 DISALLOW_COPY_AND_ASSIGN(InterfaceClaimer
);
133 UsbDeviceHandleImpl::InterfaceClaimer::InterfaceClaimer(
134 const scoped_refptr
<UsbDeviceHandleImpl
> handle
,
135 const int interface_number
)
137 interface_number_(interface_number
),
138 alternate_setting_(0) {
141 UsbDeviceHandleImpl::InterfaceClaimer::~InterfaceClaimer() {
142 libusb_release_interface(handle_
->handle(), interface_number_
);
145 bool UsbDeviceHandleImpl::InterfaceClaimer::Claim() const {
146 const int rv
= libusb_claim_interface(handle_
->handle(), interface_number_
);
147 if (rv
!= LIBUSB_SUCCESS
) {
148 VLOG(1) << "Failed to claim interface: "
149 << ConvertPlatformUsbErrorToString(rv
);
151 return rv
== LIBUSB_SUCCESS
;
154 struct UsbDeviceHandleImpl::Transfer
{
158 void Complete(UsbTransferStatus status
, size_t bytes_transferred
);
160 UsbTransferType transfer_type
;
161 scoped_refptr
<net::IOBuffer
> buffer
;
162 scoped_refptr
<UsbDeviceHandleImpl::InterfaceClaimer
> claimed_interface
;
163 scoped_refptr
<base::SingleThreadTaskRunner
> task_runner
;
165 UsbTransferCallback callback
;
168 UsbDeviceHandleImpl::Transfer::Transfer()
169 : transfer_type(USB_TRANSFER_CONTROL
), length(0) {
172 UsbDeviceHandleImpl::Transfer::~Transfer() {
175 void UsbDeviceHandleImpl::Transfer::Complete(UsbTransferStatus status
,
176 size_t bytes_transferred
) {
177 if (task_runner
->RunsTasksOnCurrentThread()) {
178 callback
.Run(status
, buffer
, bytes_transferred
);
180 task_runner
->PostTask(
181 FROM_HERE
, base::Bind(callback
, status
, buffer
, bytes_transferred
));
185 UsbDeviceHandleImpl::UsbDeviceHandleImpl(scoped_refptr
<UsbContext
> context
,
186 UsbDeviceImpl
* device
,
187 PlatformUsbDeviceHandle handle
,
188 const UsbConfigDescriptor
& config
)
193 task_runner_(base::ThreadTaskRunnerHandle::Get()) {
194 DCHECK(handle
) << "Cannot create device with NULL handle.";
197 UsbDeviceHandleImpl::~UsbDeviceHandleImpl() {
198 DCHECK(thread_checker_
.CalledOnValidThread());
200 libusb_close(handle_
);
204 scoped_refptr
<UsbDevice
> UsbDeviceHandleImpl::GetDevice() const {
205 return static_cast<UsbDevice
*>(device_
);
208 void UsbDeviceHandleImpl::Close() {
209 DCHECK(thread_checker_
.CalledOnValidThread());
211 device_
->Close(this);
214 bool UsbDeviceHandleImpl::ClaimInterface(const int interface_number
) {
215 DCHECK(thread_checker_
.CalledOnValidThread());
218 if (ContainsKey(claimed_interfaces_
, interface_number
))
221 scoped_refptr
<InterfaceClaimer
> claimer
=
222 new InterfaceClaimer(this, interface_number
);
224 if (claimer
->Claim()) {
225 claimed_interfaces_
[interface_number
] = claimer
;
226 RefreshEndpointMap();
232 bool UsbDeviceHandleImpl::ReleaseInterface(const int interface_number
) {
233 DCHECK(thread_checker_
.CalledOnValidThread());
236 if (!ContainsKey(claimed_interfaces_
, interface_number
))
239 // Cancel all the transfers on that interface.
240 InterfaceClaimer
* interface_claimer
=
241 claimed_interfaces_
[interface_number
].get();
242 for (TransferMap::iterator it
= transfers_
.begin(); it
!= transfers_
.end();
244 if (it
->second
.claimed_interface
.get() == interface_claimer
)
245 libusb_cancel_transfer(it
->first
);
247 claimed_interfaces_
.erase(interface_number
);
249 RefreshEndpointMap();
253 bool UsbDeviceHandleImpl::SetInterfaceAlternateSetting(
254 const int interface_number
,
255 const int alternate_setting
) {
256 DCHECK(thread_checker_
.CalledOnValidThread());
259 if (!ContainsKey(claimed_interfaces_
, interface_number
))
261 const int rv
= libusb_set_interface_alt_setting(
262 handle_
, interface_number
, alternate_setting
);
263 if (rv
== LIBUSB_SUCCESS
) {
264 claimed_interfaces_
[interface_number
]->set_alternate_setting(
266 RefreshEndpointMap();
268 VLOG(1) << "Failed to set interface (" << interface_number
<< ", "
270 << "): " << ConvertPlatformUsbErrorToString(rv
);
272 return rv
== LIBUSB_SUCCESS
;
275 bool UsbDeviceHandleImpl::ResetDevice() {
276 DCHECK(thread_checker_
.CalledOnValidThread());
280 const int rv
= libusb_reset_device(handle_
);
281 if (rv
!= LIBUSB_SUCCESS
) {
282 VLOG(1) << "Failed to reset device: "
283 << ConvertPlatformUsbErrorToString(rv
);
285 return rv
== LIBUSB_SUCCESS
;
288 bool UsbDeviceHandleImpl::GetStringDescriptor(uint8 string_id
,
289 base::string16
* string
) {
290 if (!GetSupportedLanguages()) {
294 std::map
<uint8
, base::string16
>::const_iterator it
= strings_
.find(string_id
);
295 if (it
!= strings_
.end()) {
296 *string
= it
->second
;
300 for (size_t i
= 0; i
< languages_
.size(); ++i
) {
301 // Get the string using language ID.
302 uint16 language_id
= languages_
[i
];
303 // The 1-byte length field limits the descriptor to 256-bytes (128 char16s).
304 base::char16 text
[128];
306 libusb_get_string_descriptor(handle_
,
309 reinterpret_cast<unsigned char*>(&text
[0]),
312 VLOG(1) << "Failed to get string descriptor " << string_id
<< " (langid "
313 << language_id
<< "): " << ConvertPlatformUsbErrorToString(size
);
315 } else if (size
< 2) {
316 VLOG(1) << "String descriptor " << string_id
<< " (langid " << language_id
317 << ") has no header.";
319 // The first 2 bytes of the descriptor are the total length and type tag.
320 } else if ((text
[0] & 0xff) != size
) {
321 VLOG(1) << "String descriptor " << string_id
<< " (langid " << language_id
322 << ") size mismatch: " << (text
[0] & 0xff) << " != " << size
;
324 } else if ((text
[0] >> 8) != LIBUSB_DT_STRING
) {
325 VLOG(1) << "String descriptor " << string_id
<< " (langid " << language_id
326 << ") is not a string descriptor.";
330 *string
= base::string16(text
+ 1, (size
- 2) / 2);
331 strings_
[string_id
] = *string
;
338 void UsbDeviceHandleImpl::ControlTransfer(
339 const UsbEndpointDirection direction
,
340 const TransferRequestType request_type
,
341 const TransferRecipient recipient
,
345 net::IOBuffer
* buffer
,
347 const unsigned int timeout
,
348 const UsbTransferCallback
& callback
) {
350 callback
.Run(USB_TRANSFER_DISCONNECT
, buffer
, 0);
354 const size_t resized_length
= LIBUSB_CONTROL_SETUP_SIZE
+ length
;
355 scoped_refptr
<net::IOBuffer
> resized_buffer(
356 new net::IOBufferWithSize(static_cast<int>(resized_length
)));
357 if (!resized_buffer
.get()) {
358 callback
.Run(USB_TRANSFER_ERROR
, buffer
, 0);
361 memcpy(resized_buffer
->data() + LIBUSB_CONTROL_SETUP_SIZE
,
363 static_cast<int>(length
));
365 PlatformUsbTransferHandle
const transfer
= libusb_alloc_transfer(0);
366 const uint8 converted_type
=
367 CreateRequestType(direction
, request_type
, recipient
);
368 libusb_fill_control_setup(reinterpret_cast<uint8
*>(resized_buffer
->data()),
373 static_cast<int16
>(length
));
374 libusb_fill_control_transfer(transfer
,
376 reinterpret_cast<uint8
*>(resized_buffer
->data()),
377 &UsbDeviceHandleImpl::PlatformTransferCallback
,
381 PostOrSubmitTransfer(transfer
,
382 USB_TRANSFER_CONTROL
,
383 resized_buffer
.get(),
388 void UsbDeviceHandleImpl::BulkTransfer(const UsbEndpointDirection direction
,
389 const uint8 endpoint
,
390 net::IOBuffer
* buffer
,
392 const unsigned int timeout
,
393 const UsbTransferCallback
& callback
) {
395 callback
.Run(USB_TRANSFER_DISCONNECT
, buffer
, 0);
399 PlatformUsbTransferHandle
const transfer
= libusb_alloc_transfer(0);
400 const uint8 new_endpoint
= ConvertTransferDirection(direction
) | endpoint
;
401 libusb_fill_bulk_transfer(transfer
,
404 reinterpret_cast<uint8
*>(buffer
->data()),
405 static_cast<int>(length
),
406 &UsbDeviceHandleImpl::PlatformTransferCallback
,
410 PostOrSubmitTransfer(transfer
, USB_TRANSFER_BULK
, buffer
, length
, callback
);
413 void UsbDeviceHandleImpl::InterruptTransfer(
414 const UsbEndpointDirection direction
,
415 const uint8 endpoint
,
416 net::IOBuffer
* buffer
,
418 const unsigned int timeout
,
419 const UsbTransferCallback
& callback
) {
421 callback
.Run(USB_TRANSFER_DISCONNECT
, buffer
, 0);
425 PlatformUsbTransferHandle
const transfer
= libusb_alloc_transfer(0);
426 const uint8 new_endpoint
= ConvertTransferDirection(direction
) | endpoint
;
427 libusb_fill_interrupt_transfer(transfer
,
430 reinterpret_cast<uint8
*>(buffer
->data()),
431 static_cast<int>(length
),
432 &UsbDeviceHandleImpl::PlatformTransferCallback
,
436 PostOrSubmitTransfer(
437 transfer
, USB_TRANSFER_INTERRUPT
, buffer
, length
, callback
);
440 void UsbDeviceHandleImpl::IsochronousTransfer(
441 const UsbEndpointDirection direction
,
442 const uint8 endpoint
,
443 net::IOBuffer
* buffer
,
445 const unsigned int packets
,
446 const unsigned int packet_length
,
447 const unsigned int timeout
,
448 const UsbTransferCallback
& callback
) {
450 callback
.Run(USB_TRANSFER_DISCONNECT
, buffer
, 0);
454 const uint64 total_length
= packets
* packet_length
;
455 CHECK(packets
<= length
&& total_length
<= length
)
456 << "transfer length is too small";
458 PlatformUsbTransferHandle
const transfer
= libusb_alloc_transfer(packets
);
459 const uint8 new_endpoint
= ConvertTransferDirection(direction
) | endpoint
;
460 libusb_fill_iso_transfer(transfer
,
463 reinterpret_cast<uint8
*>(buffer
->data()),
464 static_cast<int>(length
),
466 &UsbDeviceHandleImpl::PlatformTransferCallback
,
469 libusb_set_iso_packet_lengths(transfer
, packet_length
);
471 PostOrSubmitTransfer(
472 transfer
, USB_TRANSFER_ISOCHRONOUS
, buffer
, length
, callback
);
475 void UsbDeviceHandleImpl::RefreshEndpointMap() {
476 DCHECK(thread_checker_
.CalledOnValidThread());
477 endpoint_map_
.clear();
478 for (ClaimedInterfaceMap::iterator claimedIt
= claimed_interfaces_
.begin();
479 claimedIt
!= claimed_interfaces_
.end();
481 for (UsbInterfaceDescriptor::Iterator ifaceIt
= config_
.interfaces
.begin();
482 ifaceIt
!= config_
.interfaces
.end();
484 if (ifaceIt
->interface_number
== claimedIt
->first
&&
485 ifaceIt
->alternate_setting
==
486 claimedIt
->second
->alternate_setting()) {
487 for (UsbEndpointDescriptor::Iterator endpointIt
=
488 ifaceIt
->endpoints
.begin();
489 endpointIt
!= ifaceIt
->endpoints
.end();
491 endpoint_map_
[endpointIt
->address
] = claimedIt
->first
;
499 scoped_refptr
<UsbDeviceHandleImpl::InterfaceClaimer
>
500 UsbDeviceHandleImpl::GetClaimedInterfaceForEndpoint(unsigned char endpoint
) {
501 unsigned char address
= endpoint
& LIBUSB_ENDPOINT_ADDRESS_MASK
;
502 if (ContainsKey(endpoint_map_
, address
))
503 return claimed_interfaces_
[endpoint_map_
[address
]];
507 void UsbDeviceHandleImpl::PostOrSubmitTransfer(
508 PlatformUsbTransferHandle transfer
,
509 UsbTransferType transfer_type
,
510 net::IOBuffer
* buffer
,
512 const UsbTransferCallback
& callback
) {
513 if (task_runner_
->RunsTasksOnCurrentThread()) {
514 SubmitTransfer(transfer
,
518 base::ThreadTaskRunnerHandle::Get(),
521 task_runner_
->PostTask(FROM_HERE
,
522 base::Bind(&UsbDeviceHandleImpl::SubmitTransfer
,
526 make_scoped_refptr(buffer
),
528 base::ThreadTaskRunnerHandle::Get(),
533 void UsbDeviceHandleImpl::SubmitTransfer(
534 PlatformUsbTransferHandle handle
,
535 UsbTransferType transfer_type
,
536 net::IOBuffer
* buffer
,
538 scoped_refptr
<base::SingleThreadTaskRunner
> task_runner
,
539 const UsbTransferCallback
& callback
) {
540 DCHECK(thread_checker_
.CalledOnValidThread());
543 transfer
.transfer_type
= transfer_type
;
544 transfer
.buffer
= buffer
;
545 transfer
.length
= length
;
546 transfer
.callback
= callback
;
547 transfer
.task_runner
= task_runner
;
550 transfer
.Complete(USB_TRANSFER_DISCONNECT
, 0);
554 // It's OK for this method to return NULL. libusb_submit_transfer will fail if
555 // it requires an interface we didn't claim.
556 transfer
.claimed_interface
= GetClaimedInterfaceForEndpoint(handle
->endpoint
);
558 const int rv
= libusb_submit_transfer(handle
);
559 if (rv
== LIBUSB_SUCCESS
) {
560 transfers_
[handle
] = transfer
;
562 VLOG(1) << "Failed to submit transfer: "
563 << ConvertPlatformUsbErrorToString(rv
);
564 transfer
.Complete(USB_TRANSFER_ERROR
, 0);
569 void LIBUSB_CALL
UsbDeviceHandleImpl::PlatformTransferCallback(
570 PlatformUsbTransferHandle transfer
) {
571 UsbDeviceHandleImpl
* device_handle
=
572 reinterpret_cast<UsbDeviceHandleImpl
*>(transfer
->user_data
);
573 device_handle
->task_runner_
->PostTask(
576 &UsbDeviceHandleImpl::CompleteTransfer
, device_handle
, transfer
));
579 void UsbDeviceHandleImpl::CompleteTransfer(PlatformUsbTransferHandle handle
) {
580 DCHECK(ContainsKey(transfers_
, handle
)) << "Missing transfer completed";
582 Transfer transfer
= transfers_
[handle
];
583 transfers_
.erase(handle
);
585 DCHECK_GE(handle
->actual_length
, 0) << "Negative actual length received";
586 size_t actual_length
=
587 static_cast<size_t>(std::max(handle
->actual_length
, 0));
589 DCHECK(transfer
.length
>= actual_length
)
590 << "data too big for our buffer (libusb failure?)";
592 switch (transfer
.transfer_type
) {
593 case USB_TRANSFER_CONTROL
:
594 // If the transfer is a control transfer we do not expose the control
595 // setup header to the caller. This logic strips off the header if
596 // present before invoking the callback provided with the transfer.
597 if (actual_length
> 0) {
598 CHECK(transfer
.length
>= LIBUSB_CONTROL_SETUP_SIZE
)
599 << "buffer was not correctly set: too small for the control header";
601 if (transfer
.length
>= (LIBUSB_CONTROL_SETUP_SIZE
+ actual_length
)) {
602 // If the payload is zero bytes long, pad out the allocated buffer
603 // size to one byte so that an IOBuffer of that size can be allocated.
604 scoped_refptr
<net::IOBuffer
> resized_buffer
=
605 new net::IOBuffer(static_cast<int>(
606 std::max(actual_length
, static_cast<size_t>(1))));
607 memcpy(resized_buffer
->data(),
608 transfer
.buffer
->data() + LIBUSB_CONTROL_SETUP_SIZE
,
610 transfer
.buffer
= resized_buffer
;
615 case USB_TRANSFER_ISOCHRONOUS
:
616 // Isochronous replies might carry data in the different isoc packets even
617 // if the transfer actual_data value is zero. Furthermore, not all of the
618 // received packets might contain data, so we need to calculate how many
619 // data bytes we are effectively providing and pack the results.
620 if (actual_length
== 0) {
621 size_t packet_buffer_start
= 0;
622 for (int i
= 0; i
< handle
->num_iso_packets
; ++i
) {
623 PlatformUsbIsoPacketDescriptor packet
= &handle
->iso_packet_desc
[i
];
624 if (packet
->actual_length
> 0) {
625 // We don't need to copy as long as all packets until now provide
626 // all the data the packet can hold.
627 if (actual_length
< packet_buffer_start
) {
628 CHECK(packet_buffer_start
+ packet
->actual_length
<=
630 memmove(transfer
.buffer
->data() + actual_length
,
631 transfer
.buffer
->data() + packet_buffer_start
,
632 packet
->actual_length
);
634 actual_length
+= packet
->actual_length
;
637 packet_buffer_start
+= packet
->length
;
642 case USB_TRANSFER_BULK
:
643 case USB_TRANSFER_INTERRUPT
:
647 NOTREACHED() << "Invalid usb transfer type";
651 transfer
.Complete(ConvertTransferStatus(handle
->status
), actual_length
);
652 libusb_free_transfer(handle
);
654 // Must release interface first before actually delete this.
655 transfer
.claimed_interface
= NULL
;
658 bool UsbDeviceHandleImpl::GetSupportedLanguages() {
659 if (!languages_
.empty()) {
663 // The 1-byte length field limits the descriptor to 256-bytes (128 uint16s).
664 uint16 languages
[128];
665 int size
= libusb_get_string_descriptor(
669 reinterpret_cast<unsigned char*>(&languages
[0]),
672 VLOG(1) << "Failed to get list of supported languages: "
673 << ConvertPlatformUsbErrorToString(size
);
675 } else if (size
< 2) {
676 VLOG(1) << "String descriptor zero has no header.";
678 // The first 2 bytes of the descriptor are the total length and type tag.
679 } else if ((languages
[0] & 0xff) != size
) {
680 VLOG(1) << "String descriptor zero size mismatch: " << (languages
[0] & 0xff)
683 } else if ((languages
[0] >> 8) != LIBUSB_DT_STRING
) {
684 VLOG(1) << "String descriptor zero is not a string descriptor.";
688 languages_
.assign(languages
[1], languages
[(size
- 2) / 2]);
692 void UsbDeviceHandleImpl::InternalClose() {
693 DCHECK(thread_checker_
.CalledOnValidThread());
697 // Cancel all the transfers.
698 for (TransferMap::iterator it
= transfers_
.begin(); it
!= transfers_
.end();
700 // The callback will be called some time later.
701 libusb_cancel_transfer(it
->first
);
704 // Attempt-release all the interfaces.
705 // It will be retained until the transfer cancellation is finished.
706 claimed_interfaces_
.clear();
708 // Cannot close device handle here. Need to wait for libusb_cancel_transfer to
713 } // namespace device