viva_u3v/usb.rs
1//! USB transfer abstraction for testability.
2//!
3//! [`UsbTransfer`] decouples all U3V protocol logic from the USB library,
4//! allowing the control channel, streaming, and bootstrap parsing to be
5//! tested with [`MockUsbTransfer`] and `viva-fake-u3v` — no USB hardware
6//! required. [`BulkIn`] is how a stream keeps several transfers in flight
7//! (backlog UV-01): a transport that can queue them, as `nusb` does,
8//! implements it; any other gets one read at a time through
9//! [`UsbTransfer::bulk_read`].
10
11use std::collections::VecDeque;
12use std::sync::Arc;
13use std::time::{Duration, Instant};
14
15use crate::U3vError;
16use crate::bootstrap::UsbSpeed;
17
18/// Abstraction over a claimed USB device for bulk endpoint I/O.
19///
20/// Implementations must be safe to share across threads. The control and
21/// stream channels use different endpoints, so a single `UsbTransfer` can
22/// serve both concurrently (with internal synchronization if needed).
23pub trait UsbTransfer: Send + Sync {
24 /// Write `data` to the bulk OUT `endpoint`. Returns bytes written.
25 fn bulk_write(&self, endpoint: u8, data: &[u8], timeout: Duration) -> Result<usize, U3vError>;
26
27 /// Read up to `buf.len()` bytes from the bulk IN `endpoint`.
28 /// Returns the number of bytes actually read.
29 fn bulk_read(&self, endpoint: u8, buf: &mut [u8], timeout: Duration)
30 -> Result<usize, U3vError>;
31
32 /// Reads on the bulk IN `endpoint` that can be queued ahead of the
33 /// device, as a stream needs them.
34 ///
35 /// The default reads one transfer at a time through
36 /// [`bulk_read`](Self::bulk_read), when the next completion is asked for:
37 /// correct, but with nothing queued while the host is busy elsewhere. A
38 /// transport that can keep transfers in flight overrides it.
39 fn bulk_in(self: &Arc<Self>, endpoint: u8) -> Result<Box<dyn BulkIn>, U3vError>
40 where
41 Self: Sized + 'static,
42 {
43 Ok(Box::new(Unqueued {
44 transport: Arc::clone(self),
45 endpoint,
46 requested: VecDeque::new(),
47 cancelled: 0,
48 }))
49 }
50
51 /// The largest packet the endpoint carries, from its descriptor; `None`
52 /// when unknown. Every IN transfer a stream asks for is a multiple of
53 /// it, so that a packet never straddles two transfers.
54 fn max_packet_size(&self, _endpoint: u8) -> Option<usize> {
55 None
56 }
57
58 /// The speed the host's USB stack reports the device runs at; `None`
59 /// when this transport cannot tell.
60 fn link_speed(&self) -> Option<UsbSpeed> {
61 None
62 }
63
64 /// Whether the operating system still lists the device, asked after a
65 /// transfer failed in a way that does not say whether it is gone;
66 /// `None` when this transport cannot tell. One look, no waiting.
67 fn is_present(&self) -> Option<bool> {
68 None
69 }
70}
71
72/// How long a device whose transfer failed gets to leave the operating
73/// system's list before it counts as still attached. On macOS the transfer
74/// in flight fails before the unplugged device leaves the registry; an
75/// mvBlueFOX3-2004G's next control transfer failed 3 ms later.
76pub(crate) const GONE_GRACE: Duration = Duration::from_millis(500);
77
78/// How often the list is looked at within [`GONE_GRACE`].
79const GONE_POLL: Duration = Duration::from_millis(20);
80
81/// `error`, or [`U3vError::Disconnected`] when it is one a missing device
82/// also causes ([`U3vError::may_mean_gone`]) and `present` says the
83/// operating system no longer lists the device — now, or within `grace`
84/// (backlog UV-03). A transport that cannot tell leaves `error` as it is.
85pub(crate) fn unless_gone(
86 error: U3vError,
87 present: impl Fn() -> Option<bool>,
88 grace: Duration,
89) -> U3vError {
90 if !error.may_mean_gone() {
91 return error;
92 }
93 let deadline = Instant::now() + grace;
94 loop {
95 match present() {
96 Some(false) => {
97 tracing::debug!(%error, "the device is no longer listed: it is gone");
98 return U3vError::Disconnected;
99 }
100 Some(true) if Instant::now() < deadline => std::thread::sleep(GONE_POLL),
101 Some(true) | None => return error,
102 }
103 }
104}
105
106/// A bulk IN endpoint's queue of transfers: submitted in order, completed in
107/// order (USB bulk transfers on one endpoint complete in the order they were
108/// queued).
109pub trait BulkIn: Send {
110 /// Queue a read of `len` bytes. It completes when `len` bytes have
111 /// arrived, or earlier at a short packet.
112 fn submit(&mut self, len: usize);
113
114 /// Transfers queued and not yet returned by [`wait_next`](Self::wait_next).
115 fn pending(&self) -> usize;
116
117 /// The oldest queued transfer once it completes, waiting up to
118 /// `timeout`; `None` if none completed in time — it stays queued — or if
119 /// nothing is queued.
120 fn wait_next(&mut self, timeout: Duration) -> Option<Completion>;
121
122 /// Ask every queued transfer to end. Each still comes back from
123 /// [`wait_next`](Self::wait_next), with whatever bytes arrived before it
124 /// ended and a [`U3vError::Cancelled`] status unless it completed first.
125 fn cancel_all(&mut self);
126
127 /// Reset the endpoint, with nothing queued: halt it and clear the halt,
128 /// so the device drops whatever it had queued on it and both sides
129 /// restart the endpoint's data toggle. A stream does this before it is
130 /// enabled, as aravis does (`arv_uv_device_reset_stream_endpoint`), and
131 /// to recover from a stall.
132 fn reset(&mut self) -> Result<(), U3vError>;
133
134 /// [`UsbTransfer::is_present`] for the device this endpoint is on.
135 fn is_present(&self) -> Option<bool> {
136 None
137 }
138}
139
140/// A transfer [`BulkIn::wait_next`] hands back.
141#[derive(Debug)]
142#[non_exhaustive]
143pub struct Completion {
144 /// The bytes that arrived, as many as were received: a cancelled or
145 /// failed transfer may still carry some.
146 pub data: Vec<u8>,
147 /// How the transfer ended.
148 pub status: Result<(), U3vError>,
149}
150
151impl Completion {
152 /// A transfer that ended with `status`, carrying `data`.
153 pub fn new(data: Vec<u8>, status: Result<(), U3vError>) -> Self {
154 Self { data, status }
155 }
156}
157
158/// [`UsbTransfer::bulk_in`]'s default: each queued read is performed, one at
159/// a time, when its completion is asked for.
160struct Unqueued<T: UsbTransfer> {
161 transport: Arc<T>,
162 endpoint: u8,
163 requested: VecDeque<usize>,
164 /// How many of the oldest requests were cancelled before being read.
165 cancelled: usize,
166}
167
168impl<T: UsbTransfer + 'static> BulkIn for Unqueued<T> {
169 fn submit(&mut self, len: usize) {
170 self.requested.push_back(len);
171 }
172
173 fn pending(&self) -> usize {
174 self.requested.len()
175 }
176
177 fn wait_next(&mut self, timeout: Duration) -> Option<Completion> {
178 let len = *self.requested.front()?;
179 if self.cancelled > 0 {
180 self.cancelled -= 1;
181 self.requested.pop_front();
182 return Some(Completion::new(Vec::new(), Err(U3vError::Cancelled)));
183 }
184 let mut data = vec![0; len];
185 match self.transport.bulk_read(self.endpoint, &mut data, timeout) {
186 // Nothing within the wait: the request stays queued.
187 Err(U3vError::Timeout) => None,
188 Ok(n) => {
189 self.requested.pop_front();
190 data.truncate(n);
191 Some(Completion::new(data, Ok(())))
192 }
193 Err(error) => {
194 self.requested.pop_front();
195 Some(Completion::new(Vec::new(), Err(error)))
196 }
197 }
198 }
199
200 fn cancel_all(&mut self) {
201 self.cancelled = self.requested.len();
202 }
203
204 fn reset(&mut self) -> Result<(), U3vError> {
205 // Nothing is queued on the device on our behalf between reads.
206 Ok(())
207 }
208
209 fn is_present(&self) -> Option<bool> {
210 self.transport.is_present()
211 }
212}
213
214// ---------------------------------------------------------------------------
215// Mock implementation for testing
216// ---------------------------------------------------------------------------
217
218use std::collections::HashMap;
219use std::sync::Mutex;
220
221/// What one endpoint of [`MockUsbTransfer`] answers, in order.
222type ReadQueue = VecDeque<Result<Vec<u8>, U3vError>>;
223
224/// In-memory mock of [`UsbTransfer`] for unit tests.
225///
226/// Pre-load expected read responses per endpoint, then execute protocol
227/// logic. After the test, inspect captured writes to verify correctness.
228///
229/// # Thread safety
230///
231/// State lives behind a `Mutex`, so the `Send + Sync` that [`UsbTransfer`]
232/// requires is derived rather than asserted. The mock used to hold `RefCell`
233/// and claim the bounds with `unsafe impl`, which was unsound: `RefCell`'s
234/// borrow flag is not atomic, so two threads sharing one mock could hold
235/// overlapping `borrow_mut()`s and alias the same `&mut`.
236pub struct MockUsbTransfer {
237 /// Queued read responses per endpoint address.
238 reads: Mutex<HashMap<u8, ReadQueue>>,
239 /// Captured write payloads per endpoint address.
240 writes: Mutex<HashMap<u8, Vec<Vec<u8>>>>,
241 /// What [`UsbTransfer::is_present`] answers.
242 present: Mutex<Option<bool>>,
243}
244
245impl MockUsbTransfer {
246 /// Create an empty mock with no pre-loaded responses.
247 pub fn new() -> Self {
248 Self {
249 reads: Mutex::new(HashMap::new()),
250 writes: Mutex::new(HashMap::new()),
251 present: Mutex::new(None),
252 }
253 }
254
255 /// What [`UsbTransfer::is_present`] answers from now on: `Some(false)`
256 /// for a device the operating system no longer lists. `None`, cannot
257 /// tell, until set.
258 pub fn set_present(&self, present: Option<bool>) {
259 *self.present.lock().expect("mock presence poisoned") = present;
260 }
261
262 /// Enqueue a response that will be returned by the next `bulk_read`
263 /// on the given `endpoint`.
264 pub fn enqueue_read(&self, endpoint: u8, data: Vec<u8>) {
265 self.enqueue(endpoint, Ok(data));
266 }
267
268 /// Enqueue an error the next `bulk_read` on `endpoint` fails with.
269 pub fn enqueue_error(&self, endpoint: u8, error: U3vError) {
270 self.enqueue(endpoint, Err(error));
271 }
272
273 fn enqueue(&self, endpoint: u8, read: Result<Vec<u8>, U3vError>) {
274 self.reads
275 .lock()
276 .expect("mock read queue poisoned")
277 .entry(endpoint)
278 .or_default()
279 .push_back(read);
280 }
281
282 /// Return all captured write payloads for the given `endpoint`.
283 pub fn take_writes(&self, endpoint: u8) -> Vec<Vec<u8>> {
284 self.writes
285 .lock()
286 .expect("mock write log poisoned")
287 .remove(&endpoint)
288 .unwrap_or_default()
289 }
290}
291
292impl Default for MockUsbTransfer {
293 fn default() -> Self {
294 Self::new()
295 }
296}
297
298impl UsbTransfer for MockUsbTransfer {
299 fn bulk_write(&self, endpoint: u8, data: &[u8], _timeout: Duration) -> Result<usize, U3vError> {
300 let len = data.len();
301 self.writes
302 .lock()
303 .expect("mock write log poisoned")
304 .entry(endpoint)
305 .or_default()
306 .push(data.to_vec());
307 Ok(len)
308 }
309
310 fn bulk_read(
311 &self,
312 endpoint: u8,
313 buf: &mut [u8],
314 _timeout: Duration,
315 ) -> Result<usize, U3vError> {
316 let mut reads = self.reads.lock().expect("mock read queue poisoned");
317 // Nothing queued is a device that does not answer: the host times
318 // out.
319 let data = reads
320 .get_mut(&endpoint)
321 .and_then(VecDeque::pop_front)
322 .ok_or(U3vError::Timeout)??;
323 let n = data.len().min(buf.len());
324 buf[..n].copy_from_slice(&data[..n]);
325 Ok(n)
326 }
327
328 fn is_present(&self) -> Option<bool> {
329 *self.present.lock().expect("mock presence poisoned")
330 }
331}
332
333#[cfg(test)]
334mod tests {
335 use super::*;
336
337 #[test]
338 fn mock_write_then_read() {
339 let mock = MockUsbTransfer::new();
340 let ep_out = 0x01;
341 let ep_in = 0x81;
342
343 // Write some data
344 let written = mock
345 .bulk_write(ep_out, &[1, 2, 3], Duration::from_millis(100))
346 .unwrap();
347 assert_eq!(written, 3);
348
349 // Enqueue a read response and read it back
350 mock.enqueue_read(ep_in, vec![4, 5, 6, 7]);
351 let mut buf = [0u8; 8];
352 let n = mock
353 .bulk_read(ep_in, &mut buf, Duration::from_millis(100))
354 .unwrap();
355 assert_eq!(n, 4);
356 assert_eq!(&buf[..4], &[4, 5, 6, 7]);
357
358 // Verify captured writes
359 let writes = mock.take_writes(ep_out);
360 assert_eq!(writes.len(), 1);
361 assert_eq!(writes[0], &[1, 2, 3]);
362 }
363
364 #[test]
365 fn mock_read_exhausted_returns_error() {
366 let mock = MockUsbTransfer::new();
367 let mut buf = [0u8; 4];
368 let err = mock
369 .bulk_read(0x81, &mut buf, Duration::from_millis(100))
370 .unwrap_err();
371 assert!(matches!(err, U3vError::Timeout));
372 }
373
374 /// The default queue reads in submission order, keeps a request queued
375 /// across a timeout, and hands back cancelled requests as such.
376 #[test]
377 fn the_default_queue_reads_one_request_at_a_time() {
378 let mock = Arc::new(MockUsbTransfer::new());
379 let mut queue = mock.bulk_in(0x82).unwrap();
380 queue.submit(8);
381 queue.submit(8);
382 assert_eq!(queue.pending(), 2);
383 assert!(queue.wait_next(Duration::from_millis(1)).is_none());
384 assert_eq!(queue.pending(), 2, "a timeout keeps the request");
385
386 mock.enqueue_read(0x82, vec![1, 2, 3]);
387 let first = queue.wait_next(Duration::from_millis(1)).expect("done");
388 assert_eq!(first.data, [1, 2, 3]);
389 assert!(first.status.is_ok());
390
391 mock.enqueue_error(0x82, U3vError::Stalled { endpoint: 0x82 });
392 let failed = queue.wait_next(Duration::from_millis(1)).expect("done");
393 assert!(matches!(
394 failed.status,
395 Err(U3vError::Stalled { endpoint: 0x82 })
396 ));
397
398 queue.submit(4);
399 queue.cancel_all();
400 mock.enqueue_read(0x82, vec![9; 4]);
401 let cancelled = queue.wait_next(Duration::from_millis(1)).expect("done");
402 assert!(matches!(cancelled.status, Err(U3vError::Cancelled)));
403 assert_eq!(queue.pending(), 0);
404 assert!(queue.wait_next(Duration::from_millis(1)).is_none());
405 }
406}