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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
use std::collections::HashMap;
use std::fs::File;
use std::mem;
use std::sync::Arc;
use std::time::Duration;
use anyhow::Context;
use base::error;
use base::AsRawDescriptor;
use base::EventType;
use base::RawDescriptor;
use base::Tube;
use sync::Mutex;
use usb_util::Device;
use vm_control::UsbControlAttachedDevice;
use vm_control::UsbControlCommand;
use vm_control::UsbControlResult;
use vm_control::USB_CONTROL_MAX_PORTS;
use super::error::*;
use super::host_device::HostDevice;
use crate::usb::xhci::usb_hub::UsbHub;
use crate::usb::xhci::xhci_backend_device_provider::XhciBackendDeviceProvider;
use crate::utils::AsyncJobQueue;
use crate::utils::EventHandler;
use crate::utils::EventLoop;
use crate::utils::FailHandle;
const SOCKET_TIMEOUT_MS: u64 = 2000;
pub enum HostBackendDeviceProvider {
Created { control_tube: Mutex<Tube> },
Started { inner: Arc<ProviderInner> },
Failed,
}
impl HostBackendDeviceProvider {
pub fn new() -> Result<(Tube, HostBackendDeviceProvider)> {
let (child_tube, control_tube) = Tube::pair().map_err(Error::CreateControlTube)?;
control_tube
.set_send_timeout(Some(Duration::from_millis(SOCKET_TIMEOUT_MS)))
.map_err(Error::SetupControlTube)?;
control_tube
.set_recv_timeout(Some(Duration::from_millis(SOCKET_TIMEOUT_MS)))
.map_err(Error::SetupControlTube)?;
let provider = HostBackendDeviceProvider::Created {
control_tube: Mutex::new(child_tube),
};
Ok((control_tube, provider))
}
fn start_helper(
&mut self,
fail_handle: Arc<dyn FailHandle>,
event_loop: Arc<EventLoop>,
hub: Arc<UsbHub>,
) -> Result<()> {
match mem::replace(self, HostBackendDeviceProvider::Failed) {
HostBackendDeviceProvider::Created { control_tube } => {
let job_queue =
AsyncJobQueue::init(&event_loop).map_err(Error::StartAsyncJobQueue)?;
let inner = Arc::new(ProviderInner::new(
fail_handle,
job_queue,
event_loop.clone(),
control_tube,
hub,
));
let handler: Arc<dyn EventHandler> = inner.clone();
event_loop
.add_event(
&*inner.control_tube.lock(),
EventType::Read,
Arc::downgrade(&handler),
)
.map_err(Error::AddToEventLoop)?;
*self = HostBackendDeviceProvider::Started { inner };
Ok(())
}
HostBackendDeviceProvider::Started { .. } => {
error!("Host backend provider has already started");
Err(Error::BadBackendProviderState)
}
HostBackendDeviceProvider::Failed => {
error!("Host backend provider has already failed");
Err(Error::BadBackendProviderState)
}
}
}
}
impl XhciBackendDeviceProvider for HostBackendDeviceProvider {
fn start(
&mut self,
fail_handle: Arc<dyn FailHandle>,
event_loop: Arc<EventLoop>,
hub: Arc<UsbHub>,
) -> Result<()> {
self.start_helper(fail_handle, event_loop, hub)
}
fn keep_rds(&self) -> Vec<RawDescriptor> {
match self {
HostBackendDeviceProvider::Created { control_tube } => {
vec![control_tube.lock().as_raw_descriptor()]
}
_ => {
error!(
"Trying to get keepfds when HostBackendDeviceProvider is not in created state"
);
vec![]
}
}
}
}
pub struct ProviderInner {
fail_handle: Arc<dyn FailHandle>,
job_queue: Arc<AsyncJobQueue>,
event_loop: Arc<EventLoop>,
control_tube: Mutex<Tube>,
usb_hub: Arc<UsbHub>,
devices: Mutex<HashMap<u8, HostDeviceContext>>,
}
struct HostDeviceContext {
event_handler: Arc<dyn EventHandler>,
device: Arc<Mutex<Device>>,
}
impl ProviderInner {
fn new(
fail_handle: Arc<dyn FailHandle>,
job_queue: Arc<AsyncJobQueue>,
event_loop: Arc<EventLoop>,
control_tube: Mutex<Tube>,
usb_hub: Arc<UsbHub>,
) -> ProviderInner {
ProviderInner {
fail_handle,
job_queue,
event_loop,
control_tube,
usb_hub,
devices: Mutex::new(HashMap::new()),
}
}
fn handle_attach_device(&self, usb_file: File) -> UsbControlResult {
let device = match Device::new(usb_file) {
Ok(d) => d,
Err(e) => {
error!("could not construct USB device from fd: {}", e);
return UsbControlResult::NoSuchDevice;
}
};
let arc_mutex_device = Arc::new(Mutex::new(device));
let event_handler: Arc<dyn EventHandler> = Arc::new(UsbUtilEventHandler {
device: arc_mutex_device.clone(),
});
if let Err(e) = self.event_loop.add_event(
&*arc_mutex_device.lock(),
EventType::ReadWrite,
Arc::downgrade(&event_handler),
) {
error!("failed to add USB device fd to event handler: {}", e);
return UsbControlResult::FailedToOpenDevice;
}
let device_ctx = HostDeviceContext {
event_handler,
device: arc_mutex_device.clone(),
};
if let Err(e) = arc_mutex_device.lock().reset() {
error!("failed to reset device after attach: {:?}", e);
}
let host_device = match HostDevice::new(
self.fail_handle.clone(),
self.job_queue.clone(),
arc_mutex_device,
) {
Ok(host_device) => Box::new(host_device),
Err(e) => {
error!("failed to initialize HostDevice: {}", e);
return UsbControlResult::FailedToInitHostDevice;
}
};
let port = self.usb_hub.connect_backend(host_device);
match port {
Ok(port) => {
self.devices.lock().insert(port, device_ctx);
UsbControlResult::Ok { port }
}
Err(e) => {
error!("failed to connect device to hub: {}", e);
UsbControlResult::NoAvailablePort
}
}
}
fn handle_detach_device(&self, port: u8) -> UsbControlResult {
match self.usb_hub.disconnect_port(port) {
Ok(()) => {
if let Some(device_ctx) = self.devices.lock().remove(&port) {
let _ = device_ctx.event_handler.on_event();
let device = device_ctx.device.lock();
let descriptor = device.fd();
if let Err(e) = self.event_loop.remove_event_for_descriptor(&*descriptor) {
error!(
"failed to remove poll change handler from event loop: {}",
e
);
}
}
UsbControlResult::Ok { port }
}
Err(e) => {
error!("failed to disconnect device from port {}: {}", port, e);
UsbControlResult::NoSuchDevice
}
}
}
fn handle_list_devices(&self, ports: [u8; USB_CONTROL_MAX_PORTS]) -> UsbControlResult {
let mut devices: [UsbControlAttachedDevice; USB_CONTROL_MAX_PORTS] = Default::default();
for (result_index, &port_id) in ports.iter().enumerate() {
match self.usb_hub.get_port(port_id).and_then(|p| {
p.get_backend_device()
.as_ref()
.map(|d| (d.get_vid(), d.get_pid()))
}) {
Some((vendor_id, product_id)) => {
devices[result_index] = UsbControlAttachedDevice {
port: port_id,
vendor_id,
product_id,
}
}
None => continue,
}
}
UsbControlResult::Devices(devices)
}
fn on_event_helper(&self) -> Result<()> {
let tube = self.control_tube.lock();
let cmd = tube.recv().map_err(Error::ReadControlTube)?;
let result = match cmd {
UsbControlCommand::AttachDevice { file } => self.handle_attach_device(file),
UsbControlCommand::DetachDevice { port } => self.handle_detach_device(port),
UsbControlCommand::ListDevice { ports } => self.handle_list_devices(ports),
};
tube.send(&result).map_err(Error::WriteControlTube)?;
Ok(())
}
}
impl EventHandler for ProviderInner {
fn on_event(&self) -> anyhow::Result<()> {
self.on_event_helper()
.context("host backend device provider failed")
}
}
struct UsbUtilEventHandler {
device: Arc<Mutex<Device>>,
}
impl EventHandler for UsbUtilEventHandler {
fn on_event(&self) -> anyhow::Result<()> {
self.device
.lock()
.poll_transfers()
.context("UsbUtilEventHandler poll_transfers failed")
}
}