usbvfiod 0.1.0

A vfio-user server for USB pass-through.
Documentation
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
use std::{fmt::Debug, future::Future, pin::Pin, sync::Arc, time::Duration};

use anyhow::{anyhow, Error};
use nusb::{
    transfer::{
        Buffer, Bulk, BulkOrInterrupt, ControlIn, ControlOut, ControlType, EndpointDirection,
        EndpointType, In, Interrupt, Out, Recipient, TransferError,
    },
    Endpoint, Interface, MaybeFuture,
};
use tokio::{runtime, select, sync::mpsc};
use tokio_util::sync::CancellationToken;
use tracing::{debug, warn};

use crate::device::xhci::{
    hotplug_endpoint_handle::BaseEndpointHandle,
    real_device::{RealDevice, Speed},
    real_endpoint_handle::{
        ControlRequestProcessingResult, InTrbProcessingResult, RealControlEndpointHandle,
        RealInEndpointHandle, RealOutEndpointHandle,
    },
    usbrequest::UsbRequest,
};

use super::real_endpoint_handle::OutTrbProcessingResult;

struct NusbDeviceWrapper {
    device: nusb::Device,
    interfaces: Vec<Interface>,
}

impl Debug for NusbDeviceWrapper {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // The active configuration is either cached or not available
        // for unconfigured devices. There is no I/O for this.
        f.debug_struct("NusbDeviceWrapper")
            .field("device", &self.device.active_configuration())
            .finish()
    }
}

impl TryFrom<nusb::Device> for NusbDeviceWrapper {
    type Error = Error;

    fn try_from(device: nusb::Device) -> Result<Self, Error> {
        // Claim all interfaces
        let mut interfaces = vec![];
        let desc = device.active_configuration()?;
        for interface in desc.interfaces() {
            let interface_number = interface.interface_number();
            debug!("Claiming interface {}", interface_number);
            interfaces.push(device.detach_and_claim_interface(interface_number).wait()?);
        }

        Ok(Self { device, interfaces })
    }
}

impl NusbDeviceWrapper {
    fn get_interface_number_containing_endpoint(&self, endpoint_id: u8) -> Option<usize> {
        self.interfaces.iter().position(|interface| {
            interface
                .descriptor()
                .unwrap()
                .endpoints()
                .any(|ep| ep.address() == endpoint_id)
        })
    }

    fn open_endpoint<EpType: EndpointType, Dir: EndpointDirection>(
        &self,
        endpoint_id: u8,
    ) -> Result<Endpoint<EpType, Dir>, Error> {
        let endpoint_address = endpoint_id_to_address(endpoint_id);
        let interface_num = self
            .get_interface_number_containing_endpoint(endpoint_address)
            .ok_or_else(|| anyhow!("Endpoint with id {endpoint_id} is not part of an interface"))?;
        let endpoint = self.interfaces[interface_num].endpoint(endpoint_address)?;

        Ok(endpoint)
    }
}

const fn endpoint_id_to_address(endpoint_id: u8) -> u8 {
    let endpoint_number = endpoint_id / 2;
    let is_out_endpoint = endpoint_id.is_multiple_of(2);

    match is_out_endpoint {
        true => endpoint_number,
        false => 0x80 | endpoint_number,
    }
}

#[derive(Debug)]
pub struct NusbRealDevice {
    device_wrapper: Arc<NusbDeviceWrapper>,
    async_runtime: runtime::Handle,
}

impl NusbRealDevice {
    pub fn try_new(device: nusb::Device, async_runtime: runtime::Handle) -> Result<Self, Error> {
        let device_wrapper = NusbDeviceWrapper::try_from(device)?;

        Ok(Self {
            device_wrapper: Arc::new(device_wrapper),
            async_runtime,
        })
    }
}

impl RealDevice for NusbRealDevice {
    type RCEH = ControlEndpointHandle;
    type RBIEH = NormalEndpointHandle<Bulk, In>;
    type RBOEH = NormalEndpointHandle<Bulk, Out>;
    type RIIEH = NormalEndpointHandle<Interrupt, In>;
    type RIOEH = NormalEndpointHandle<Interrupt, Out>;

