Skip to main content

virtio_accel_shared_queue/
driver.rs

1//! The driver's half: chains published, and taken back used.
2
3use core::fmt;
4use core::sync::atomic::{Ordering, fence};
5
6use virtio_accel_transport::{
7    ChainId, ChainLayoutError, ChainRegion, DriverChainBuffer, DriverQueue, NotificationHint,
8    NotificationRecheck, PublishError, PublishErrorKind, PublishedChain, QueueConfigError,
9    QueueControl, QueueEpoch, QueueError, QueuePort, QueueSize, QueueState, ReclaimedChain,
10    UsedChain, UsedLength, validate_chain_layout,
11};
12
13use crate::layout::{
14    AVAILABLE_ENTRY, DESCRIPTOR_BYTES, RING_FLAGS, RING_HEADER, RING_INDEX, RingAddresses,
15    USED_ENTRY, VIRTQ_AVAIL_F_NO_INTERRUPT, VIRTQ_DESC_F_NEXT, VIRTQ_DESC_F_WRITE,
16    VIRTQ_USED_F_NO_NOTIFY, descriptor, each_span,
17};
18use crate::memory::{Access, MemoryFault, SharedMemory};
19
20/// One run of bytes a descriptor names: a device address and a length.
21#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
22pub struct Region {
23    /// The device address of the first byte.
24    pub address: u64,
25    /// Bytes from there. Never zero in a chain.
26    pub len: u32,
27}
28
29/// Why a set of regions is not a chain.
30#[derive(Clone, Copy, Debug, PartialEq, Eq)]
31pub enum ChainShapeError {
32    /// More regions than the chain type holds.
33    Capacity,
34    /// The protocol's own chain rule refused the shape: fewer than one
35    /// region in either direction, or a region of no bytes.
36    Layout(ChainLayoutError),
37    /// A region runs past the end of the address space.
38    AddressOverflow,
39}
40
41/// A chain a driver owns: the regions the device reads, then the regions it
42/// writes, one descriptor each, at most `R` in all.
43///
44/// The value is a description. It owns no memory and holds no descriptor
45/// until [`DriverRing::publish`] gives it some; the bytes it names are the
46/// driver's, in memory `M` reaches by the same device addresses the device
47/// will be given. Nothing is copied into a queue: a region may be a buffer
48/// that already holds a payload.
49#[derive(Debug)]
50pub struct DriverChain<M, const R: usize> {
51    memory: M,
52    regions: [Region; R],
53    /// Of the first `count` regions, the first `readable` are the device's
54    /// to read.
55    readable: u16,
56    count: u16,
57    readable_bytes: u64,
58    writable_bytes: u64,
59}
60
61impl<M, const R: usize> DriverChain<M, R> {
62    /// A chain of `readable` regions followed by `writable` ones.
63    ///
64    /// The shape is held to the protocol's own rule here
65    /// (`validate_chain_layout`), so a `DriverChain` that exists is one a
66    /// conforming device accepts.
67    pub fn new(
68        memory: M,
69        readable: &[Region],
70        writable: &[Region],
71    ) -> Result<Self, ChainShapeError> {
72        let count = readable.len() + writable.len();
73        if count > R || count > usize::from(u16::MAX) {
74            return Err(ChainShapeError::Capacity);
75        }
76        let mut regions = [Region::default(); R];
77        let mut described = [ChainRegion::readable(0); R];
78        for (index, (region, writes)) in readable
79            .iter()
80            .map(|region| (region, false))
81            .chain(writable.iter().map(|region| (region, true)))
82            .enumerate()
83        {
84            if region.address.checked_add(u64::from(region.len)).is_none() {
85                return Err(ChainShapeError::AddressOverflow);
86            }
87            regions[index] = *region;
88            described[index] = if writes {
89                ChainRegion::writable(u64::from(region.len))
90            } else {
91                ChainRegion::readable(u64::from(region.len))
92            };
93        }
94        // `count <= u16::MAX` was checked, and the rule's own bound is the
95        // type's capacity: the queue applies its own, smaller one.
96        let layout = validate_chain_layout(&described[..count], count as u16)
97            .map_err(ChainShapeError::Layout)?;
98        Ok(Self {
99            memory,
100            regions,
101            readable: layout.readable_descriptors(),
102            count: count as u16,
103            readable_bytes: layout.readable_bytes(),
104            writable_bytes: layout.writable_bytes(),
105        })
106    }
107
108    /// The regions the device reads.
109    pub fn readable(&self) -> &[Region] {
110        &self.regions[..usize::from(self.readable)]
111    }
112
113    /// The regions the device writes.
114    pub fn writable(&self) -> &[Region] {
115        &self.regions[usize::from(self.readable)..usize::from(self.count)]
116    }
117
118    /// Descriptors the chain takes: one a region.
119    pub const fn descriptors(&self) -> u16 {
120        self.count
121    }
122}
123
124impl<M: SharedMemory + fmt::Debug, const R: usize> DriverChainBuffer for DriverChain<M, R> {
125    type Error = MemoryFault;
126
127    fn device_readable_len(&self) -> u64 {
128        self.readable_bytes
129    }
130
131    fn device_writable_len(&self) -> u64 {
132        self.writable_bytes
133    }
134
135    fn write_device_readable(&mut self, offset: u64, source: &[u8]) -> Result<(), MemoryFault> {
136        within(offset, source.len(), self.readable_bytes)?;
137        let spans = self
138            .readable()
139            .iter()
140            .map(|region| (region.address, region.len));
141        each_span(spans, offset, source.len(), |at, from, count| {
142            self.memory.write(at, &source[from..from + count])
143        })
144    }
145
146    fn read_device_writable(&self, offset: u64, target: &mut [u8]) -> Result<(), MemoryFault> {
147        within(offset, target.len(), self.writable_bytes)?;
148        let spans = self
149            .writable()
150            .iter()
151            .map(|region| (region.address, region.len));
152        each_span(spans, offset, target.len(), |at, from, count| {
153            self.memory.read(at, &mut target[from..from + count])
154        })
155    }
156}
157
158fn within(offset: u64, len: usize, room: u64) -> Result<(), MemoryFault> {
159    match offset.checked_add(len as u64) {
160        Some(end) if end <= room => Ok(()),
161        _ => Err(MemoryFault::Range),
162    }
163}
164
165/// Why the driver's half could not go on.
166#[derive(Clone, Copy, Debug, PartialEq, Eq)]
167pub enum DriverRingError {
168    /// A part of the queue is not where the layout allows: misaligned,
169    /// overlapping another, or outside memory the driver may write.
170    Layout,
171    /// The queue cannot be reconfigured while it is ready or holds chains.
172    Busy,
173    /// The queue was sized smaller than the longest chain it must hold.
174    ChainLimitExceedsQueue,
175    /// The device published more used entries than it holds chains.
176    UsedIndex,
177    /// A used entry names a chain the device does not hold, or says it wrote
178    /// more than the chain gave it room for.
179    UsedEntry,
180    /// The memory stopped answering for a ring the queue validated.
181    Memory(MemoryFault),
182}
183
184impl From<MemoryFault> for QueueError<DriverRingError> {
185    fn from(fault: MemoryFault) -> Self {
186        Self::Transport(DriverRingError::Memory(fault))
187    }
188}
189
190/// The driver's half of one split virtqueue in shared memory.
191///
192/// `N` bounds the queue's size and `R` a chain's regions; both are storage
193/// the value carries inline, so the queue allocates nothing. One owner:
194/// every operation takes `&mut self`, and there is no lock.
195///
196/// # What the driver trusts
197///
198/// Nothing the device wrote, and nothing it can write. The descriptor table
199/// is never read back: the free list, each chain's links and its room are
200/// kept here, so a device that rewrites a descriptor changes nothing the
201/// driver does. A used entry is checked before it is believed — the head
202/// must be a chain the device holds, the length no more than the chain's
203/// writable bytes, and the used index no further ahead than chains are
204/// outstanding. A device that fails any of them has stopped being a device:
205/// the queue refuses every operation from then on
206/// ([`DriverRingError::UsedIndex`], [`DriverRingError::UsedEntry`]) until it
207/// is [`reset`](DriverQueue::reset), which is also what the driver owes the
208/// device.
209///
210/// The profile is the protocol's: direct descriptors only, no indirect
211/// tables, no event indices, and the two suppression flags.
212#[derive(Debug)]
213pub struct DriverRing<M, const N: usize, const R: usize> {
214    memory: M,
215    state: QueueState,
216    max_chain_descriptors: u16,
217    addresses: RingAddresses,
218    /// The free list's links and each published chain's, by descriptor.
219    next: [u16; N],
220    free_head: u16,
221    free: u16,
222    /// The chains the device has, by head descriptor.
223    held: [Option<DriverChain<M, R>>; N],
224    outstanding: u16,
225    /// Available entries published, and used entries taken back.
226    published: u16,
227    taken: u16,
228    /// Set once the device has lied; cleared by a reset.
229    failed: Option<DriverRingError>,
230    /// The rings have not been cleared since the queue was sized or placed.
231    fresh: bool,
232}
233
234impl<M: SharedMemory + Clone + fmt::Debug, const N: usize, const R: usize> DriverRing<M, N, R> {
235    /// A queue in `memory` of at most `max_size` descriptors whose chains
236    /// are at most `max_chain_descriptors` long. Unconfigured: the driver
237    /// [`configure`](QueueControl::configure)s a size, says where the parts
238    /// are ([`set_addresses`](Self::set_addresses)) and makes it ready.
239    ///
240    /// `None` when the limits do not fit: a queue no larger than `N`, and a
241    /// chain of two descriptors at least, no longer than `R` or the queue.
242    pub fn new(memory: M, max_size: QueueSize, max_chain_descriptors: u16) -> Option<Self> {
243        let fits = usize::from(max_size.get()) <= N
244            && max_chain_descriptors >= 2
245            && usize::from(max_chain_descriptors) <= R
246            && max_chain_descriptors <= max_size.get();
247        fits.then(|| Self {
248            memory,
249            state: QueueState::unconfigured(max_size, QueueEpoch::INITIAL),
250            max_chain_descriptors,
251            addresses: RingAddresses::default(),
252            next: [0; N],
253            free_head: 0,
254            free: 0,
255            held: [const { None }; N],
256            outstanding: 0,
257            published: 0,
258            taken: 0,
259            failed: None,
260            fresh: true,
261        })
262    }
263
264    /// Where the queue's parts are. Taken while the queue is not ready and
265    /// the device holds nothing, and checked when the queue is made ready.
266    pub fn set_addresses(
267        &mut self,
268        addresses: RingAddresses,
269    ) -> Result<(), QueueError<DriverRingError>> {
270        if self.state.ready() || self.outstanding != 0 {
271            return Err(QueueError::Transport(DriverRingError::Busy));
272        }
273        self.addresses = addresses;
274        self.fresh = true;
275        Ok(())
276    }
277
278    /// The addresses the queue was given: what the transport is told.
279    pub const fn addresses(&self) -> RingAddresses {
280        self.addresses
281    }
282
283    /// Chains the device holds: published and not yet taken back.
284    pub const fn outstanding(&self) -> u16 {
285        self.outstanding
286    }
287
288    /// Descriptors no chain holds.
289    pub const fn free_descriptors(&self) -> u16 {
290        self.free
291    }
292
293    /// The configured size of a ready queue that has not failed.
294    fn live(&self) -> Result<QueueSize, QueueError<DriverRingError>> {
295        if let Some(failure) = self.failed {
296            return Err(QueueError::Transport(failure));
297        }
298        match (self.state.ready(), self.state.size()) {
299            (true, Some(size)) => Ok(size),
300            _ => Err(QueueError::NotReady),
301        }
302    }
303
304    /// Record that the device lied, and say so.
305    fn fail<T>(&mut self, failure: DriverRingError) -> Result<T, QueueError<DriverRingError>> {
306        self.failed = Some(failure);
307        Err(QueueError::Transport(failure))
308    }
309
310    /// Write `chain`'s descriptors into the table on descriptors taken from
311    /// the free list, add its head to the available ring and publish the
312    /// index. On a fault nothing is published and the free list is as it was.
313    fn expose(
314        &mut self,
315        chain: &DriverChain<M, R>,
316        size: u16,
317    ) -> Result<(u16, NotificationHint), MemoryFault> {
318        let head = self.free_head;
319        let last = chain.count - 1;
320        let mut index = head;
321        for (position, region) in chain.regions[..usize::from(chain.count)].iter().enumerate() {
322            let position = position as u16;
323            let following = self.next[usize::from(index)];
324            let mut flags = if position < chain.readable {
325                0
326            } else {
327                VIRTQ_DESC_F_WRITE
328            };
329            if position < last {
330                flags |= VIRTQ_DESC_F_NEXT;
331            }
332            let next = if position < last { following } else { 0 };
333            self.memory.write(
334                self.addresses.descriptors + u64::from(index) * DESCRIPTOR_BYTES,
335                &descriptor(region.address, region.len, flags, next),
336            )?;
337            index = following;
338        }
339        let slot = u64::from(self.published % size);
340        self.memory.write(
341            self.addresses.available + RING_HEADER + slot * AVAILABLE_ENTRY,
342            &head.to_le_bytes(),
343        )?;
344        let published = self.published.wrapping_add(1);
345        // Release: the request bytes, the descriptors and the entry are
346        // visible to a device that has loaded this index.
347        self.memory
348            .store_u16(self.addresses.available + RING_INDEX, published)?;
349        // Committed: the descriptors are the device's from here.
350        self.published = published;
351        self.free_head = index;
352        self.free -= chain.count;
353        // The index is published before the device's suppression flag is
354        // read: a device that clears the flag and rechecks the index cannot
355        // miss this chain. The chain is the device's by now, so a flag that
356        // cannot be read is a device that is told, not a failed publication.
357        fence(Ordering::SeqCst);
358        let suppressed = matches!(
359            self.memory.load_u16(self.addresses.used + RING_FLAGS),
360            Ok(flags) if flags & VIRTQ_USED_F_NO_NOTIFY != 0
361        );
362        Ok((
363            head,
364            if suppressed {
365                NotificationHint::Suppressed
366            } else {
367                NotificationHint::Notify
368            },
369        ))
370    }
371
372    /// Return the `count` descriptors chained from `head` to the free list.
373    fn release(&mut self, head: u16, count: u16) {
374        let mut tail = head;
375        for _ in 1..count {
376            tail = self.next[usize::from(tail)];
377        }
378        self.next[usize::from(tail)] = self.free_head;
379        self.free_head = head;
380        self.free += count;
381    }
382}
383
384impl<M, const N: usize, const R: usize> QueuePort for DriverRing<M, N, R> {
385    fn state(&self) -> QueueState {
386        self.state
387    }
388}
389
390impl<M: SharedMemory + Clone + fmt::Debug, const N: usize, const R: usize> QueueControl
391    for DriverRing<M, N, R>
392{
393    type Error = DriverRingError;
394
395    fn configure(&mut self, size: QueueSize) -> Result<(), QueueError<Self::Error>> {
396        if self.state.ready() || self.outstanding != 0 {
397            return Err(QueueError::Transport(DriverRingError::Busy));
398        }
399        if size > self.state.max_size() {
400            return Err(QueueError::InvalidConfiguration(
401                QueueConfigError::SizeExceedsMaximum,
402            ));
403        }
404        if size.get() < self.max_chain_descriptors {
405            return Err(QueueError::Transport(
406                DriverRingError::ChainLimitExceedsQueue,
407            ));
408        }
409        self.state = QueueState::new(self.state.max_size(), Some(size), false, self.state.epoch())
410            .map_err(QueueError::InvalidConfiguration)?;
411        // Every descriptor is free, each linked to the one after it.
412        for index in 0..size.get() {
413            self.next[usize::from(index)] = index + 1;
414        }
415        self.free_head = 0;
416        self.free = size.get();
417        self.fresh = true;
418        Ok(())
419    }
420
421    /// Making the queue ready checks the layout. The first time after it was
422    /// sized or placed it also clears both rings' headers, because the memory
423    /// may have held a queue before: do that before the transport is told the
424    /// queue is live, while the memory is still only the driver's. A queue
425    /// made not ready and ready again is a pause, and resumes where it was.
426    fn set_ready(&mut self, ready: bool) -> Result<(), QueueError<Self::Error>> {
427        if ready && !self.state.ready() {
428            let Some(size) = self.state.size() else {
429                return Err(QueueError::InvalidConfiguration(
430                    QueueConfigError::ReadyWithoutSize,
431                ));
432            };
433            if !self.addresses.hold(&self.memory, size, [Access::Write; 3]) {
434                return Err(QueueError::Transport(DriverRingError::Layout));
435            }
436            if self.fresh {
437                for ring in [self.addresses.available, self.addresses.used] {
438                    self.memory.store_u16(ring + RING_FLAGS, 0)?;
439                    self.memory.store_u16(ring + RING_INDEX, 0)?;
440                }
441                self.published = 0;
442                self.taken = 0;
443                self.fresh = false;
444            }
445        }
446        self.state = QueueState::new(
447            self.state.max_size(),
448            self.state.size(),
449            ready,
450            self.state.epoch(),
451        )
452        .map_err(QueueError::InvalidConfiguration)?;
453        Ok(())
454    }
455}
456
457impl<M: SharedMemory + Clone + fmt::Debug, const N: usize, const R: usize> DriverQueue
458    for DriverRing<M, N, R>
459{
460    type Chain = DriverChain<M, R>;
461    type Reclaimed = ReclaimedChains<M, N, R>;
462    type Error = DriverRingError;
463
464    fn publish(
465        &mut self,
466        chain: Self::Chain,
467    ) -> Result<PublishedChain, PublishError<Self::Chain, Self::Error>> {
468        let size = match self.live() {
469            Ok(size) => size.get(),
470            Err(QueueError::Transport(failure)) => {
471                return Err(PublishError::new(
472                    chain,
473                    PublishErrorKind::Transport(failure),
474                ));
475            }
476            Err(_) => return Err(PublishError::new(chain, PublishErrorKind::NotReady)),
477        };
478        // The reference model's classification, kept exactly: the ring is
479        // full only when it has no slot for another head, which chains of
480        // two descriptors at least never reach; a chain that does not fit
481        // the limit, or the descriptors now free, lacks descriptors.
482        if self.outstanding == size {
483            return Err(PublishError::new(chain, PublishErrorKind::QueueFull));
484        }
485        if chain.count > self.max_chain_descriptors || chain.count > self.free {
486            return Err(PublishError::new(
487                chain,
488                PublishErrorKind::InsufficientDescriptors,
489            ));
490        }
491        match self.expose(&chain, size) {
492            Ok((head, hint)) => {
493                let id = ChainId::new(self.state.epoch(), u64::from(head));
494                self.held[usize::from(head)] = Some(chain);
495                self.outstanding += 1;
496                Ok(PublishedChain::new(id, hint))
497            }
498            Err(fault) => Err(PublishError::new(
499                chain,
500                PublishErrorKind::Transport(DriverRingError::Memory(fault)),
501            )),
502        }
503    }
504
505    fn pop_used(&mut self) -> Result<Option<UsedChain<Self::Chain>>, QueueError<Self::Error>> {
506        let size = self.live()?.get();
507        // Acquire: the entry and the response bytes the device wrote before
508        // it published this index are visible to the reads below.
509        let published = self.memory.load_u16(self.addresses.used + RING_INDEX)?;
510        let pending = published.wrapping_sub(self.taken);
511        if pending == 0 {
512            return Ok(None);
513        }
514        if pending > self.outstanding {
515            return self.fail(DriverRingError::UsedIndex);
516        }
517        let slot = u64::from(self.taken % size);
518        // One snapshot: the entry is judged and acted on from the same bytes.
519        let mut entry = [0u8; USED_ENTRY as usize];
520        self.memory.read(
521            self.addresses.used + RING_HEADER + slot * USED_ENTRY,
522            &mut entry,
523        )?;
524        let head = u32::from_le_bytes([entry[0], entry[1], entry[2], entry[3]]);
525        let written = u32::from_le_bytes([entry[4], entry[5], entry[6], entry[7]]);
526        let held = if head < u32::from(size) {
527            self.held[head as usize].take()
528        } else {
529            None
530        };
531        let Some(chain) = held else {
532            return self.fail(DriverRingError::UsedEntry);
533        };
534        if u64::from(written) > chain.writable_bytes {
535            // Kept, so a reset still returns it to its owner.
536            self.held[head as usize] = Some(chain);
537            return self.fail(DriverRingError::UsedEntry);
538        }
539        let head = head as u16;
540        self.taken = self.taken.wrapping_add(1);
541        self.outstanding -= 1;
542        self.release(head, chain.count);
543        Ok(Some(UsedChain::new(
544            ChainId::new(self.state.epoch(), u64::from(head)),
545            UsedLength::new(written),
546            chain,
547        )))
548    }
549
550    fn disable_used_notifications(&mut self) -> Result<(), QueueError<Self::Error>> {
551        self.live()?;
552        self.memory.store_u16(
553            self.addresses.available + RING_FLAGS,
554            VIRTQ_AVAIL_F_NO_INTERRUPT,
555        )?;
556        Ok(())
557    }
558
559    fn enable_used_notifications(
560        &mut self,
561    ) -> Result<NotificationRecheck, QueueError<Self::Error>> {
562        self.live()?;
563        self.memory
564            .store_u16(self.addresses.available + RING_FLAGS, 0)?;
565        // The flag is cleared before the index is read: a device that used a
566        // chain while interrupts were off is seen here, and one that uses a
567        // chain after sees the flag clear and interrupts.
568        fence(Ordering::SeqCst);
569        let published = self.memory.load_u16(self.addresses.used + RING_INDEX)?;
570        Ok(if published == self.taken {
571            NotificationRecheck::Idle
572        } else {
573            NotificationRecheck::WorkPending
574        })
575    }
576
577    fn reset(
578        &mut self,
579        next_epoch: QueueEpoch,
580    ) -> Result<Self::Reclaimed, QueueError<Self::Error>> {
581        let epoch = self.state.epoch();
582        if next_epoch <= epoch {
583            return Err(QueueError::InvalidConfiguration(
584                QueueConfigError::NonIncreasingEpoch,
585            ));
586        }
587        let held = core::mem::replace(&mut self.held, [const { None }; N]);
588        // Unconfigured: the queue a driver uses after a reset is one it has
589        // sized, placed and made ready again.
590        self.state = QueueState::unconfigured(self.state.max_size(), next_epoch);
591        self.addresses = RingAddresses::default();
592        self.free_head = 0;
593        self.free = 0;
594        self.outstanding = 0;
595        self.published = 0;
596        self.taken = 0;
597        self.failed = None;
598        self.fresh = true;
599        Ok(ReclaimedChains {
600            held,
601            epoch,
602            next: 0,
603        })
604    }
605}
606
607/// The chains a reset took back from the device, each with the identity it
608/// was published under.
609#[derive(Debug)]
610pub struct ReclaimedChains<M, const N: usize, const R: usize> {
611    held: [Option<DriverChain<M, R>>; N],
612    epoch: QueueEpoch,
613    next: usize,
614}
615
616impl<M, const N: usize, const R: usize> Iterator for ReclaimedChains<M, N, R> {
617    type Item = ReclaimedChain<DriverChain<M, R>>;
618
619    fn next(&mut self) -> Option<Self::Item> {
620        while self.next < N {
621            let head = self.next;
622            self.next += 1;
623            if let Some(chain) = self.held[head].take() {
624                return Some(ReclaimedChain::new(
625                    ChainId::new(self.epoch, head as u64),
626                    chain,
627                ));
628            }
629        }
630        None
631    }
632}