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/simple_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::SimpleThread
{
21 explicit UsbEventHandler(libusb_context
* context
);
22 ~UsbEventHandler() override
;
30 base::subtle::Atomic32 running_
;
31 libusb_context
* context_
;
32 DISALLOW_COPY_AND_ASSIGN(UsbEventHandler
);
35 UsbContext::UsbEventHandler::UsbEventHandler(libusb_context
* context
)
36 : base::SimpleThread("UsbEventHandler"), context_(context
) {
37 base::subtle::Release_Store(&running_
, 1);
40 UsbContext::UsbEventHandler::~UsbEventHandler() {
41 libusb_exit(context_
);
44 void UsbContext::UsbEventHandler::Run() {
45 VLOG(1) << "UsbEventHandler started.";
47 while (base::subtle::Acquire_Load(&running_
)) {
48 const int rv
= libusb_handle_events(context_
);
49 if (rv
!= LIBUSB_SUCCESS
) {
50 VLOG(1) << "Failed to handle events: "
51 << ConvertPlatformUsbErrorToString(rv
);
55 VLOG(1) << "UsbEventHandler shutting down.";
58 void UsbContext::UsbEventHandler::Stop() {
59 base::subtle::Release_Store(&running_
, 0);
60 libusb_interrupt_handle_event(context_
);
63 UsbContext::UsbContext(PlatformUsbContext context
) : context_(context
) {
64 // Ownership of the PlatformUsbContext is passed to the event handler thread.
65 event_handler_
.reset(new UsbEventHandler(context_
));
66 event_handler_
->Start();
69 UsbContext::~UsbContext() {
70 DCHECK(thread_checker_
.CalledOnValidThread());
71 event_handler_
->Stop();
72 event_handler_
->Join();