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_context.h"
7 #include "base/atomicops.h"
8 #include "base/logging.h"
9 #include "base/threading/platform_thread.h"
10 #include "device/usb/usb_error.h"
11 #include "third_party/libusb/src/libusb/interrupt.h"
12 #include "third_party/libusb/src/libusb/libusb.h"
16 // The UsbEventHandler works around a design flaw in the libusb interface. There
17 // is currently no way to signal to libusb that any caller into one of the event
18 // handler calls should return without handling any events.
19 class UsbContext::UsbEventHandler
: public base::PlatformThread::Delegate
{
21 explicit UsbEventHandler(libusb_context
* context
);
22 ~UsbEventHandler() override
;
24 // base::PlatformThread::Delegate
25 void ThreadMain() override
;
30 base::subtle::Atomic32 running_
;
31 libusb_context
* context_
;
32 base::PlatformThreadHandle thread_handle_
;
33 DISALLOW_COPY_AND_ASSIGN(UsbEventHandler
);
36 UsbContext::UsbEventHandler::UsbEventHandler(libusb_context
* context
)
37 : context_(context
), thread_handle_(0) {
38 base::subtle::Release_Store(&running_
, 1);
39 bool success
= base::PlatformThread::Create(0, this, &thread_handle_
);
40 DCHECK(success
) << "Failed to create USB IO handling thread.";
43 UsbContext::UsbEventHandler::~UsbEventHandler() {
44 libusb_exit(context_
);
47 void UsbContext::UsbEventHandler::ThreadMain() {
48 base::PlatformThread::SetName("UsbEventHandler");
49 VLOG(1) << "UsbEventHandler started.";
51 while (base::subtle::Acquire_Load(&running_
)) {
52 const int rv
= libusb_handle_events(context_
);
53 if (rv
!= LIBUSB_SUCCESS
) {
54 VLOG(1) << "Failed to handle events: "
55 << ConvertPlatformUsbErrorToString(rv
);
59 VLOG(1) << "UsbEventHandler shutting down.";
63 void UsbContext::UsbEventHandler::Stop() {
64 base::subtle::Release_Store(&running_
, 0);
65 libusb_interrupt_handle_event(context_
);
66 base::PlatformThread::Join(thread_handle_
);
69 UsbContext::UsbContext(PlatformUsbContext context
) : context_(context
) {
70 // Ownership of the PlatformUsbContext is passed to the event handler thread.
71 event_handler_
= new UsbEventHandler(context_
);
74 UsbContext::~UsbContext() {
75 DCHECK(thread_checker_
.CalledOnValidThread());
76 event_handler_
->Stop();