    fn speed(&self) -> Option<super::real_device::Speed> {
        self.device_wrapper.device.speed().map(|speed| speed.into())
    }

    fn control_endpoint_handle(&self) -> Self::RCEH {
        ControlEndpointHandle::new(self.device_wrapper.device.clone(), &self.async_runtime)
    }

    fn bulk_in_endpoint_handle(&self, endpoint_id: u8) -> Self::RBIEH {
        NormalEndpointHandle::new(endpoint_id, self.device_wrapper.clone())
    }

    fn bulk_out_endpoint_handle(&self, endpoint_id: u8) -> Self::RBOEH {
        NormalEndpointHandle::new(endpoint_id, self.device_wrapper.clone())
    }

    fn interrupt_in_endpoint_handle(&self, endpoint_id: u8) -> Self::RIIEH {
        NormalEndpointHandle::new(endpoint_id, self.device_wrapper.clone())
    }

    fn interrupt_out_endpoint_handle(&self, endpoint_id: u8) -> Self::RIOEH {
        NormalEndpointHandle::new(endpoint_id, self.device_wrapper.clone())
    }
}

#[derive(Debug)]
pub struct ControlEndpointHandle {
    // signal worker to stop
    cancel: CancellationToken,
    request_submitter: mpsc::UnboundedSender<UsbRequest>,
    response_receiver: mpsc::UnboundedReceiver<ControlRequestProcessingResult>,
}

impl Drop for ControlEndpointHandle {
    fn drop(&mut self) {
        self.cancel.cancel();
    }
}

impl RealControlEndpointHandle for ControlEndpointHandle {
    type TrbCompletionFuture<'a> =
        Pin<Box<dyn Future<Output = anyhow::Result<ControlRequestProcessingResult>> + Send + 'a>>;

    fn submit_control_request(&mut self, request: UsbRequest) -> anyhow::Result<()> {
        self.request_submitter.send(request)?;

        Ok(())
    }

    fn next_completion(&mut self) -> Self::TrbCompletionFuture<'_> {
        Box::pin(async {
            let result = (self.response_receiver.recv().await)
                // background worker is dead and has dropped the response sender
                // maybe we want to error here instead
                .map_or(ControlRequestProcessingResult::TransactionError, |res| res);

            Ok(result)
        })
    }
}

impl BaseEndpointHandle for ControlEndpointHandle {
    type CompletionFuture<'a> = Pin<Box<dyn Future<Output = anyhow::Result<()>> + Send + 'a>>;

    fn cancel(&mut self) -> Self::CompletionFuture<'_> {
        // nothing we can do
        Box::pin(async { Ok(()) })
    }

    fn clear_halt(&mut self) -> Self::CompletionFuture<'_> {
        // nusb handles clearing halts on control endpoints by itself
        Box::pin(async { Ok(()) })
    }
}

impl ControlEndpointHandle {
    fn new(device: nusb::Device, async_runtime: &runtime::Handle) -> Self {
        let (request_submitter, request_receiver) = mpsc::unbounded_channel();
        let (response_submitter, response_receiver) = mpsc::unbounded_channel();
        let cancel = CancellationToken::new();

        async_runtime.spawn(cancellable_control_endpoint_worker(
            device,
            request_receiver,
            response_submitter,
            cancel.clone(),
        ));

        Self {
            cancel,
            request_submitter,
            response_receiver,
        }
    }
}

async fn cancellable_control_endpoint_worker(
    device: nusb::Device,
    request_receiver: mpsc::UnboundedReceiver<UsbRequest>,
    response_submitter: mpsc::UnboundedSender<ControlRequestProcessingResult>,
    cancel: CancellationToken,
) {
    select! {
        _ = control_endpoint_worker(device, request_receiver, response_submitter) => {},
        _ = cancel.cancelled() => {},
    }
}

