summaryrefslogtreecommitdiffstats
path: root/device/usb/usb_context.cc
blob: 6959fab01dc9690fc7e4fa3ae68aefa291f0cf93 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "device/usb/usb_context.h"

#include "base/atomicops.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/threading/simple_thread.h"
#include "device/usb/usb_error.h"
#include "third_party/libusb/src/libusb/interrupt.h"
#include "third_party/libusb/src/libusb/libusb.h"

namespace device {

// The UsbEventHandler works around a design flaw in the libusb interface. There
// is currently no way to signal to libusb that any caller into one of the event
// handler calls should return without handling any events.
class UsbContext::UsbEventHandler : public base::SimpleThread {
 public:
  explicit UsbEventHandler(libusb_context* context);
  ~UsbEventHandler() override;

  // base::SimpleThread
  void Run() override;

  void Stop();

 private:
  base::subtle::Atomic32 running_;
  libusb_context* context_;
  DISALLOW_COPY_AND_ASSIGN(UsbEventHandler);
};

UsbContext::UsbEventHandler::UsbEventHandler(libusb_context* context)
    : base::SimpleThread("UsbEventHandler"), context_(context) {
  base::subtle::Release_Store(&running_, 1);
}

UsbContext::UsbEventHandler::~UsbEventHandler() {
  libusb_exit(context_);
}

void UsbContext::UsbEventHandler::Run() {
  VLOG(1) << "UsbEventHandler started.";

  while (base::subtle::Acquire_Load(&running_)) {
    const int rv = libusb_handle_events(context_);
    if (rv != LIBUSB_SUCCESS) {
      VLOG(1) << "Failed to handle events: "
              << ConvertPlatformUsbErrorToString(rv);
    }
  }

  VLOG(1) << "UsbEventHandler shutting down.";
}

void UsbContext::UsbEventHandler::Stop() {
  base::subtle::Release_Store(&running_, 0);
  libusb_interrupt_handle_event(context_);
}

UsbContext::UsbContext(PlatformUsbContext context) : context_(context) {
  // Ownership of the PlatformUsbContext is passed to the event handler thread.
  event_handler_.reset(new UsbEventHandler(context_));
  event_handler_->Start();
}

UsbContext::~UsbContext() {
  event_handler_->Stop();
  event_handler_->Join();
}

}  // namespace device