Implement SetDiscoveryFilter for ChromiumOS
[chromium-blink-merge.git] / device / usb / usb_context.cc
blob7661469d294911994d8fb4b83332fb6fe267b2af
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"
14 namespace device {
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 {
20 public:
21 explicit UsbEventHandler(libusb_context* context);
22 ~UsbEventHandler() override;
24 // base::PlatformThread::Delegate
25 void ThreadMain() override;
27 void Stop();
29 private:
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.";
60 delete this;
63 void UsbContext::UsbEventHandler::Stop() {
64 base::subtle::Release_Store(&running_, 0);
65 libusb_interrupt_handle_event(context_);
68 UsbContext::UsbContext(PlatformUsbContext context) : context_(context) {
69 // Ownership of the PlatformUsbContext is passed to the event handler thread.
70 event_handler_ = new UsbEventHandler(context_);
73 UsbContext::~UsbContext() {
74 DCHECK(thread_checker_.CalledOnValidThread());
75 event_handler_->Stop();
78 } // namespace device