// this function can only return with an error, but ! cannot be used in Result
async fn control_endpoint_worker(
    device: nusb::Device,
    mut request_receiver: mpsc::UnboundedReceiver<UsbRequest>,
    response_submitter: mpsc::UnboundedSender<ControlRequestProcessingResult>,
) -> anyhow::Result<()> {
    loop {
        if let Some(request) = request_receiver.recv().await {
            let (recipient, control_type) = extract_recipient_and_type(request.request_type);
            let is_out_request = request.request_type & 0x80 == 0;

            let processing_result = match is_out_request {
                true => {
                    let data = request.data.unwrap_or(Vec::new());
                    let control = ControlOut {
                        control_type,
                        recipient,
                        request: request.request,
                        value: request.value,
                        index: request.index,
                        data: &data,
                    };
                    match device
                        .control_out(control, Duration::from_millis(2000))
                        .await
                    {
                        Ok(_) => ControlRequestProcessingResult::SuccessfulControlOut,
                        Err(err) => map_error(err),
                    }
                }
                false => {
                    let control = ControlIn {
                        control_type,
                        recipient,
                        request: request.request,
                        value: request.value,
                        index: request.index,
                        length: request.length,
                    };
                    match device
                        .control_in(control, Duration::from_millis(2000))
                        .await
                    {
                        Ok(data) => ControlRequestProcessingResult::SuccessfulControlIn(data),
                        Err(err) => map_error(err),
                    }
                }
            };

            response_submitter.send(processing_result)?;
        }
    }
}

const fn map_error(error: TransferError) -> ControlRequestProcessingResult {
    match error {
        TransferError::Cancelled => ControlRequestProcessingResult::TransactionError,
        TransferError::Stall => ControlRequestProcessingResult::Stall,
        TransferError::Disconnected => ControlRequestProcessingResult::Disconnect,
        TransferError::Fault => ControlRequestProcessingResult::TransactionError,
        TransferError::InvalidArgument => ControlRequestProcessingResult::TransactionError,
        TransferError::Unknown(_) => ControlRequestProcessingResult::TransactionError,
    }
}

fn extract_recipient_and_type(request_type: u8) -> (Recipient, ControlType) {
    let recipient = match request_type & 0x1f {
        0 => Recipient::Device,
        1 => Recipient::Interface,
        2 => Recipient::Endpoint,
        val => panic!("invalid recipient {val}"),
    };
    let control_type = match (request_type >> 5) & 0x3 {
        0 => ControlType::Standard,
        1 => ControlType::Class,
        2 => ControlType::Vendor,
        val => panic!("invalid type {val}"),
    };
    (recipient, control_type)
}

pub struct NormalEndpointHandle<EpType: EndpointType + 'static, Dir: EndpointDirection + 'static> {
    id: u8,
    device_wrapper: Arc<NusbDeviceWrapper>,
    endpoint: Option<Endpoint<EpType, Dir>>,
}

impl<EpType: EndpointType, Dir: EndpointDirection> NormalEndpointHandle<EpType, Dir> {
    const fn new(id: u8, device_wrapper: Arc<NusbDeviceWrapper>) -> Self {
        Self {
            id,
            device_wrapper,
            endpoint: None,
        }
    }
}

impl<EpType: EndpointType, Dir: EndpointDirection> Debug for NormalEndpointHandle<EpType, Dir> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("lol")
            //.field("device", &self.device.active_configuration())
            .finish()
    }
}

impl<EpType: EndpointType, Dir: EndpointDirection> NormalEndpointHandle<EpType, Dir> {
    fn endpoint(&mut self) -> &mut Endpoint<EpType, Dir> {
        match self.endpoint {
            Some(ref mut endpoint) => endpoint,
            None => {
                let ep: Endpoint<EpType, Dir> = self.device_wrapper.open_endpoint(self.id).expect("Failed to open endpoint on nusb device. We could handle this error and always return transaction errors. Panic is fine for now.");
                self.endpoint = Some(ep);
                self.endpoint.as_mut().unwrap()
            }
        }
    }
}

impl<EpType: BulkOrInterrupt> RealOutEndpointHandle for NormalEndpointHandle<EpType, Out> {
    type TrbCompletionFuture<'a> =
        Pin<Box<dyn Future<Output = anyhow::Result<OutTrbProcessingResult>> + Send + 'a>>;

