Debian Codegraph @

src/transfer/queue.rs

raw symbols SCIP
1 use std::{
2 collections::VecDeque,
3 future::{poll_fn, Future},
4 marker::PhantomData,
5 sync::Arc,
6 task::{Context, Poll},
7 };
8
9 use crate::{platform, Error};
10
11 use super::{Completion, EndpointType, PlatformSubmit, TransferHandle, TransferRequest};
12
13 /// Manages a stream of transfers on an endpoint.
14 ///
15 /// A `Queue` optimizes a common pattern when streaming data to or from a USB
16 /// endpoint: To maximize throughput and minimize latency, the host controller
17 /// needs to attempt a transfer in every possible frame. That requires always
18 /// having a transfer request pending with the kernel by submitting multiple
19 /// transfer requests and re-submitting them as they complete.
20 ///
21 /// Use the methods on [`Interface`][`crate::Interface`] to obtain a `Queue`.
22 ///
23 /// When the `Queue` is dropped, all pending transfers are cancelled.
24 ///
25 /// ### Why use a `Queue` instead of submitting multiple transfers individually with the methods on [`Interface`][`crate::Interface`]?
26 ///
27 /// * Individual transfers give you individual `Future`s, which you then have
28 /// to keep track of and poll using something like `FuturesUnordered`.
29 /// * A `Queue` provides better cancellation semantics than `Future`'s
30 /// cancel-on-drop.
31 /// * After dropping a [`TransferFuture`][super::TransferFuture], you lose
32 /// the ability to get the status of the cancelled transfer and see if it
33 /// may have been partially or fully completed.
34 /// * When cancelling multiple transfers, it's important to do so in reverse
35 /// order so that subsequent pending transfers can't end up executing.
36 /// When managing a collection of `TransferFuture`s it's tricky to
37 /// guarantee drop order, while `Queue` always cancels its contained
38 /// transfers in reverse order.
39 /// * The `TransferFuture` methods on `Interface` are not [cancel-safe],
40 /// meaning they cannot be used in `select!{}` or similar patterns,
41 /// because dropping the Future has side effects and can lose data. The
42 /// Future returned from [`Queue::next_complete`] is cancel-safe because
43 /// it merely waits for completion, while the `Queue` owns the pending
44 /// transfers.
45 /// * A queue caches the internal transfer data structures of the last
46 /// completed transfer, meaning that if you re-use the data buffer there is
47 /// no memory allocation involved in continued streaming.
48 ///
49 /// [cancel-safe]: https://docs.rs/tokio/latest/tokio/macro.select.html#cancellation-safety
50 /// ### Example (read from an endpoint)
51 ///
52 /// ```no_run
53 /// use futures_lite::future::block_on;
54 /// use nusb::transfer::RequestBuffer;
55 /// # let di = nusb::list_devices().unwrap().next().unwrap();
56 /// # let device = di.open().unwrap();
57 /// # let interface = device.claim_interface(0).unwrap();
58 /// # fn handle_data(_: &[u8]) {}
59 /// let mut queue = interface.bulk_in_queue(0x81);
60 ///
61 /// let n_transfers = 8;
62 /// let transfer_size = 256;
63 ///
64 /// while queue.pending() < n_transfers {
65 /// queue.submit(RequestBuffer::new(transfer_size));
66 /// }
67 ///
68 /// loop {
69 /// let completion = block_on(queue.next_complete());
70 /// handle_data(&completion.data); // your function
71 ///
72 /// if completion.status.is_err() {
73 /// break;
74 /// }
75 ///
76 /// queue.submit(RequestBuffer::reuse(completion.data, transfer_size))
77 /// }
78 /// ```
79 ///
80 /// ### Example (write to an endpoint)
81 /// ```no_run
82 /// use std::mem;
83 /// use futures_lite::future::block_on;
84 /// # let di = nusb::list_devices().unwrap().next().unwrap();
85 /// # let device = di.open().unwrap();
86 /// # let interface = device.claim_interface(0).unwrap();
87 /// # fn fill_data(_: &mut Vec<u8>) {}
88 /// # fn data_confirmed_sent(_: usize) {}
89 /// let mut queue = interface.bulk_out_queue(0x02);
90 ///
91 /// let n_transfers = 8;
92 ///
93 /// let mut next_buf = Vec::new();
94 ///
95 /// loop {
96 /// while queue.pending() < n_transfers {
97 /// let mut buf = mem::replace(&mut next_buf, Vec::new());
98 /// fill_data(&mut buf); // your function
99 /// queue.submit(buf);
100 /// }
101 ///
102 /// let completion = block_on(queue.next_complete());
103 /// data_confirmed_sent(completion.data.actual_length()); // your function
104 /// next_buf = completion.data.reuse();
105
106 /// if completion.status.is_err() {
107 /// break;
108 /// }
109 /// }
110 /// ```
111 pub struct Queue<R: TransferRequest> {
112 interface: Arc<platform::Interface>,
113 endpoint: u8,
114 endpoint_type: EndpointType,
115
116 /// A queue of pending transfers, expected to complete in order
117 pending: VecDeque<TransferHandle<platform::TransferData>>,
118
119 /// An idle transfer that recently completed for re-use.
120 cached: Option<TransferHandle<platform::TransferData>>,
121
122 bufs: PhantomData<R>,
123 }
124
125 impl<R> Queue<R>
126 where
127 R: TransferRequest + Send + Sync,
128 platform::TransferData: PlatformSubmit<R>,
129 {
130 pub(crate) fn new(
131 interface: Arc<platform::Interface>,
132 endpoint: u8,
133 endpoint_type: EndpointType,
134 ) -> Queue<R> {
135 Queue {
136 interface,
137 endpoint,
138 endpoint_type,
139 pending: VecDeque::new(),
140 cached: None,
141 bufs: PhantomData,
142 }
143 }
144
145 /// Submit a new transfer on the endpoint.
146 ///
147 /// For an `IN` endpoint, pass a [`RequestBuffer`][`super::RequestBuffer`].\
148 /// For an `OUT` endpoint, pass a [`Vec<u8>`].
149 pub fn submit(&mut self, data: R) {
150 let mut transfer = self.cached.take().unwrap_or_else(|| {
151 self.interface
152 .make_transfer(self.endpoint, self.endpoint_type)
153 });
154 transfer.submit(data);
155 self.pending.push_back(transfer);
156 }
157
158 /// Return a `Future` that waits for the next pending transfer to complete, and yields its
159 /// buffer and status.
160 ///
161 /// For an `IN` endpoint, the completion contains a [`Vec<u8>`].\
162 /// For an `OUT` endpoint, the completion contains a [`ResponseBuffer`][`super::ResponseBuffer`].
163 ///
164 /// This future is cancel-safe: it can be cancelled and re-created without
165 /// side effects, enabling its use in `select!{}` or similar.
166 ///
167 /// Panics if there are no transfers pending.
168 pub fn next_complete<'a>(
169 &'a mut self,
170 ) -> impl Future<Output = Completion<R::Response>> + Unpin + Send + Sync + 'a {
171 poll_fn(|cx| self.poll_next(cx))
172 }
173
174 /// Get the next pending transfer if one has completed, or register the
175 /// current task for wakeup when the next transfer completes.
176 ///
177 /// For an `IN` endpoint, the completion contains a [`Vec<u8>`].\
178 /// For an `OUT` endpoint, the completion contains a
179 /// [`ResponseBuffer`][`super::ResponseBuffer`].
180 ///
181 /// Panics if there are no transfers pending.
182 pub fn poll_next(&mut self, cx: &mut Context) -> Poll<Completion<R::Response>> {
183 let res = self
184 .pending
185 .front_mut()
186 .expect("queue should have pending transfers when calling next_complete")
187 .poll_completion::<R>(cx);
188 if res.is_ready() {
189 self.cached = self.pending.pop_front();
190 }
191 res
192 }
193
194 /// Get the number of transfers that have been submitted with `submit` that
195 /// have not yet been returned from `next_complete`.
196 pub fn pending(&self) -> usize {
197 self.pending.len()
198 }
199
200 /// Request cancellation of all pending transfers.
201 ///
202 /// The transfers will still be returned from subsequent calls to
203 /// `next_complete` so you can tell which were completed,
204 /// partially-completed, or cancelled.
205 pub fn cancel_all(&mut self) {
206 // Cancel transfers in reverse order to ensure subsequent transfers
207 // can't complete out of order while we're going through them.
208 for transfer in self.pending.iter_mut().rev() {
209 transfer.cancel();
210 }
211 }
212
213 /// Clear the endpoint's halt / stall condition.
214 ///
215 /// Sends a `CLEAR_FEATURE` `ENDPOINT_HALT` control transfer to tell the
216 /// device to reset the endpoint's data toggle and clear the halt / stall
217 /// condition, and resets the host-side data toggle.
218 ///
219 /// Use this after receiving
220 /// [`TransferError::Stall`][crate::transfer::TransferError::Stall] to clear
221 /// the error and resume use of the endpoint.
222 ///
223 /// This should not be called when transfers are pending on the endpoint.
224 pub fn clear_halt(&mut self) -> Result<(), Error> {
225 self.interface.clear_halt(self.endpoint)
226 }
227 }
228
229 impl<R: TransferRequest> Drop for Queue<R> {
230 fn drop(&mut self) {
231 // Cancel transfers in reverse order to ensure subsequent transfers
232 // can't complete out of order while we're going through them.
233 self.pending.drain(..).rev().for_each(drop)
234 }
235 }