Updating trunk VERSION from 2139.0 to 2140.0
[chromium-blink-merge.git] / components / usb_service / usb_device_handle_impl.cc
blob73b04b95eb7f260121ce1255951c6998d4a9fcf6
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_impl.h"
7 #include <algorithm>
8 #include <vector>
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_impl.h"
16 #include "components/usb_service/usb_error.h"
17 #include "components/usb_service/usb_interface.h"
18 #include "components/usb_service/usb_service.h"
19 #include "content/public/browser/browser_thread.h"
20 #include "third_party/libusb/src/libusb/libusb.h"
22 using content::BrowserThread;
24 namespace usb_service {
26 typedef libusb_device* PlatformUsbDevice;
28 void HandleTransferCompletion(usb_service::PlatformUsbTransferHandle transfer);
30 namespace {
32 static uint8 ConvertTransferDirection(const UsbEndpointDirection direction) {
33 switch (direction) {
34 case USB_DIRECTION_INBOUND:
35 return LIBUSB_ENDPOINT_IN;
36 case USB_DIRECTION_OUTBOUND:
37 return LIBUSB_ENDPOINT_OUT;
38 default:
39 NOTREACHED();
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;
53 break;
54 case UsbDeviceHandle::CLASS:
55 result |= LIBUSB_REQUEST_TYPE_CLASS;
56 break;
57 case UsbDeviceHandle::VENDOR:
58 result |= LIBUSB_REQUEST_TYPE_VENDOR;
59 break;
60 case UsbDeviceHandle::RESERVED:
61 result |= LIBUSB_REQUEST_TYPE_RESERVED;
62 break;
65 switch (recipient) {
66 case UsbDeviceHandle::DEVICE:
67 result |= LIBUSB_RECIPIENT_DEVICE;
68 break;
69 case UsbDeviceHandle::INTERFACE:
70 result |= LIBUSB_RECIPIENT_INTERFACE;
71 break;
72 case UsbDeviceHandle::ENDPOINT:
73 result |= LIBUSB_RECIPIENT_ENDPOINT;
74 break;
75 case UsbDeviceHandle::OTHER:
76 result |= LIBUSB_RECIPIENT_OTHER;
77 break;
80 return result;
83 static UsbTransferStatus ConvertTransferStatus(
84 const libusb_transfer_status status) {
85 switch (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;
100 default:
101 NOTREACHED();
102 return USB_TRANSFER_ERROR;
106 static void LIBUSB_CALL
107 PlatformTransferCompletionCallback(PlatformUsbTransferHandle transfer) {
108 BrowserThread::PostTask(BrowserThread::FILE,
109 FROM_HERE,
110 base::Bind(HandleTransferCompletion, transfer));
113 } // namespace
115 void HandleTransferCompletion(PlatformUsbTransferHandle transfer) {
116 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
117 UsbDeviceHandleImpl* const device_handle =
118 reinterpret_cast<UsbDeviceHandleImpl*>(transfer->user_data);
119 CHECK(device_handle) << "Device handle is closed before transfer finishes.";
120 device_handle->TransferComplete(transfer);
121 libusb_free_transfer(transfer);
124 class UsbDeviceHandleImpl::InterfaceClaimer
125 : public base::RefCountedThreadSafe<UsbDeviceHandleImpl::InterfaceClaimer> {
126 public:
127 InterfaceClaimer(const scoped_refptr<UsbDeviceHandleImpl> handle,
128 const int interface_number);
130 bool Claim() const;
132 int alternate_setting() const { return alternate_setting_; }
133 void set_alternate_setting(const int alternate_setting) {
134 alternate_setting_ = alternate_setting;
137 private:
138 friend class UsbDevice;
139 friend class base::RefCountedThreadSafe<InterfaceClaimer>;
140 ~InterfaceClaimer();
142 const scoped_refptr<UsbDeviceHandleImpl> handle_;
143 const int interface_number_;
144 int alternate_setting_;
146 DISALLOW_COPY_AND_ASSIGN(InterfaceClaimer);
149 UsbDeviceHandleImpl::InterfaceClaimer::InterfaceClaimer(
150 const scoped_refptr<UsbDeviceHandleImpl> handle,
151 const int interface_number)
152 : handle_(handle),
153 interface_number_(interface_number),
154 alternate_setting_(0) {
157 UsbDeviceHandleImpl::InterfaceClaimer::~InterfaceClaimer() {
158 libusb_release_interface(handle_->handle(), interface_number_);
161 bool UsbDeviceHandleImpl::InterfaceClaimer::Claim() const {
162 const int rv = libusb_claim_interface(handle_->handle(), interface_number_);
163 if (rv != LIBUSB_SUCCESS) {
164 VLOG(1) << "Failed to claim interface: " << ConvertErrorToString(rv);
166 return rv == LIBUSB_SUCCESS;
169 struct UsbDeviceHandleImpl::Transfer {
170 Transfer();
171 ~Transfer();
173 UsbTransferType transfer_type;
174 scoped_refptr<net::IOBuffer> buffer;
175 scoped_refptr<UsbDeviceHandleImpl::InterfaceClaimer> claimed_interface;
176 scoped_refptr<base::MessageLoopProxy> message_loop_proxy;
177 size_t length;
178 UsbTransferCallback callback;
181 UsbDeviceHandleImpl::Transfer::Transfer()
182 : transfer_type(USB_TRANSFER_CONTROL), length(0) {
185 UsbDeviceHandleImpl::Transfer::~Transfer() {
188 UsbDeviceHandleImpl::UsbDeviceHandleImpl(
189 scoped_refptr<UsbContext> context,
190 UsbDeviceImpl* device,
191 PlatformUsbDeviceHandle handle,
192 scoped_refptr<UsbConfigDescriptor> interfaces)
193 : device_(device),
194 handle_(handle),
195 interfaces_(interfaces),
196 context_(context) {
197 DCHECK(thread_checker_.CalledOnValidThread());
198 DCHECK(handle) << "Cannot create device with NULL handle.";
199 DCHECK(interfaces_.get()) << "Unable to list interfaces";
202 UsbDeviceHandleImpl::~UsbDeviceHandleImpl() {
203 DCHECK(thread_checker_.CalledOnValidThread());
205 libusb_close(handle_);
206 handle_ = NULL;
209 scoped_refptr<UsbDevice> UsbDeviceHandleImpl::GetDevice() const {
210 return static_cast<UsbDevice*>(device_);
213 void UsbDeviceHandleImpl::Close() {
214 DCHECK(thread_checker_.CalledOnValidThread());
215 if (device_)
216 device_->Close(this);
219 void UsbDeviceHandleImpl::TransferComplete(PlatformUsbTransferHandle handle) {
220 DCHECK(ContainsKey(transfers_, handle)) << "Missing transfer completed";
222 Transfer transfer = transfers_[handle];
223 transfers_.erase(handle);
225 DCHECK_GE(handle->actual_length, 0) << "Negative actual length received";
226 size_t actual_length =
227 static_cast<size_t>(std::max(handle->actual_length, 0));
229 DCHECK(transfer.length >= actual_length)
230 << "data too big for our buffer (libusb failure?)";
232 scoped_refptr<net::IOBuffer> buffer = transfer.buffer;
233 switch (transfer.transfer_type) {
234 case USB_TRANSFER_CONTROL:
235 // If the transfer is a control transfer we do not expose the control
236 // setup header to the caller. This logic strips off the header if
237 // present before invoking the callback provided with the transfer.
238 if (actual_length > 0) {
239 CHECK(transfer.length >= LIBUSB_CONTROL_SETUP_SIZE)
240 << "buffer was not correctly set: too small for the control header";
242 if (transfer.length >= (LIBUSB_CONTROL_SETUP_SIZE + actual_length)) {
243 // If the payload is zero bytes long, pad out the allocated buffer
244 // size to one byte so that an IOBuffer of that size can be allocated.
245 scoped_refptr<net::IOBuffer> resized_buffer =
246 new net::IOBuffer(static_cast<int>(
247 std::max(actual_length, static_cast<size_t>(1))));
248 memcpy(resized_buffer->data(),
249 buffer->data() + LIBUSB_CONTROL_SETUP_SIZE,
250 actual_length);
251 buffer = resized_buffer;
254 break;
256 case USB_TRANSFER_ISOCHRONOUS:
257 // Isochronous replies might carry data in the different isoc packets even
258 // if the transfer actual_data value is zero. Furthermore, not all of the
259 // received packets might contain data, so we need to calculate how many
260 // data bytes we are effectively providing and pack the results.
261 if (actual_length == 0) {
262 size_t packet_buffer_start = 0;
263 for (int i = 0; i < handle->num_iso_packets; ++i) {
264 PlatformUsbIsoPacketDescriptor packet = &handle->iso_packet_desc[i];
265 if (packet->actual_length > 0) {
266 // We don't need to copy as long as all packets until now provide
267 // all the data the packet can hold.
268 if (actual_length < packet_buffer_start) {
269 CHECK(packet_buffer_start + packet->actual_length <=
270 transfer.length);
271 memmove(buffer->data() + actual_length,
272 buffer->data() + packet_buffer_start,
273 packet->actual_length);
275 actual_length += packet->actual_length;
278 packet_buffer_start += packet->length;
281 break;
283 case USB_TRANSFER_BULK:
284 case USB_TRANSFER_INTERRUPT:
285 break;
287 default:
288 NOTREACHED() << "Invalid usb transfer type";
289 break;
292 transfer.message_loop_proxy->PostTask(
293 FROM_HERE,
294 base::Bind(transfer.callback,
295 ConvertTransferStatus(handle->status),
296 buffer,
297 actual_length));
299 // Must release interface first before actually delete this.
300 transfer.claimed_interface = NULL;
303 bool UsbDeviceHandleImpl::ClaimInterface(const int interface_number) {
304 DCHECK(thread_checker_.CalledOnValidThread());
305 if (!device_)
306 return false;
307 if (ContainsKey(claimed_interfaces_, interface_number))
308 return true;
310 scoped_refptr<InterfaceClaimer> claimer =
311 new InterfaceClaimer(this, interface_number);
313 if (claimer->Claim()) {
314 claimed_interfaces_[interface_number] = claimer;
315 RefreshEndpointMap();
316 return true;
318 return false;
321 bool UsbDeviceHandleImpl::ReleaseInterface(const int interface_number) {
322 DCHECK(thread_checker_.CalledOnValidThread());
323 if (!device_)
324 return false;
325 if (!ContainsKey(claimed_interfaces_, interface_number))
326 return false;
328 // Cancel all the transfers on that interface.
329 InterfaceClaimer* interface_claimer =
330 claimed_interfaces_[interface_number].get();
331 for (TransferMap::iterator it = transfers_.begin(); it != transfers_.end();
332 ++it) {
333 if (it->second.claimed_interface.get() == interface_claimer)
334 libusb_cancel_transfer(it->first);
336 claimed_interfaces_.erase(interface_number);
338 RefreshEndpointMap();
339 return true;
342 bool UsbDeviceHandleImpl::SetInterfaceAlternateSetting(
343 const int interface_number,
344 const int alternate_setting) {
345 DCHECK(thread_checker_.CalledOnValidThread());
346 if (!device_)
347 return false;
348 if (!ContainsKey(claimed_interfaces_, interface_number))
349 return false;
350 const int rv = libusb_set_interface_alt_setting(
351 handle_, interface_number, alternate_setting);
352 if (rv == LIBUSB_SUCCESS) {
353 claimed_interfaces_[interface_number]->set_alternate_setting(
354 alternate_setting);
355 RefreshEndpointMap();
356 } else {
357 VLOG(1) << "Failed to set interface (" << interface_number << ", "
358 << alternate_setting << "): " << ConvertErrorToString(rv);
360 return rv == LIBUSB_SUCCESS;
363 bool UsbDeviceHandleImpl::ResetDevice() {
364 DCHECK(thread_checker_.CalledOnValidThread());
365 if (!device_)
366 return false;
368 const int rv = libusb_reset_device(handle_);
369 if (rv != LIBUSB_SUCCESS) {
370 VLOG(1) << "Failed to reset device: " << ConvertErrorToString(rv);
372 return rv == LIBUSB_SUCCESS;
375 bool UsbDeviceHandleImpl::GetSupportedLanguages() {
376 if (!languages_.empty()) {
377 return true;
380 // The 1-byte length field limits the descriptor to 256-bytes (128 uint16s).
381 uint16 languages[128];
382 int size = libusb_get_string_descriptor(
383 handle_,
386 reinterpret_cast<unsigned char*>(&languages[0]),
387 sizeof(languages));
388 if (size < 0) {
389 VLOG(1) << "Failed to get list of supported languages: "
390 << ConvertErrorToString(size);
391 return false;
392 } else if (size < 2) {
393 VLOG(1) << "String descriptor zero has no header.";
394 return false;
395 // The first 2 bytes of the descriptor are the total length and type tag.
396 } else if ((languages[0] & 0xff) != size) {
397 VLOG(1) << "String descriptor zero size mismatch: " << (languages[0] & 0xff)
398 << " != " << size;
399 return false;
400 } else if ((languages[0] >> 8) != LIBUSB_DT_STRING) {
401 VLOG(1) << "String descriptor zero is not a string descriptor.";
402 return false;
405 languages_.assign(languages[1], languages[(size - 2) / 2]);
406 return true;
409 bool UsbDeviceHandleImpl::GetStringDescriptor(uint8 string_id,
410 base::string16* string) {
411 if (!GetSupportedLanguages()) {
412 return false;
415 std::map<uint8, base::string16>::const_iterator it = strings_.find(string_id);
416 if (it != strings_.end()) {
417 *string = it->second;
418 return true;
421 for (size_t i = 0; i < languages_.size(); ++i) {
422 // Get the string using language ID.
423 uint16 language_id = languages_[i];
424 // The 1-byte length field limits the descriptor to 256-bytes (128 char16s).
425 base::char16 text[128];
426 int size =
427 libusb_get_string_descriptor(handle_,
428 string_id,
429 language_id,
430 reinterpret_cast<unsigned char*>(&text[0]),
431 sizeof(text));
432 if (size < 0) {
433 VLOG(1) << "Failed to get string descriptor " << string_id << " (langid "
434 << language_id << "): " << ConvertErrorToString(size);
435 continue;
436 } else if (size < 2) {
437 VLOG(1) << "String descriptor " << string_id << " (langid " << language_id
438 << ") has no header.";
439 continue;
440 // The first 2 bytes of the descriptor are the total length and type tag.
441 } else if ((text[0] & 0xff) != size) {
442 VLOG(1) << "String descriptor " << string_id << " (langid " << language_id
443 << ") size mismatch: " << (text[0] & 0xff) << " != " << size;
444 continue;
445 } else if ((text[0] >> 8) != LIBUSB_DT_STRING) {
446 VLOG(1) << "String descriptor " << string_id << " (langid " << language_id
447 << ") is not a string descriptor.";
448 continue;
451 *string = base::string16(text + 1, (size - 2) / 2);
452 strings_[string_id] = *string;
453 return true;
456 return false;
459 bool UsbDeviceHandleImpl::GetManufacturer(base::string16* manufacturer) {
460 DCHECK(thread_checker_.CalledOnValidThread());
461 PlatformUsbDevice device = libusb_get_device(handle_);
462 libusb_device_descriptor desc;
464 // This is a non-blocking call as libusb has the descriptor in memory.
465 const int rv = libusb_get_device_descriptor(device, &desc);
466 if (rv != LIBUSB_SUCCESS) {
467 VLOG(1) << "Failed to read device descriptor: " << ConvertErrorToString(rv);
468 return false;
471 if (desc.iManufacturer == 0) {
472 return false;
475 return GetStringDescriptor(desc.iManufacturer, manufacturer);
478 bool UsbDeviceHandleImpl::GetProduct(base::string16* product) {
479 DCHECK(thread_checker_.CalledOnValidThread());
480 PlatformUsbDevice device = libusb_get_device(handle_);
481 libusb_device_descriptor desc;
483 // This is a non-blocking call as libusb has the descriptor in memory.
484 const int rv = libusb_get_device_descriptor(device, &desc);
485 if (rv != LIBUSB_SUCCESS) {
486 VLOG(1) << "Failed to read device descriptor: " << ConvertErrorToString(rv);
487 return false;
490 if (desc.iProduct == 0) {
491 return false;
494 return GetStringDescriptor(desc.iProduct, product);
497 bool UsbDeviceHandleImpl::GetSerial(base::string16* serial) {
498 DCHECK(thread_checker_.CalledOnValidThread());
499 PlatformUsbDevice device = libusb_get_device(handle_);
500 libusb_device_descriptor desc;
502 // This is a non-blocking call as libusb has the descriptor in memory.
503 const int rv = libusb_get_device_descriptor(device, &desc);
504 if (rv != LIBUSB_SUCCESS) {
505 VLOG(1) << "Failed to read device descriptor: " << ConvertErrorToString(rv);
506 return false;
509 if (desc.iSerialNumber == 0) {
510 return false;
513 return GetStringDescriptor(desc.iSerialNumber, serial);
516 void UsbDeviceHandleImpl::ControlTransfer(
517 const UsbEndpointDirection direction,
518 const TransferRequestType request_type,
519 const TransferRecipient recipient,
520 const uint8 request,
521 const uint16 value,
522 const uint16 index,
523 net::IOBuffer* buffer,
524 const size_t length,
525 const unsigned int timeout,
526 const UsbTransferCallback& callback) {
527 if (!device_) {
528 callback.Run(USB_TRANSFER_DISCONNECT, buffer, 0);
529 return;
532 const size_t resized_length = LIBUSB_CONTROL_SETUP_SIZE + length;
533 scoped_refptr<net::IOBuffer> resized_buffer(
534 new net::IOBufferWithSize(static_cast<int>(resized_length)));
535 if (!resized_buffer.get()) {
536 callback.Run(USB_TRANSFER_ERROR, buffer, 0);
537 return;
539 memcpy(resized_buffer->data() + LIBUSB_CONTROL_SETUP_SIZE,
540 buffer->data(),
541 static_cast<int>(length));
543 PlatformUsbTransferHandle const transfer = libusb_alloc_transfer(0);
544 const uint8 converted_type =
545 CreateRequestType(direction, request_type, recipient);
546 libusb_fill_control_setup(reinterpret_cast<uint8*>(resized_buffer->data()),
547 converted_type,
548 request,
549 value,
550 index,
551 static_cast<int16>(length));
552 libusb_fill_control_transfer(transfer,
553 handle_,
554 reinterpret_cast<uint8*>(resized_buffer->data()),
555 PlatformTransferCompletionCallback,
556 this,
557 timeout);
559 BrowserThread::PostTask(BrowserThread::FILE,
560 FROM_HERE,
561 base::Bind(&UsbDeviceHandleImpl::SubmitTransfer,
562 this,
563 transfer,
564 USB_TRANSFER_CONTROL,
565 resized_buffer,
566 resized_length,
567 base::MessageLoopProxy::current(),
568 callback));
571 void UsbDeviceHandleImpl::BulkTransfer(const UsbEndpointDirection direction,
572 const uint8 endpoint,
573 net::IOBuffer* buffer,
574 const size_t length,
575 const unsigned int timeout,
576 const UsbTransferCallback& callback) {
577 if (!device_) {
578 callback.Run(USB_TRANSFER_DISCONNECT, buffer, 0);
579 return;
582 PlatformUsbTransferHandle const transfer = libusb_alloc_transfer(0);
583 const uint8 new_endpoint = ConvertTransferDirection(direction) | endpoint;
584 libusb_fill_bulk_transfer(transfer,
585 handle_,
586 new_endpoint,
587 reinterpret_cast<uint8*>(buffer->data()),
588 static_cast<int>(length),
589 PlatformTransferCompletionCallback,
590 this,
591 timeout);
593 BrowserThread::PostTask(BrowserThread::FILE,
594 FROM_HERE,
595 base::Bind(&UsbDeviceHandleImpl::SubmitTransfer,
596 this,
597 transfer,
598 USB_TRANSFER_BULK,
599 make_scoped_refptr(buffer),
600 length,
601 base::MessageLoopProxy::current(),
602 callback));
605 void UsbDeviceHandleImpl::InterruptTransfer(
606 const UsbEndpointDirection direction,
607 const uint8 endpoint,
608 net::IOBuffer* buffer,
609 const size_t length,
610 const unsigned int timeout,
611 const UsbTransferCallback& callback) {
612 if (!device_) {
613 callback.Run(USB_TRANSFER_DISCONNECT, buffer, 0);
614 return;
617 PlatformUsbTransferHandle const transfer = libusb_alloc_transfer(0);
618 const uint8 new_endpoint = ConvertTransferDirection(direction) | endpoint;
619 libusb_fill_interrupt_transfer(transfer,
620 handle_,
621 new_endpoint,
622 reinterpret_cast<uint8*>(buffer->data()),
623 static_cast<int>(length),
624 PlatformTransferCompletionCallback,
625 this,
626 timeout);
627 BrowserThread::PostTask(BrowserThread::FILE,
628 FROM_HERE,
629 base::Bind(&UsbDeviceHandleImpl::SubmitTransfer,
630 this,
631 transfer,
632 USB_TRANSFER_INTERRUPT,
633 make_scoped_refptr(buffer),
634 length,
635 base::MessageLoopProxy::current(),
636 callback));
639 void UsbDeviceHandleImpl::IsochronousTransfer(
640 const UsbEndpointDirection direction,
641 const uint8 endpoint,
642 net::IOBuffer* buffer,
643 const size_t length,
644 const unsigned int packets,
645 const unsigned int packet_length,
646 const unsigned int timeout,
647 const UsbTransferCallback& callback) {
648 if (!device_) {
649 callback.Run(USB_TRANSFER_DISCONNECT, buffer, 0);
650 return;
653 const uint64 total_length = packets * packet_length;
654 CHECK(packets <= length && total_length <= length)
655 << "transfer length is too small";
657 PlatformUsbTransferHandle const transfer = libusb_alloc_transfer(packets);
658 const uint8 new_endpoint = ConvertTransferDirection(direction) | endpoint;
659 libusb_fill_iso_transfer(transfer,
660 handle_,
661 new_endpoint,
662 reinterpret_cast<uint8*>(buffer->data()),
663 static_cast<int>(length),
664 packets,
665 PlatformTransferCompletionCallback,
666 this,
667 timeout);
668 libusb_set_iso_packet_lengths(transfer, packet_length);
670 BrowserThread::PostTask(BrowserThread::FILE,
671 FROM_HERE,
672 base::Bind(&UsbDeviceHandleImpl::SubmitTransfer,
673 this,
674 transfer,
675 USB_TRANSFER_ISOCHRONOUS,
676 make_scoped_refptr(buffer),
677 length,
678 base::MessageLoopProxy::current(),
679 callback));
682 void UsbDeviceHandleImpl::RefreshEndpointMap() {
683 DCHECK(thread_checker_.CalledOnValidThread());
684 endpoint_map_.clear();
685 for (ClaimedInterfaceMap::iterator it = claimed_interfaces_.begin();
686 it != claimed_interfaces_.end();
687 ++it) {
688 scoped_refptr<const UsbInterfaceAltSettingDescriptor> interface_desc =
689 interfaces_->GetInterface(it->first)
690 ->GetAltSetting(it->second->alternate_setting());
691 for (size_t i = 0; i < interface_desc->GetNumEndpoints(); i++) {
692 scoped_refptr<const UsbEndpointDescriptor> endpoint =
693 interface_desc->GetEndpoint(i);
694 endpoint_map_[endpoint->GetAddress()] = it->first;
699 scoped_refptr<UsbDeviceHandleImpl::InterfaceClaimer>
700 UsbDeviceHandleImpl::GetClaimedInterfaceForEndpoint(unsigned char endpoint) {
701 unsigned char address = endpoint & LIBUSB_ENDPOINT_ADDRESS_MASK;
702 if (ContainsKey(endpoint_map_, address))
703 return claimed_interfaces_[endpoint_map_[address]];
704 return NULL;
707 void UsbDeviceHandleImpl::SubmitTransfer(
708 PlatformUsbTransferHandle handle,
709 UsbTransferType transfer_type,
710 net::IOBuffer* buffer,
711 const size_t length,
712 scoped_refptr<base::MessageLoopProxy> message_loop_proxy,
713 const UsbTransferCallback& callback) {
714 DCHECK(thread_checker_.CalledOnValidThread());
715 if (!device_) {
716 message_loop_proxy->PostTask(
717 FROM_HERE,
718 base::Bind(
719 callback, USB_TRANSFER_DISCONNECT, make_scoped_refptr(buffer), 0));
722 Transfer transfer;
723 transfer.transfer_type = transfer_type;
724 transfer.buffer = buffer;
725 transfer.length = length;
726 transfer.callback = callback;
727 transfer.message_loop_proxy = message_loop_proxy;
729 // It's OK for this method to return NULL. libusb_submit_transfer will fail if
730 // it requires an interface we didn't claim.
731 transfer.claimed_interface = GetClaimedInterfaceForEndpoint(handle->endpoint);
733 const int rv = libusb_submit_transfer(handle);
734 if (rv == LIBUSB_SUCCESS) {
735 transfers_[handle] = transfer;
736 } else {
737 VLOG(1) << "Failed to submit transfer: " << ConvertErrorToString(rv);
738 message_loop_proxy->PostTask(
739 FROM_HERE,
740 base::Bind(
741 callback, USB_TRANSFER_ERROR, make_scoped_refptr(buffer), 0));
745 void UsbDeviceHandleImpl::InternalClose() {
746 DCHECK(thread_checker_.CalledOnValidThread());
747 if (!device_)
748 return;
750 // Cancel all the transfers.
751 for (TransferMap::iterator it = transfers_.begin(); it != transfers_.end();
752 ++it) {
753 // The callback will be called some time later.
754 libusb_cancel_transfer(it->first);
757 // Attempt-release all the interfaces.
758 // It will be retained until the transfer cancellation is finished.
759 claimed_interfaces_.clear();
761 // Cannot close device handle here. Need to wait for libusb_cancel_transfer to
762 // finish.
763 device_ = NULL;
766 } // namespace usb_service