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 "components/usb_service/usb_device_handle.h"
10 #include "base/message_loop/message_loop.h"
11 #include "base/stl_util.h"
12 #include "base/strings/string16.h"
13 #include "base/synchronization/lock.h"
14 #include "components/usb_service/usb_context.h"
15 #include "components/usb_service/usb_device.h"
16 #include "components/usb_service/usb_interface.h"
17 #include "components/usb_service/usb_service.h"
18 #include "content/public/browser/browser_thread.h"
19 #include "third_party/libusb/src/libusb/libusb.h"
21 using content::BrowserThread
;
23 namespace usb_service
{
25 void HandleTransferCompletion(usb_service::PlatformUsbTransferHandle transfer
);
29 static uint8
ConvertTransferDirection(const UsbEndpointDirection direction
) {
31 case USB_DIRECTION_INBOUND
:
32 return LIBUSB_ENDPOINT_IN
;
33 case USB_DIRECTION_OUTBOUND
:
34 return LIBUSB_ENDPOINT_OUT
;
37 return LIBUSB_ENDPOINT_IN
;
41 static uint8
CreateRequestType(
42 const UsbEndpointDirection direction
,
43 const UsbDeviceHandle::TransferRequestType request_type
,
44 const UsbDeviceHandle::TransferRecipient recipient
) {
45 uint8 result
= ConvertTransferDirection(direction
);
47 switch (request_type
) {
48 case UsbDeviceHandle::STANDARD
:
49 result
|= LIBUSB_REQUEST_TYPE_STANDARD
;
51 case UsbDeviceHandle::CLASS
:
52 result
|= LIBUSB_REQUEST_TYPE_CLASS
;
54 case UsbDeviceHandle::VENDOR
:
55 result
|= LIBUSB_REQUEST_TYPE_VENDOR
;
57 case UsbDeviceHandle::RESERVED
:
58 result
|= LIBUSB_REQUEST_TYPE_RESERVED
;
63 case UsbDeviceHandle::DEVICE
:
64 result
|= LIBUSB_RECIPIENT_DEVICE
;
66 case UsbDeviceHandle::INTERFACE
:
67 result
|= LIBUSB_RECIPIENT_INTERFACE
;
69 case UsbDeviceHandle::ENDPOINT
:
70 result
|= LIBUSB_RECIPIENT_ENDPOINT
;
72 case UsbDeviceHandle::OTHER
:
73 result
|= LIBUSB_RECIPIENT_OTHER
;
80 static UsbTransferStatus
ConvertTransferStatus(
81 const libusb_transfer_status status
) {
83 case LIBUSB_TRANSFER_COMPLETED
:
84 return USB_TRANSFER_COMPLETED
;
85 case LIBUSB_TRANSFER_ERROR
:
86 return USB_TRANSFER_ERROR
;
87 case LIBUSB_TRANSFER_TIMED_OUT
:
88 return USB_TRANSFER_TIMEOUT
;
89 case LIBUSB_TRANSFER_STALL
:
90 return USB_TRANSFER_STALLED
;
91 case LIBUSB_TRANSFER_NO_DEVICE
:
92 return USB_TRANSFER_DISCONNECT
;
93 case LIBUSB_TRANSFER_OVERFLOW
:
94 return USB_TRANSFER_OVERFLOW
;
95 case LIBUSB_TRANSFER_CANCELLED
:
96 return USB_TRANSFER_CANCELLED
;
99 return USB_TRANSFER_ERROR
;
103 static void LIBUSB_CALL
104 PlatformTransferCompletionCallback(PlatformUsbTransferHandle transfer
) {
105 BrowserThread::PostTask(BrowserThread::FILE,
107 base::Bind(HandleTransferCompletion
, transfer
));
112 void HandleTransferCompletion(PlatformUsbTransferHandle transfer
) {
113 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
114 UsbDeviceHandle
* const device_handle
=
115 reinterpret_cast<UsbDeviceHandle
*>(transfer
->user_data
);
116 CHECK(device_handle
) << "Device handle is closed before transfer finishes.";
117 device_handle
->TransferComplete(transfer
);
118 libusb_free_transfer(transfer
);
121 class UsbDeviceHandle::InterfaceClaimer
122 : public base::RefCountedThreadSafe
<UsbDeviceHandle::InterfaceClaimer
> {
124 InterfaceClaimer(const scoped_refptr
<UsbDeviceHandle
> handle
,
125 const int interface_number
);
129 int alternate_setting() const { return alternate_setting_
; }
130 void set_alternate_setting(const int alternate_setting
) {
131 alternate_setting_
= alternate_setting
;
135 friend class UsbDevice
;
136 friend class base::RefCountedThreadSafe
<InterfaceClaimer
>;
139 const scoped_refptr
<UsbDeviceHandle
> handle_
;
140 const int interface_number_
;
141 int alternate_setting_
;
143 DISALLOW_COPY_AND_ASSIGN(InterfaceClaimer
);
146 UsbDeviceHandle::InterfaceClaimer::InterfaceClaimer(
147 const scoped_refptr
<UsbDeviceHandle
> handle
,
148 const int interface_number
)
150 interface_number_(interface_number
),
151 alternate_setting_(0) {
154 UsbDeviceHandle::InterfaceClaimer::~InterfaceClaimer() {
155 libusb_release_interface(handle_
->handle(), interface_number_
);
158 bool UsbDeviceHandle::InterfaceClaimer::Claim() const {
159 return libusb_claim_interface(handle_
->handle(), interface_number_
) == 0;
162 struct UsbDeviceHandle::Transfer
{
166 UsbTransferType transfer_type
;
167 scoped_refptr
<net::IOBuffer
> buffer
;
168 scoped_refptr
<UsbDeviceHandle::InterfaceClaimer
> claimed_interface
;
169 scoped_refptr
<base::MessageLoopProxy
> message_loop_proxy
;
171 UsbTransferCallback callback
;
174 UsbDeviceHandle::Transfer::Transfer()
175 : transfer_type(USB_TRANSFER_CONTROL
), length(0) {
178 UsbDeviceHandle::Transfer::~Transfer() {
181 UsbDeviceHandle::UsbDeviceHandle(scoped_refptr
<UsbContext
> context
,
183 PlatformUsbDeviceHandle handle
,
184 scoped_refptr
<UsbConfigDescriptor
> interfaces
)
187 interfaces_(interfaces
),
189 DCHECK(thread_checker_
.CalledOnValidThread());
190 DCHECK(handle
) << "Cannot create device with NULL handle.";
191 DCHECK(interfaces_
) << "Unabled to list interfaces";
194 UsbDeviceHandle::UsbDeviceHandle() : device_(NULL
), handle_(NULL
) {
197 UsbDeviceHandle::~UsbDeviceHandle() {
198 DCHECK(thread_checker_
.CalledOnValidThread());
200 libusb_close(handle_
);
204 scoped_refptr
<UsbDevice
> UsbDeviceHandle::device() const {
208 void UsbDeviceHandle::Close() {
209 DCHECK(thread_checker_
.CalledOnValidThread());
211 device_
->Close(this);
214 void UsbDeviceHandle::TransferComplete(PlatformUsbTransferHandle handle
) {
215 DCHECK(ContainsKey(transfers_
, handle
)) << "Missing transfer completed";
217 Transfer transfer
= transfers_
[handle
];
218 transfers_
.erase(handle
);
220 DCHECK_GE(handle
->actual_length
, 0) << "Negative actual length received";
221 size_t actual_length
=
222 static_cast<size_t>(std::max(handle
->actual_length
, 0));
224 DCHECK(transfer
.length
>= actual_length
)
225 << "data too big for our buffer (libusb failure?)";
227 scoped_refptr
<net::IOBuffer
> buffer
= transfer
.buffer
;
228 switch (transfer
.transfer_type
) {
229 case USB_TRANSFER_CONTROL
:
230 // If the transfer is a control transfer we do not expose the control
231 // setup header to the caller. This logic strips off the header if
232 // present before invoking the callback provided with the transfer.
233 if (actual_length
> 0) {
234 CHECK(transfer
.length
>= LIBUSB_CONTROL_SETUP_SIZE
)
235 << "buffer was not correctly set: too small for the control header";
237 if (transfer
.length
>= (LIBUSB_CONTROL_SETUP_SIZE
+ actual_length
)) {
238 // If the payload is zero bytes long, pad out the allocated buffer
239 // size to one byte so that an IOBuffer of that size can be allocated.
240 scoped_refptr
<net::IOBuffer
> resized_buffer
=
241 new net::IOBuffer(static_cast<int>(
242 std::max(actual_length
, static_cast<size_t>(1))));
243 memcpy(resized_buffer
->data(),
244 buffer
->data() + LIBUSB_CONTROL_SETUP_SIZE
,
246 buffer
= resized_buffer
;
251 case USB_TRANSFER_ISOCHRONOUS
:
252 // Isochronous replies might carry data in the different isoc packets even
253 // if the transfer actual_data value is zero. Furthermore, not all of the
254 // received packets might contain data, so we need to calculate how many
255 // data bytes we are effectively providing and pack the results.
256 if (actual_length
== 0) {
257 size_t packet_buffer_start
= 0;
258 for (int i
= 0; i
< handle
->num_iso_packets
; ++i
) {
259 PlatformUsbIsoPacketDescriptor packet
= &handle
->iso_packet_desc
[i
];
260 if (packet
->actual_length
> 0) {
261 // We don't need to copy as long as all packets until now provide
262 // all the data the packet can hold.
263 if (actual_length
< packet_buffer_start
) {
264 CHECK(packet_buffer_start
+ packet
->actual_length
<=
266 memmove(buffer
->data() + actual_length
,
267 buffer
->data() + packet_buffer_start
,
268 packet
->actual_length
);
270 actual_length
+= packet
->actual_length
;
273 packet_buffer_start
+= packet
->length
;
278 case USB_TRANSFER_BULK
:
279 case USB_TRANSFER_INTERRUPT
:
283 NOTREACHED() << "Invalid usb transfer type";
287 transfer
.message_loop_proxy
->PostTask(
289 base::Bind(transfer
.callback
,
290 ConvertTransferStatus(handle
->status
),
294 // Must release interface first before actually delete this.
295 transfer
.claimed_interface
= NULL
;
298 bool UsbDeviceHandle::ClaimInterface(const int interface_number
) {
299 DCHECK(thread_checker_
.CalledOnValidThread());
302 if (ContainsKey(claimed_interfaces_
, interface_number
))
305 scoped_refptr
<InterfaceClaimer
> claimer
=
306 new InterfaceClaimer(this, interface_number
);
308 if (claimer
->Claim()) {
309 claimed_interfaces_
[interface_number
] = claimer
;
310 RefreshEndpointMap();
316 bool UsbDeviceHandle::ReleaseInterface(const int interface_number
) {
317 DCHECK(thread_checker_
.CalledOnValidThread());
320 if (!ContainsKey(claimed_interfaces_
, interface_number
))
323 // Cancel all the transfers on that interface.
324 InterfaceClaimer
* interface_claimer
=
325 claimed_interfaces_
[interface_number
].get();
326 for (TransferMap::iterator it
= transfers_
.begin(); it
!= transfers_
.end();
328 if (it
->second
.claimed_interface
.get() == interface_claimer
)
329 libusb_cancel_transfer(it
->first
);
331 claimed_interfaces_
.erase(interface_number
);
333 RefreshEndpointMap();
337 bool UsbDeviceHandle::SetInterfaceAlternateSetting(
338 const int interface_number
,
339 const int alternate_setting
) {
340 DCHECK(thread_checker_
.CalledOnValidThread());
343 if (!ContainsKey(claimed_interfaces_
, interface_number
))
345 const int rv
= libusb_set_interface_alt_setting(
346 handle_
, interface_number
, alternate_setting
);
348 claimed_interfaces_
[interface_number
]->set_alternate_setting(
350 RefreshEndpointMap();
356 bool UsbDeviceHandle::ResetDevice() {
357 DCHECK(thread_checker_
.CalledOnValidThread());
361 return libusb_reset_device(handle_
) == 0;
364 bool UsbDeviceHandle::GetSerial(base::string16
* serial
) {
365 DCHECK(thread_checker_
.CalledOnValidThread());
366 PlatformUsbDevice device
= libusb_get_device(handle_
);
367 libusb_device_descriptor desc
;
369 if (libusb_get_device_descriptor(device
, &desc
) != LIBUSB_SUCCESS
)
372 if (desc
.iSerialNumber
== 0)
375 // Getting supported language ID.
376 uint16 langid
[128] = {0};
379 libusb_get_string_descriptor(handle_
,
382 reinterpret_cast<unsigned char*>(&langid
[0]),
387 int language_count
= (size
- 2) / 2;
389 for (int i
= 1; i
<= language_count
; ++i
) {
390 // Get the string using language ID.
391 base::char16 text
[256] = {0};
393 libusb_get_string_descriptor(handle_
,
396 reinterpret_cast<unsigned char*>(&text
[0]),
400 if ((text
[0] >> 8) != LIBUSB_DT_STRING
)
402 if ((text
[0] & 255) > size
)
406 *serial
= base::string16(text
+ 1, size
);
412 void UsbDeviceHandle::ControlTransfer(const UsbEndpointDirection direction
,
413 const TransferRequestType request_type
,
414 const TransferRecipient recipient
,
418 net::IOBuffer
* buffer
,
420 const unsigned int timeout
,
421 const UsbTransferCallback
& callback
) {
423 callback
.Run(USB_TRANSFER_DISCONNECT
, buffer
, 0);
427 const size_t resized_length
= LIBUSB_CONTROL_SETUP_SIZE
+ length
;
428 scoped_refptr
<net::IOBuffer
> resized_buffer(
429 new net::IOBufferWithSize(static_cast<int>(resized_length
)));
430 if (!resized_buffer
) {
431 callback
.Run(USB_TRANSFER_ERROR
, buffer
, 0);
434 memcpy(resized_buffer
->data() + LIBUSB_CONTROL_SETUP_SIZE
,
436 static_cast<int>(length
));
438 PlatformUsbTransferHandle
const transfer
= libusb_alloc_transfer(0);
439 const uint8 converted_type
=
440 CreateRequestType(direction
, request_type
, recipient
);
441 libusb_fill_control_setup(reinterpret_cast<uint8
*>(resized_buffer
->data()),
446 static_cast<int16
>(length
));
447 libusb_fill_control_transfer(transfer
,
449 reinterpret_cast<uint8
*>(resized_buffer
->data()),
450 PlatformTransferCompletionCallback
,
454 BrowserThread::PostTask(BrowserThread::FILE,
456 base::Bind(&UsbDeviceHandle::SubmitTransfer
,
459 USB_TRANSFER_CONTROL
,
462 base::MessageLoopProxy::current(),
466 void UsbDeviceHandle::BulkTransfer(const UsbEndpointDirection direction
,
467 const uint8 endpoint
,
468 net::IOBuffer
* buffer
,
470 const unsigned int timeout
,
471 const UsbTransferCallback
& callback
) {
473 callback
.Run(USB_TRANSFER_DISCONNECT
, buffer
, 0);
477 PlatformUsbTransferHandle
const transfer
= libusb_alloc_transfer(0);
478 const uint8 new_endpoint
= ConvertTransferDirection(direction
) | endpoint
;
479 libusb_fill_bulk_transfer(transfer
,
482 reinterpret_cast<uint8
*>(buffer
->data()),
483 static_cast<int>(length
),
484 PlatformTransferCompletionCallback
,
488 BrowserThread::PostTask(BrowserThread::FILE,
490 base::Bind(&UsbDeviceHandle::SubmitTransfer
,
494 make_scoped_refptr(buffer
),
496 base::MessageLoopProxy::current(),
500 void UsbDeviceHandle::InterruptTransfer(const UsbEndpointDirection direction
,
501 const uint8 endpoint
,
502 net::IOBuffer
* buffer
,
504 const unsigned int timeout
,
505 const UsbTransferCallback
& callback
) {
507 callback
.Run(USB_TRANSFER_DISCONNECT
, buffer
, 0);
511 PlatformUsbTransferHandle
const transfer
= libusb_alloc_transfer(0);
512 const uint8 new_endpoint
= ConvertTransferDirection(direction
) | endpoint
;
513 libusb_fill_interrupt_transfer(transfer
,
516 reinterpret_cast<uint8
*>(buffer
->data()),
517 static_cast<int>(length
),
518 PlatformTransferCompletionCallback
,
521 BrowserThread::PostTask(BrowserThread::FILE,
523 base::Bind(&UsbDeviceHandle::SubmitTransfer
,
526 USB_TRANSFER_INTERRUPT
,
527 make_scoped_refptr(buffer
),
529 base::MessageLoopProxy::current(),
533 void UsbDeviceHandle::IsochronousTransfer(const UsbEndpointDirection direction
,
534 const uint8 endpoint
,
535 net::IOBuffer
* buffer
,
537 const unsigned int packets
,
538 const unsigned int packet_length
,
539 const unsigned int timeout
,
540 const UsbTransferCallback
& callback
) {
542 callback
.Run(USB_TRANSFER_DISCONNECT
, buffer
, 0);
546 const uint64 total_length
= packets
* packet_length
;
547 CHECK(packets
<= length
&& total_length
<= length
)
548 << "transfer length is too small";
550 PlatformUsbTransferHandle
const transfer
= libusb_alloc_transfer(packets
);
551 const uint8 new_endpoint
= ConvertTransferDirection(direction
) | endpoint
;
552 libusb_fill_iso_transfer(transfer
,
555 reinterpret_cast<uint8
*>(buffer
->data()),
556 static_cast<int>(length
),
558 PlatformTransferCompletionCallback
,
561 libusb_set_iso_packet_lengths(transfer
, packet_length
);
563 BrowserThread::PostTask(BrowserThread::FILE,
565 base::Bind(&UsbDeviceHandle::SubmitTransfer
,
568 USB_TRANSFER_ISOCHRONOUS
,
569 make_scoped_refptr(buffer
),
571 base::MessageLoopProxy::current(),
575 void UsbDeviceHandle::RefreshEndpointMap() {
576 DCHECK(thread_checker_
.CalledOnValidThread());
577 endpoint_map_
.clear();
578 for (ClaimedInterfaceMap::iterator it
= claimed_interfaces_
.begin();
579 it
!= claimed_interfaces_
.end();
581 scoped_refptr
<const UsbInterfaceAltSettingDescriptor
> interface_desc
=
582 interfaces_
->GetInterface(it
->first
)
583 ->GetAltSetting(it
->second
->alternate_setting());
584 for (size_t i
= 0; i
< interface_desc
->GetNumEndpoints(); i
++) {
585 scoped_refptr
<const UsbEndpointDescriptor
> endpoint
=
586 interface_desc
->GetEndpoint(i
);
587 endpoint_map_
[endpoint
->GetAddress()] = it
->first
;
592 scoped_refptr
<UsbDeviceHandle::InterfaceClaimer
>
593 UsbDeviceHandle::GetClaimedInterfaceForEndpoint(unsigned char endpoint
) {
594 unsigned char address
= endpoint
& LIBUSB_ENDPOINT_ADDRESS_MASK
;
595 if (ContainsKey(endpoint_map_
, address
))
596 return claimed_interfaces_
[endpoint_map_
[address
]];
600 void UsbDeviceHandle::SubmitTransfer(
601 PlatformUsbTransferHandle handle
,
602 UsbTransferType transfer_type
,
603 net::IOBuffer
* buffer
,
605 scoped_refptr
<base::MessageLoopProxy
> message_loop_proxy
,
606 const UsbTransferCallback
& callback
) {
607 DCHECK(thread_checker_
.CalledOnValidThread());
609 message_loop_proxy
->PostTask(
612 callback
, USB_TRANSFER_DISCONNECT
, make_scoped_refptr(buffer
), 0));
616 transfer
.transfer_type
= transfer_type
;
617 transfer
.buffer
= buffer
;
618 transfer
.length
= length
;
619 transfer
.callback
= callback
;
620 transfer
.message_loop_proxy
= message_loop_proxy
;
622 // It's OK for this method to return NULL. libusb_submit_transfer will fail if
623 // it requires an interface we didn't claim.
624 transfer
.claimed_interface
= GetClaimedInterfaceForEndpoint(handle
->endpoint
);
626 if (libusb_submit_transfer(handle
) == LIBUSB_SUCCESS
) {
627 transfers_
[handle
] = transfer
;
629 message_loop_proxy
->PostTask(
632 callback
, USB_TRANSFER_ERROR
, make_scoped_refptr(buffer
), 0));
636 void UsbDeviceHandle::InternalClose() {
637 DCHECK(thread_checker_
.CalledOnValidThread());
641 // Cancel all the transfers.
642 for (TransferMap::iterator it
= transfers_
.begin(); it
!= transfers_
.end();
644 // The callback will be called some time later.
645 libusb_cancel_transfer(it
->first
);
648 // Attempt-release all the interfaces.
649 // It will be retained until the transfer cancellation is finished.
650 claimed_interfaces_
.clear();
652 // Cannot close device handle here. Need to wait for libusb_cancel_transfer to
657 } // namespace usb_service