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 typedef libusb_device
* PlatformUsbDevice
;
27 void HandleTransferCompletion(usb_service::PlatformUsbTransferHandle transfer
);
31 static uint8
ConvertTransferDirection(const UsbEndpointDirection direction
) {
33 case USB_DIRECTION_INBOUND
:
34 return LIBUSB_ENDPOINT_IN
;
35 case USB_DIRECTION_OUTBOUND
:
36 return LIBUSB_ENDPOINT_OUT
;
39 return LIBUSB_ENDPOINT_IN
;
43 static uint8
CreateRequestType(
44 const UsbEndpointDirection direction
,
45 const UsbDeviceHandle::TransferRequestType request_type
,
46 const UsbDeviceHandle::TransferRecipient recipient
) {
47 uint8 result
= ConvertTransferDirection(direction
);
49 switch (request_type
) {
50 case UsbDeviceHandle::STANDARD
:
51 result
|= LIBUSB_REQUEST_TYPE_STANDARD
;
53 case UsbDeviceHandle::CLASS
:
54 result
|= LIBUSB_REQUEST_TYPE_CLASS
;
56 case UsbDeviceHandle::VENDOR
:
57 result
|= LIBUSB_REQUEST_TYPE_VENDOR
;
59 case UsbDeviceHandle::RESERVED
:
60 result
|= LIBUSB_REQUEST_TYPE_RESERVED
;
65 case UsbDeviceHandle::DEVICE
:
66 result
|= LIBUSB_RECIPIENT_DEVICE
;
68 case UsbDeviceHandle::INTERFACE
:
69 result
|= LIBUSB_RECIPIENT_INTERFACE
;
71 case UsbDeviceHandle::ENDPOINT
:
72 result
|= LIBUSB_RECIPIENT_ENDPOINT
;
74 case UsbDeviceHandle::OTHER
:
75 result
|= LIBUSB_RECIPIENT_OTHER
;
82 static UsbTransferStatus
ConvertTransferStatus(
83 const libusb_transfer_status status
) {
85 case LIBUSB_TRANSFER_COMPLETED
:
86 return USB_TRANSFER_COMPLETED
;
87 case LIBUSB_TRANSFER_ERROR
:
88 return USB_TRANSFER_ERROR
;
89 case LIBUSB_TRANSFER_TIMED_OUT
:
90 return USB_TRANSFER_TIMEOUT
;
91 case LIBUSB_TRANSFER_STALL
:
92 return USB_TRANSFER_STALLED
;
93 case LIBUSB_TRANSFER_NO_DEVICE
:
94 return USB_TRANSFER_DISCONNECT
;
95 case LIBUSB_TRANSFER_OVERFLOW
:
96 return USB_TRANSFER_OVERFLOW
;
97 case LIBUSB_TRANSFER_CANCELLED
:
98 return USB_TRANSFER_CANCELLED
;
101 return USB_TRANSFER_ERROR
;
105 static void LIBUSB_CALL
106 PlatformTransferCompletionCallback(PlatformUsbTransferHandle transfer
) {
107 BrowserThread::PostTask(BrowserThread::FILE,
109 base::Bind(HandleTransferCompletion
, transfer
));
114 void HandleTransferCompletion(PlatformUsbTransferHandle transfer
) {
115 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
116 UsbDeviceHandle
* const device_handle
=
117 reinterpret_cast<UsbDeviceHandle
*>(transfer
->user_data
);
118 CHECK(device_handle
) << "Device handle is closed before transfer finishes.";
119 device_handle
->TransferComplete(transfer
);
120 libusb_free_transfer(transfer
);
123 class UsbDeviceHandle::InterfaceClaimer
124 : public base::RefCountedThreadSafe
<UsbDeviceHandle::InterfaceClaimer
> {
126 InterfaceClaimer(const scoped_refptr
<UsbDeviceHandle
> handle
,
127 const int interface_number
);
131 int alternate_setting() const { return alternate_setting_
; }
132 void set_alternate_setting(const int alternate_setting
) {
133 alternate_setting_
= alternate_setting
;
137 friend class UsbDevice
;
138 friend class base::RefCountedThreadSafe
<InterfaceClaimer
>;
141 const scoped_refptr
<UsbDeviceHandle
> handle_
;
142 const int interface_number_
;
143 int alternate_setting_
;
145 DISALLOW_COPY_AND_ASSIGN(InterfaceClaimer
);
148 UsbDeviceHandle::InterfaceClaimer::InterfaceClaimer(
149 const scoped_refptr
<UsbDeviceHandle
> handle
,
150 const int interface_number
)
152 interface_number_(interface_number
),
153 alternate_setting_(0) {
156 UsbDeviceHandle::InterfaceClaimer::~InterfaceClaimer() {
157 libusb_release_interface(handle_
->handle(), interface_number_
);
160 bool UsbDeviceHandle::InterfaceClaimer::Claim() const {
161 return libusb_claim_interface(handle_
->handle(), interface_number_
) == 0;
164 struct UsbDeviceHandle::Transfer
{
168 UsbTransferType transfer_type
;
169 scoped_refptr
<net::IOBuffer
> buffer
;
170 scoped_refptr
<UsbDeviceHandle::InterfaceClaimer
> claimed_interface
;
171 scoped_refptr
<base::MessageLoopProxy
> message_loop_proxy
;
173 UsbTransferCallback callback
;
176 UsbDeviceHandle::Transfer::Transfer()
177 : transfer_type(USB_TRANSFER_CONTROL
), length(0) {
180 UsbDeviceHandle::Transfer::~Transfer() {
183 UsbDeviceHandle::UsbDeviceHandle(scoped_refptr
<UsbContext
> context
,
185 PlatformUsbDeviceHandle handle
,
186 scoped_refptr
<UsbConfigDescriptor
> interfaces
)
189 interfaces_(interfaces
),
191 DCHECK(thread_checker_
.CalledOnValidThread());
192 DCHECK(handle
) << "Cannot create device with NULL handle.";
193 DCHECK(interfaces_
) << "Unabled to list interfaces";
196 UsbDeviceHandle::UsbDeviceHandle() : device_(NULL
), handle_(NULL
) {
199 UsbDeviceHandle::~UsbDeviceHandle() {
200 DCHECK(thread_checker_
.CalledOnValidThread());
202 libusb_close(handle_
);
206 scoped_refptr
<UsbDevice
> UsbDeviceHandle::device() const {
210 void UsbDeviceHandle::Close() {
211 DCHECK(thread_checker_
.CalledOnValidThread());
213 device_
->Close(this);
216 void UsbDeviceHandle::TransferComplete(PlatformUsbTransferHandle handle
) {
217 DCHECK(ContainsKey(transfers_
, handle
)) << "Missing transfer completed";
219 Transfer transfer
= transfers_
[handle
];
220 transfers_
.erase(handle
);
222 DCHECK_GE(handle
->actual_length
, 0) << "Negative actual length received";
223 size_t actual_length
=
224 static_cast<size_t>(std::max(handle
->actual_length
, 0));
226 DCHECK(transfer
.length
>= actual_length
)
227 << "data too big for our buffer (libusb failure?)";
229 scoped_refptr
<net::IOBuffer
> buffer
= transfer
.buffer
;
230 switch (transfer
.transfer_type
) {
231 case USB_TRANSFER_CONTROL
:
232 // If the transfer is a control transfer we do not expose the control
233 // setup header to the caller. This logic strips off the header if
234 // present before invoking the callback provided with the transfer.
235 if (actual_length
> 0) {
236 CHECK(transfer
.length
>= LIBUSB_CONTROL_SETUP_SIZE
)
237 << "buffer was not correctly set: too small for the control header";
239 if (transfer
.length
>= (LIBUSB_CONTROL_SETUP_SIZE
+ actual_length
)) {
240 // If the payload is zero bytes long, pad out the allocated buffer
241 // size to one byte so that an IOBuffer of that size can be allocated.
242 scoped_refptr
<net::IOBuffer
> resized_buffer
=
243 new net::IOBuffer(static_cast<int>(
244 std::max(actual_length
, static_cast<size_t>(1))));
245 memcpy(resized_buffer
->data(),
246 buffer
->data() + LIBUSB_CONTROL_SETUP_SIZE
,
248 buffer
= resized_buffer
;
253 case USB_TRANSFER_ISOCHRONOUS
:
254 // Isochronous replies might carry data in the different isoc packets even
255 // if the transfer actual_data value is zero. Furthermore, not all of the
256 // received packets might contain data, so we need to calculate how many
257 // data bytes we are effectively providing and pack the results.
258 if (actual_length
== 0) {
259 size_t packet_buffer_start
= 0;
260 for (int i
= 0; i
< handle
->num_iso_packets
; ++i
) {
261 PlatformUsbIsoPacketDescriptor packet
= &handle
->iso_packet_desc
[i
];
262 if (packet
->actual_length
> 0) {
263 // We don't need to copy as long as all packets until now provide
264 // all the data the packet can hold.
265 if (actual_length
< packet_buffer_start
) {
266 CHECK(packet_buffer_start
+ packet
->actual_length
<=
268 memmove(buffer
->data() + actual_length
,
269 buffer
->data() + packet_buffer_start
,
270 packet
->actual_length
);
272 actual_length
+= packet
->actual_length
;
275 packet_buffer_start
+= packet
->length
;
280 case USB_TRANSFER_BULK
:
281 case USB_TRANSFER_INTERRUPT
:
285 NOTREACHED() << "Invalid usb transfer type";
289 transfer
.message_loop_proxy
->PostTask(
291 base::Bind(transfer
.callback
,
292 ConvertTransferStatus(handle
->status
),
296 // Must release interface first before actually delete this.
297 transfer
.claimed_interface
= NULL
;
300 bool UsbDeviceHandle::ClaimInterface(const int interface_number
) {
301 DCHECK(thread_checker_
.CalledOnValidThread());
304 if (ContainsKey(claimed_interfaces_
, interface_number
))
307 scoped_refptr
<InterfaceClaimer
> claimer
=
308 new InterfaceClaimer(this, interface_number
);
310 if (claimer
->Claim()) {
311 claimed_interfaces_
[interface_number
] = claimer
;
312 RefreshEndpointMap();
318 bool UsbDeviceHandle::ReleaseInterface(const int interface_number
) {
319 DCHECK(thread_checker_
.CalledOnValidThread());
322 if (!ContainsKey(claimed_interfaces_
, interface_number
))
325 // Cancel all the transfers on that interface.
326 InterfaceClaimer
* interface_claimer
=
327 claimed_interfaces_
[interface_number
].get();
328 for (TransferMap::iterator it
= transfers_
.begin(); it
!= transfers_
.end();
330 if (it
->second
.claimed_interface
.get() == interface_claimer
)
331 libusb_cancel_transfer(it
->first
);
333 claimed_interfaces_
.erase(interface_number
);
335 RefreshEndpointMap();
339 bool UsbDeviceHandle::SetInterfaceAlternateSetting(
340 const int interface_number
,
341 const int alternate_setting
) {
342 DCHECK(thread_checker_
.CalledOnValidThread());
345 if (!ContainsKey(claimed_interfaces_
, interface_number
))
347 const int rv
= libusb_set_interface_alt_setting(
348 handle_
, interface_number
, alternate_setting
);
350 claimed_interfaces_
[interface_number
]->set_alternate_setting(
352 RefreshEndpointMap();
358 bool UsbDeviceHandle::ResetDevice() {
359 DCHECK(thread_checker_
.CalledOnValidThread());
363 return libusb_reset_device(handle_
) == 0;
366 bool UsbDeviceHandle::GetSerial(base::string16
* serial
) {
367 DCHECK(thread_checker_
.CalledOnValidThread());
368 PlatformUsbDevice device
= libusb_get_device(handle_
);
369 libusb_device_descriptor desc
;
371 if (libusb_get_device_descriptor(device
, &desc
) != LIBUSB_SUCCESS
)
374 if (desc
.iSerialNumber
== 0)
377 // Getting supported language ID.
378 uint16 langid
[128] = {0};
381 libusb_get_string_descriptor(handle_
,
384 reinterpret_cast<unsigned char*>(&langid
[0]),
389 int language_count
= (size
- 2) / 2;
391 for (int i
= 1; i
<= language_count
; ++i
) {
392 // Get the string using language ID.
393 base::char16 text
[256] = {0};
395 libusb_get_string_descriptor(handle_
,
398 reinterpret_cast<unsigned char*>(&text
[0]),
402 if ((text
[0] >> 8) != LIBUSB_DT_STRING
)
404 if ((text
[0] & 255) > size
)
408 *serial
= base::string16(text
+ 1, size
);
414 void UsbDeviceHandle::ControlTransfer(const UsbEndpointDirection direction
,
415 const TransferRequestType request_type
,
416 const TransferRecipient recipient
,
420 net::IOBuffer
* buffer
,
422 const unsigned int timeout
,
423 const UsbTransferCallback
& callback
) {
425 callback
.Run(USB_TRANSFER_DISCONNECT
, buffer
, 0);
429 const size_t resized_length
= LIBUSB_CONTROL_SETUP_SIZE
+ length
;
430 scoped_refptr
<net::IOBuffer
> resized_buffer(
431 new net::IOBufferWithSize(static_cast<int>(resized_length
)));
432 if (!resized_buffer
) {
433 callback
.Run(USB_TRANSFER_ERROR
, buffer
, 0);
436 memcpy(resized_buffer
->data() + LIBUSB_CONTROL_SETUP_SIZE
,
438 static_cast<int>(length
));
440 PlatformUsbTransferHandle
const transfer
= libusb_alloc_transfer(0);
441 const uint8 converted_type
=
442 CreateRequestType(direction
, request_type
, recipient
);
443 libusb_fill_control_setup(reinterpret_cast<uint8
*>(resized_buffer
->data()),
448 static_cast<int16
>(length
));
449 libusb_fill_control_transfer(transfer
,
451 reinterpret_cast<uint8
*>(resized_buffer
->data()),
452 PlatformTransferCompletionCallback
,
456 BrowserThread::PostTask(BrowserThread::FILE,
458 base::Bind(&UsbDeviceHandle::SubmitTransfer
,
461 USB_TRANSFER_CONTROL
,
464 base::MessageLoopProxy::current(),
468 void UsbDeviceHandle::BulkTransfer(const UsbEndpointDirection direction
,
469 const uint8 endpoint
,
470 net::IOBuffer
* buffer
,
472 const unsigned int timeout
,
473 const UsbTransferCallback
& callback
) {
475 callback
.Run(USB_TRANSFER_DISCONNECT
, buffer
, 0);
479 PlatformUsbTransferHandle
const transfer
= libusb_alloc_transfer(0);
480 const uint8 new_endpoint
= ConvertTransferDirection(direction
) | endpoint
;
481 libusb_fill_bulk_transfer(transfer
,
484 reinterpret_cast<uint8
*>(buffer
->data()),
485 static_cast<int>(length
),
486 PlatformTransferCompletionCallback
,
490 BrowserThread::PostTask(BrowserThread::FILE,
492 base::Bind(&UsbDeviceHandle::SubmitTransfer
,
496 make_scoped_refptr(buffer
),
498 base::MessageLoopProxy::current(),
502 void UsbDeviceHandle::InterruptTransfer(const UsbEndpointDirection direction
,
503 const uint8 endpoint
,
504 net::IOBuffer
* buffer
,
506 const unsigned int timeout
,
507 const UsbTransferCallback
& callback
) {
509 callback
.Run(USB_TRANSFER_DISCONNECT
, buffer
, 0);
513 PlatformUsbTransferHandle
const transfer
= libusb_alloc_transfer(0);
514 const uint8 new_endpoint
= ConvertTransferDirection(direction
) | endpoint
;
515 libusb_fill_interrupt_transfer(transfer
,
518 reinterpret_cast<uint8
*>(buffer
->data()),
519 static_cast<int>(length
),
520 PlatformTransferCompletionCallback
,
523 BrowserThread::PostTask(BrowserThread::FILE,
525 base::Bind(&UsbDeviceHandle::SubmitTransfer
,
528 USB_TRANSFER_INTERRUPT
,
529 make_scoped_refptr(buffer
),
531 base::MessageLoopProxy::current(),
535 void UsbDeviceHandle::IsochronousTransfer(const UsbEndpointDirection direction
,
536 const uint8 endpoint
,
537 net::IOBuffer
* buffer
,
539 const unsigned int packets
,
540 const unsigned int packet_length
,
541 const unsigned int timeout
,
542 const UsbTransferCallback
& callback
) {
544 callback
.Run(USB_TRANSFER_DISCONNECT
, buffer
, 0);
548 const uint64 total_length
= packets
* packet_length
;
549 CHECK(packets
<= length
&& total_length
<= length
)
550 << "transfer length is too small";
552 PlatformUsbTransferHandle
const transfer
= libusb_alloc_transfer(packets
);
553 const uint8 new_endpoint
= ConvertTransferDirection(direction
) | endpoint
;
554 libusb_fill_iso_transfer(transfer
,
557 reinterpret_cast<uint8
*>(buffer
->data()),
558 static_cast<int>(length
),
560 PlatformTransferCompletionCallback
,
563 libusb_set_iso_packet_lengths(transfer
, packet_length
);
565 BrowserThread::PostTask(BrowserThread::FILE,
567 base::Bind(&UsbDeviceHandle::SubmitTransfer
,
570 USB_TRANSFER_ISOCHRONOUS
,
571 make_scoped_refptr(buffer
),
573 base::MessageLoopProxy::current(),
577 void UsbDeviceHandle::RefreshEndpointMap() {
578 DCHECK(thread_checker_
.CalledOnValidThread());
579 endpoint_map_
.clear();
580 for (ClaimedInterfaceMap::iterator it
= claimed_interfaces_
.begin();
581 it
!= claimed_interfaces_
.end();
583 scoped_refptr
<const UsbInterfaceAltSettingDescriptor
> interface_desc
=
584 interfaces_
->GetInterface(it
->first
)
585 ->GetAltSetting(it
->second
->alternate_setting());
586 for (size_t i
= 0; i
< interface_desc
->GetNumEndpoints(); i
++) {
587 scoped_refptr
<const UsbEndpointDescriptor
> endpoint
=
588 interface_desc
->GetEndpoint(i
);
589 endpoint_map_
[endpoint
->GetAddress()] = it
->first
;
594 scoped_refptr
<UsbDeviceHandle::InterfaceClaimer
>
595 UsbDeviceHandle::GetClaimedInterfaceForEndpoint(unsigned char endpoint
) {
596 unsigned char address
= endpoint
& LIBUSB_ENDPOINT_ADDRESS_MASK
;
597 if (ContainsKey(endpoint_map_
, address
))
598 return claimed_interfaces_
[endpoint_map_
[address
]];
602 void UsbDeviceHandle::SubmitTransfer(
603 PlatformUsbTransferHandle handle
,
604 UsbTransferType transfer_type
,
605 net::IOBuffer
* buffer
,
607 scoped_refptr
<base::MessageLoopProxy
> message_loop_proxy
,
608 const UsbTransferCallback
& callback
) {
609 DCHECK(thread_checker_
.CalledOnValidThread());
611 message_loop_proxy
->PostTask(
614 callback
, USB_TRANSFER_DISCONNECT
, make_scoped_refptr(buffer
), 0));
618 transfer
.transfer_type
= transfer_type
;
619 transfer
.buffer
= buffer
;
620 transfer
.length
= length
;
621 transfer
.callback
= callback
;
622 transfer
.message_loop_proxy
= message_loop_proxy
;
624 // It's OK for this method to return NULL. libusb_submit_transfer will fail if
625 // it requires an interface we didn't claim.
626 transfer
.claimed_interface
= GetClaimedInterfaceForEndpoint(handle
->endpoint
);
628 if (libusb_submit_transfer(handle
) == LIBUSB_SUCCESS
) {
629 transfers_
[handle
] = transfer
;
631 message_loop_proxy
->PostTask(
634 callback
, USB_TRANSFER_ERROR
, make_scoped_refptr(buffer
), 0));
638 void UsbDeviceHandle::InternalClose() {
639 DCHECK(thread_checker_
.CalledOnValidThread());
643 // Cancel all the transfers.
644 for (TransferMap::iterator it
= transfers_
.begin(); it
!= transfers_
.end();
646 // The callback will be called some time later.
647 libusb_cancel_transfer(it
->first
);
650 // Attempt-release all the interfaces.
651 // It will be retained until the transfer cancellation is finished.
652 claimed_interfaces_
.clear();
654 // Cannot close device handle here. Need to wait for libusb_cancel_transfer to
659 } // namespace usb_service