Skip to main content

virtio_accel_shared_queue/
device.rs

1//! The device's half: chains taken from the available ring, and used.
2
3use core::borrow::Borrow;
4use core::fmt;
5use core::sync::atomic::{AtomicU64, Ordering, fence};
6
7use virtio_accel_transport::{
8    ByteAccessError, ChainError, ChainId, ChainIo, ChainIoResult, ChainRegion, DeviceChain,
9    DeviceQueue, MalformedChain, NotificationHint, NotificationRecheck, QueueConfigError,
10    QueueControl, QueueEpoch, QueueError, QueuePort, QueueSize, QueueState, ReadableBytes,
11    UsedLength, WritableBytes, validate_chain_layout,
12};
13
14use crate::layout::{
15    AVAILABLE_ENTRY, DESCRIPTOR_BYTES, RING_FLAGS, RING_HEADER, RING_INDEX, RingAddresses,
16    USED_ENTRY, VIRTQ_AVAIL_F_NO_INTERRUPT, VIRTQ_DESC_F_INDIRECT, VIRTQ_DESC_F_NEXT,
17    VIRTQ_DESC_F_WRITE, VIRTQ_USED_F_NO_NOTIFY, each_span, fields,
18};
19use crate::memory::{Access, MemoryFault, SharedMemory};
20
21/// Why the device's half could not go on. Each is the driver's doing, and
22/// none is one chain's: a device that sees one stops serving the queue and
23/// asks for a reset.
24#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25pub enum DeviceRingError {
26    /// A part of the queue is not where the layout allows: misaligned,
27    /// overlapping another, or outside memory the device may reach.
28    Layout,
29    /// The queue was made ready smaller than the longest chain it must hold.
30    ChainLimitExceedsQueue,
31    /// The queue cannot be reconfigured while it is ready.
32    Busy,
33    /// The available index is further ahead than the queue is long.
34    AvailableIndex,
35    /// A head was published that the device already holds.
36    HeadInFlight,
37    /// The memory stopped answering for a ring the queue validated.
38    Memory(MemoryFault),
39}
40
41impl From<MemoryFault> for QueueError<DeviceRingError> {
42    fn from(fault: MemoryFault) -> Self {
43        Self::Transport(DeviceRingError::Memory(fault))
44    }
45}
46
47/// One descriptor's bytes, snapshotted when its chain was taken.
48#[derive(Clone, Copy, Debug, Default)]
49struct Span {
50    at: u64,
51    len: u32,
52}
53
54/// A chain's spans in one direction, as one run of bytes.
55#[derive(Clone, Debug)]
56struct Port<M, E, const R: usize> {
57    memory: M,
58    spans: [Span; R],
59    count: u16,
60    len: u64,
61    epoch: QueueEpoch,
62    current: E,
63}
64
65impl<M: SharedMemory, E: Borrow<AtomicU64>, const R: usize> Port<M, E, R> {
66    fn each(
67        &self,
68        offset: u64,
69        len: usize,
70        visit: impl FnMut(u64, usize, usize) -> Result<(), MemoryFault>,
71    ) -> Result<(), ByteAccessError> {
72        if self.current.borrow().load(Ordering::Acquire) != self.epoch.get() {
73            return Err(ByteAccessError::Reset);
74        }
75        match offset.checked_add(len as u64) {
76            Some(end) if end <= self.len => {}
77            _ => return Err(ByteAccessError::OutOfBounds),
78        }
79        let spans = self.spans[..usize::from(self.count)]
80            .iter()
81            .map(|span| (span.at, span.len));
82        each_span(spans, offset, len, visit).map_err(|_| ByteAccessError::Access)
83    }
84
85    fn mapped(&self, access: Access) -> bool {
86        self.spans[..usize::from(self.count)]
87            .iter()
88            .all(|span| self.memory.admits(span.at, u64::from(span.len), access))
89    }
90}
91
92/// The bytes a chain gives the device to read.
93#[derive(Debug)]
94pub struct RingSource<M, E, const R: usize>(Port<M, E, R>);
95
96impl<M, E, const R: usize> ReadableBytes for RingSource<M, E, R>
97where
98    M: SharedMemory + fmt::Debug,
99    E: Borrow<AtomicU64> + fmt::Debug,
100{
101    fn len(&self) -> u64 {
102        self.0.len
103    }
104
105    fn read_at(&self, offset: u64, target: &mut [u8]) -> Result<(), ByteAccessError> {
106        let memory = &self.0.memory;
107        let len = target.len();
108        self.0.each(offset, len, |at, from, count| {
109            memory.read(at, &mut target[from..from + count])
110        })
111    }
112}
113
114/// The bytes a chain gives the device to write.
115#[derive(Debug)]
116pub struct RingSink<M, E, const R: usize>(Port<M, E, R>);
117
118impl<M, E, const R: usize> WritableBytes for RingSink<M, E, R>
119where
120    M: SharedMemory + fmt::Debug,
121    E: Borrow<AtomicU64> + fmt::Debug,
122{
123    fn len(&self) -> u64 {
124        self.0.len
125    }
126
127    fn write_at(&mut self, offset: u64, source: &[u8]) -> Result<(), ByteAccessError> {
128        let memory = &self.0.memory;
129        self.0.each(offset, source.len(), |at, from, count| {
130            memory.write(at, &source[from..from + count])
131        })
132    }
133}
134
135/// One chain the device took from the available ring and has not yet used.
136/// Not `Clone`: [`DeviceQueue::complete`] consumes it, so a chain is used
137/// once.
138#[derive(Debug)]
139pub struct DeviceRingChain<M, E, const R: usize> {
140    id: ChainId,
141    head: u16,
142    regions: [ChainRegion; R],
143    count: u16,
144    malformed: Option<MalformedChain>,
145    request: RingSource<M, E, R>,
146    response: RingSink<M, E, R>,
147}
148
149impl<M, E, const R: usize> DeviceChain for DeviceRingChain<M, E, R>
150where
151    M: SharedMemory + fmt::Debug,
152    E: Borrow<AtomicU64> + fmt::Debug,
153{
154    type Request = RingSource<M, E, R>;
155    type Response = RingSink<M, E, R>;
156    type Error = DeviceRingError;
157
158    fn id(&self) -> ChainId {
159        self.id
160    }
161
162    fn io(&mut self) -> ChainIoResult<'_, Self::Request, Self::Response, Self::Error> {
163        let current = self.request.0.current.borrow().load(Ordering::Acquire);
164        if current != self.id.epoch().get() {
165            return Err(ChainError::ResetRace {
166                chain: self.id.epoch(),
167                // An epoch is never zero: it starts at one and only grows.
168                current: QueueEpoch::new(current).unwrap_or(QueueEpoch::INITIAL),
169            });
170        }
171        if let Some(malformed) = self.malformed {
172            return Err(ChainError::Malformed(malformed));
173        }
174        Ok(ChainIo::new(
175            &self.regions[..usize::from(self.count)],
176            &self.request,
177            &mut self.response,
178        ))
179    }
180}
181
182/// The device's half of one split virtqueue in shared memory.
183///
184/// `N` bounds the queue's size and `R` a chain's descriptors; both are
185/// storage carried inline, so the queue allocates nothing. `E` is the cell
186/// the queue and every chain it hands out share, so that a reset reaches a
187/// chain the device still holds: an `Rc<AtomicU64>` where there is a heap, a
188/// `&'static AtomicU64` where there is not. The queue sets it; its value
189/// before [`DeviceRing::new`] does not matter.
190///
191/// # What the device trusts
192///
193/// Nothing the driver wrote. Every index is checked against the queue's
194/// size, a chain is walked at most `size` descriptors with a visited set so
195/// a loop ends, every span must lie in memory the device may reach for its
196/// direction, and a chain is read **once**: the walk snapshots each
197/// descriptor, and the ports then use the snapshot, so a driver that
198/// rewrites a descriptor after publishing it changes nothing the device
199/// does. A chain that is malformed is not an error of the queue. It is
200/// handed up like any other, its [`io`](DeviceChain::io) says why, and the
201/// device completes it with a used length of zero, as the protocol's
202/// command-chain rules require.
203///
204/// The profile is the protocol's: direct descriptors only, no indirect
205/// tables, no event indices, and the two suppression flags.
206#[derive(Debug)]
207pub struct DeviceRing<M, E, const N: usize, const R: usize> {
208    memory: M,
209    state: QueueState,
210    max_chain_descriptors: u16,
211    addresses: RingAddresses,
212    current: E,
213    /// Available entries taken, and used entries published.
214    taken: u16,
215    used: u16,
216    /// Heads the device holds.
217    in_flight: [bool; N],
218    held: u16,
219    /// The walk's visited set: a descriptor was met on walk `pass` when its
220    /// mark is `pass`. Clearing the set is then one increment.
221    mark: [u16; N],
222    pass: u16,
223}
224
225impl<M, E, const N: usize, const R: usize> DeviceRing<M, E, N, R>
226where
227    M: SharedMemory + Clone + fmt::Debug,
228    E: Borrow<AtomicU64> + Clone + fmt::Debug,
229{
230    /// A queue in `memory` of at most `max_size` descriptors, whose chains
231    /// are at most `max_chain_descriptors` long. Unconfigured: the driver
232    /// sets its size and addresses and makes it ready.
233    ///
234    /// `None` when the limits do not fit: a queue no larger than `N`, and a
235    /// chain of two descriptors at least, no longer than `R` or the queue.
236    pub fn new(
237        memory: M,
238        current: E,
239        max_size: QueueSize,
240        max_chain_descriptors: u16,
241    ) -> Option<Self> {
242        let fits = usize::from(max_size.get()) <= N
243            && max_chain_descriptors >= 2
244            && usize::from(max_chain_descriptors) <= R
245            && max_chain_descriptors <= max_size.get();
246        fits.then(|| {
247            let epoch = QueueEpoch::INITIAL;
248            current.borrow().store(epoch.get(), Ordering::Release);
249            Self {
250                memory,
251                state: QueueState::unconfigured(max_size, epoch),
252                max_chain_descriptors,
253                addresses: RingAddresses::default(),
254                current,
255                taken: 0,
256                used: 0,
257                in_flight: [false; N],
258                held: 0,
259                mark: [0; N],
260                pass: 0,
261            }
262        })
263    }
264
265    /// The memory the queue is in, given back: the queue is over.
266    pub fn into_memory(self) -> M {
267        self.memory
268    }
269
270    /// Where the driver says the queue's parts are. Taken while the queue is
271    /// not ready, and checked when it is made so.
272    pub fn set_addresses(
273        &mut self,
274        addresses: RingAddresses,
275    ) -> Result<(), QueueError<DeviceRingError>> {
276        if self.state.ready() {
277            return Err(QueueError::Transport(DeviceRingError::Busy));
278        }
279        self.addresses = addresses;
280        Ok(())
281    }
282
283    /// The addresses the queue was given.
284    pub const fn addresses(&self) -> RingAddresses {
285        self.addresses
286    }
287
288    /// Chains the device holds: taken and not yet used.
289    pub const fn in_flight(&self) -> u16 {
290        self.held
291    }
292
293    fn size(&self) -> Result<u16, QueueError<DeviceRingError>> {
294        match (self.state.ready(), self.state.size()) {
295            (true, Some(size)) => Ok(size.get()),
296            _ => Err(QueueError::NotReady),
297        }
298    }
299
300    /// Walk the chain at `head`, snapshotting each descriptor once.
301    fn take(
302        &mut self,
303        head: u16,
304        size: u16,
305    ) -> Result<DeviceRingChain<M, E, R>, QueueError<DeviceRingError>> {
306        let epoch = self.state.epoch();
307        let port = || Port {
308            memory: self.memory.clone(),
309            spans: [Span::default(); R],
310            count: 0,
311            len: 0,
312            epoch,
313            current: self.current.clone(),
314        };
315        let mut chain = DeviceRingChain {
316            id: ChainId::new(epoch, u64::from(head)),
317            head,
318            regions: [ChainRegion::readable(0); R],
319            count: 0,
320            malformed: None,
321            request: RingSource(port()),
322            response: RingSink(port()),
323        };
324        chain.malformed = self.walk(&mut chain, head, size)?.err();
325        Ok(chain)
326    }
327
328    /// A fresh visited set.
329    fn begin_pass(&mut self) -> u16 {
330        self.pass = self.pass.wrapping_add(1);
331        if self.pass == 0 {
332            // Every mark a wrapped counter could collide with is forgotten.
333            self.mark = [0; N];
334            self.pass = 1;
335        }
336        self.pass
337    }
338
339    /// The walk proper. The outer error is the queue's own memory failing;
340    /// the inner one is this chain being malformed, which is the chain's
341    /// business and not the queue's.
342    fn walk(
343        &mut self,
344        chain: &mut DeviceRingChain<M, E, R>,
345        head: u16,
346        size: u16,
347    ) -> Result<Result<(), MalformedChain>, QueueError<DeviceRingError>> {
348        let pass = self.begin_pass();
349        let limit = self.max_chain_descriptors;
350        let (mut next, mut met) = (head, 0u16);
351        // At most `size` descriptors, a hostile loop included: the visited
352        // set ends it on the first index met twice.
353        for _ in 0..size {
354            if next >= size {
355                return Ok(Err(MalformedChain::DescriptorIndex));
356            }
357            if self.mark[usize::from(next)] == pass {
358                return Ok(Err(MalformedChain::DescriptorLoop));
359            }
360            self.mark[usize::from(next)] = pass;
361            let mut bytes = [0u8; DESCRIPTOR_BYTES as usize];
362            self.memory.read(
363                self.addresses.descriptors + u64::from(next) * DESCRIPTOR_BYTES,
364                &mut bytes,
365            )?;
366            let (at, len, flags, following) = fields(&bytes);
367            next = following;
368            if flags & VIRTQ_DESC_F_INDIRECT != 0 {
369                return Ok(Err(MalformedChain::IndirectUnsupported));
370            }
371            if flags & !(VIRTQ_DESC_F_NEXT | VIRTQ_DESC_F_WRITE) != 0 {
372                return Ok(Err(MalformedChain::DescriptorFlags));
373            }
374            met += 1;
375            // A chain past the limit is still walked to its end, so that it
376            // is judged for what is wrong with it; only its first `limit`
377            // descriptors are kept, and it is refused for its length below.
378            if met <= limit {
379                let writable = flags & VIRTQ_DESC_F_WRITE != 0;
380                chain.regions[usize::from(chain.count)] = if writable {
381                    ChainRegion::writable(u64::from(len))
382                } else {
383                    ChainRegion::readable(u64::from(len))
384                };
385                chain.count += 1;
386                let port = if writable {
387                    &mut chain.response.0
388                } else {
389                    &mut chain.request.0
390                };
391                port.spans[usize::from(port.count)] = Span { at, len };
392                port.count += 1;
393                port.len += u64::from(len);
394            }
395            if flags & VIRTQ_DESC_F_NEXT == 0 {
396                if met > limit {
397                    return Ok(Err(MalformedChain::DescriptorCount));
398                }
399                // Count, zero lengths, direction order and totals are the
400                // protocol's own rule, by its own function.
401                if let Err(error) =
402                    validate_chain_layout(&chain.regions[..usize::from(chain.count)], limit)
403                {
404                    return Ok(Err(error.into()));
405                }
406                // Every byte the engine may touch is reachable, for the
407                // direction it will be touched in, before the engine runs.
408                if !chain.request.0.mapped(Access::Read) || !chain.response.0.mapped(Access::Write)
409                {
410                    return Ok(Err(MalformedChain::Address));
411                }
412                return Ok(Ok(()));
413            }
414        }
415        // `size` descriptors and still a `next`: longer than any chain.
416        Ok(Err(MalformedChain::DescriptorCount))
417    }
418}
419
420impl<M, E, const N: usize, const R: usize> QueuePort for DeviceRing<M, E, N, R> {
421    fn state(&self) -> QueueState {
422        self.state
423    }
424}
425
426impl<M, E, const N: usize, const R: usize> QueueControl for DeviceRing<M, E, N, R>
427where
428    M: SharedMemory + Clone + fmt::Debug,
429    E: Borrow<AtomicU64> + Clone + fmt::Debug,
430{
431    type Error = DeviceRingError;
432
433    fn configure(&mut self, size: QueueSize) -> Result<(), QueueError<Self::Error>> {
434        if self.state.ready() {
435            return Err(QueueError::Transport(DeviceRingError::Busy));
436        }
437        if size > self.state.max_size() {
438            return Err(QueueError::InvalidConfiguration(
439                QueueConfigError::SizeExceedsMaximum,
440            ));
441        }
442        if size.get() < self.max_chain_descriptors {
443            return Err(QueueError::Transport(
444                DeviceRingError::ChainLimitExceedsQueue,
445            ));
446        }
447        self.state = QueueState::new(self.state.max_size(), Some(size), false, self.state.epoch())
448            .map_err(QueueError::InvalidConfiguration)?;
449        Ok(())
450    }
451
452    fn set_ready(&mut self, ready: bool) -> Result<(), QueueError<Self::Error>> {
453        if ready {
454            let Some(size) = self.state.size() else {
455                return Err(QueueError::InvalidConfiguration(
456                    QueueConfigError::ReadyWithoutSize,
457                ));
458            };
459            // The device reads the descriptor table and the available ring,
460            // and writes the used ring.
461            let access = [Access::Read, Access::Read, Access::Write];
462            if !self.addresses.hold(&self.memory, size, access) {
463                return Err(QueueError::Transport(DeviceRingError::Layout));
464            }
465        }
466        self.state = QueueState::new(
467            self.state.max_size(),
468            self.state.size(),
469            ready,
470            self.state.epoch(),
471        )
472        .map_err(QueueError::InvalidConfiguration)?;
473        Ok(())
474    }
475}
476
477impl<M, E, const N: usize, const R: usize> DeviceQueue for DeviceRing<M, E, N, R>
478where
479    M: SharedMemory + Clone + fmt::Debug,
480    E: Borrow<AtomicU64> + Clone + fmt::Debug,
481{
482    type Chain = DeviceRingChain<M, E, R>;
483    type Error = DeviceRingError;
484
485    fn pop_available(&mut self) -> Result<Option<Self::Chain>, QueueError<Self::Error>> {
486        let size = self.size()?;
487        // Acquire: the entry and the descriptors the driver wrote before it
488        // published this index are visible to the reads below.
489        let published = self
490            .memory
491            .load_u16(self.addresses.available + RING_INDEX)?;
492        let pending = published.wrapping_sub(self.taken);
493        if pending == 0 {
494            return Ok(None);
495        }
496        if pending > size {
497            return Err(QueueError::Transport(DeviceRingError::AvailableIndex));
498        }
499        let slot = u64::from(self.taken % size);
500        let mut entry = [0u8; AVAILABLE_ENTRY as usize];
501        self.memory.read(
502            self.addresses.available + RING_HEADER + slot * AVAILABLE_ENTRY,
503            &mut entry,
504        )?;
505        let head = u16::from_le_bytes(entry);
506        // A head the device already holds is the driver reusing descriptors
507        // it does not own. Judged before the entry is taken, so the queue is
508        // left exactly as it was.
509        if head < size && self.in_flight[usize::from(head)] {
510            return Err(QueueError::Transport(DeviceRingError::HeadInFlight));
511        }
512        let chain = self.take(head, size)?;
513        self.taken = self.taken.wrapping_add(1);
514        if head < size {
515            self.in_flight[usize::from(head)] = true;
516            self.held += 1;
517        }
518        Ok(Some(chain))
519    }
520
521    fn complete(
522        &mut self,
523        chain: Self::Chain,
524        used: UsedLength,
525    ) -> Result<NotificationHint, QueueError<Self::Error>> {
526        let current = self.state.epoch();
527        if chain.id.epoch() != current {
528            return Err(QueueError::ResetRace {
529                operation: chain.id.epoch(),
530                current,
531            });
532        }
533        let size = self.size()?;
534        let capacity = chain.response.0.len;
535        if u64::from(used.get()) > capacity {
536            return Err(QueueError::UsedLengthExceeded { used, capacity });
537        }
538        let slot = u64::from(self.used % size);
539        let mut entry = [0u8; USED_ENTRY as usize];
540        entry[..4].copy_from_slice(&u32::from(chain.head).to_le_bytes());
541        entry[4..].copy_from_slice(&used.get().to_le_bytes());
542        self.memory.write(
543            self.addresses.used + RING_HEADER + slot * USED_ENTRY,
544            &entry,
545        )?;
546        let published = self.used.wrapping_add(1);
547        // Release: the response bytes and the entry above are visible to a
548        // driver that has loaded this index.
549        self.memory
550            .store_u16(self.addresses.used + RING_INDEX, published)?;
551        self.used = published;
552        if chain.head < size && self.in_flight[usize::from(chain.head)] {
553            self.in_flight[usize::from(chain.head)] = false;
554            self.held -= 1;
555        }
556        // The index is published before the driver's suppression flag is
557        // read: a driver that clears the flag and then rechecks the index
558        // cannot miss this entry, and one that set it is not interrupted. A
559        // flag that cannot be read is a driver that is told.
560        fence(Ordering::SeqCst);
561        let suppressed = matches!(
562            self.memory.load_u16(self.addresses.available + RING_FLAGS),
563            Ok(flags) if flags & VIRTQ_AVAIL_F_NO_INTERRUPT != 0
564        );
565        Ok(if suppressed {
566            NotificationHint::Suppressed
567        } else {
568            NotificationHint::Notify
569        })
570    }
571
572    fn disable_available_notifications(&mut self) -> Result<(), QueueError<Self::Error>> {
573        self.size()?;
574        self.memory
575            .store_u16(self.addresses.used + RING_FLAGS, VIRTQ_USED_F_NO_NOTIFY)?;
576        Ok(())
577    }
578
579    fn enable_available_notifications(
580        &mut self,
581    ) -> Result<NotificationRecheck, QueueError<Self::Error>> {
582        self.size()?;
583        self.memory.store_u16(self.addresses.used + RING_FLAGS, 0)?;
584        // The flag is cleared before the index is read: a driver that
585        // published while notifications were off is seen here, and one that
586        // publishes after sees the flag clear and notifies.
587        fence(Ordering::SeqCst);
588        let published = self
589            .memory
590            .load_u16(self.addresses.available + RING_INDEX)?;
591        Ok(if published == self.taken {
592            NotificationRecheck::Idle
593        } else {
594            NotificationRecheck::WorkPending
595        })
596    }
597
598    fn reset(&mut self, next_epoch: QueueEpoch) -> Result<(), QueueError<Self::Error>> {
599        if next_epoch <= self.state.epoch() {
600            return Err(QueueError::InvalidConfiguration(
601                QueueConfigError::NonIncreasingEpoch,
602            ));
603        }
604        // Published first: a chain the device still holds refuses its bytes
605        // and its completion from here on, so nothing of the old epoch is
606        // written to memory the driver may now reuse.
607        self.current
608            .borrow()
609            .store(next_epoch.get(), Ordering::Release);
610        self.state = QueueState::unconfigured(self.state.max_size(), next_epoch);
611        self.addresses = RingAddresses::default();
612        self.taken = 0;
613        self.used = 0;
614        self.in_flight = [false; N];
615        self.held = 0;
616        Ok(())
617    }
618}