    fn submit(&mut self, data: Vec<u8>) -> anyhow::Result<()> {
        let buf = Buffer::from(data);
        self.endpoint().submit(buf);

        Ok(())
    }

    fn next_completion(&mut self) -> Self::TrbCompletionFuture<'_> {
        Box::pin(async {
            let completion = self.endpoint().next_complete().await;
            let result = match completion.status {
                Err(err) => match err {
                    TransferError::Cancelled => OutTrbProcessingResult::TransactionError,
                    TransferError::Stall => OutTrbProcessingResult::Stall,
                    TransferError::Disconnected => OutTrbProcessingResult::Disconnect,
                    TransferError::Fault => OutTrbProcessingResult::TransactionError,
                    TransferError::InvalidArgument => OutTrbProcessingResult::TransactionError,
                    TransferError::Unknown(_) => OutTrbProcessingResult::TransactionError,
                },
                Ok(_) => OutTrbProcessingResult::Success,
            };

            Ok(result)
        })
    }
}

impl<EpType: BulkOrInterrupt> RealInEndpointHandle for NormalEndpointHandle<EpType, In> {
    type TrbCompletionFuture<'a> =
        Pin<Box<dyn Future<Output = anyhow::Result<InTrbProcessingResult>> + Send + 'a>>;

    fn submit(&mut self, len: usize) -> anyhow::Result<()> {
        let endpoint = self.endpoint();
        let request_len = determine_buffer_size(len, endpoint.max_packet_size());
        let buf = Buffer::new(request_len);
        endpoint.submit(buf);

        Ok(())
    }

    fn next_completion(&mut self) -> Self::TrbCompletionFuture<'_> {
        Box::pin(async {
            let completion = self.endpoint().next_complete().await.into_result();
            let result = match completion {
                Ok(buf) => InTrbProcessingResult::Success(buf.into_vec()),
                Err(err) => match err {
                    TransferError::Cancelled => InTrbProcessingResult::TransactionError,
                    TransferError::Stall => InTrbProcessingResult::Stall,
                    TransferError::Disconnected => InTrbProcessingResult::Disconnect,
                    TransferError::Fault => InTrbProcessingResult::TransactionError,
                    TransferError::InvalidArgument => InTrbProcessingResult::TransactionError,
                    TransferError::Unknown(_) => InTrbProcessingResult::TransactionError,
                },
            };

            Ok(result)
        })
    }
}

impl<EpType: BulkOrInterrupt, Dir: EndpointDirection> BaseEndpointHandle
    for NormalEndpointHandle<EpType, Dir>
{
    type CompletionFuture<'a> = Pin<Box<dyn Future<Output = anyhow::Result<()>> + Send + 'a>>;

    fn cancel(&mut self) -> Self::CompletionFuture<'_> {
        Box::pin(async {
            let ep = self.endpoint();
            ep.cancel_all();

            // have to consume all cancelled TRBs (should be 0 or 1)
            if ep.pending() > 1 {
                warn!("while cancelling: saw more than one pending TRB");
            }
            while ep.pending() > 0 {
                let _ = ep.next_complete().await;
            }

            Ok(())
        })
    }

    fn clear_halt(&mut self) -> Self::CompletionFuture<'_> {
        Box::pin(async {
            self.endpoint().clear_halt().await?;
            Ok(())
        })
    }
}

const fn determine_buffer_size(guest_transfer_length: usize, max_packet_size: usize) -> usize {
    if guest_transfer_length <= max_packet_size {
        max_packet_size
    } else {
        guest_transfer_length.div_ceil(max_packet_size) * max_packet_size
    }
}

impl From<nusb::Speed> for Speed {
    fn from(value: nusb::Speed) -> Self {
        match value {
            nusb::Speed::Low => Self::Low,
            nusb::Speed::Full => Self::Full,
            nusb::Speed::High => Self::High,
            nusb::Speed::Super => Self::Super,
            nusb::Speed::SuperPlus => Self::SuperPlus,
            _ => todo!("new USB speed was added to non-exhaustive enum"),
        }
    }
}