Skip to main content

virtio_accel_shared_queue/
layout.rs

1//! Where a split virtqueue's three parts are, and what is in them
2//! (Virtio 1.2 §2.7).
3
4use virtio_accel_transport::QueueSize;
5
6use crate::memory::{Access, SharedMemory};
7
8/// One descriptor: `addr: u64, len: u32, flags: u16, next: u16` (§2.7.5).
9pub(crate) const DESCRIPTOR_BYTES: u64 = 16;
10pub(crate) const DESCRIPTOR_LEN: usize = 8;
11pub(crate) const DESCRIPTOR_FLAGS: usize = 12;
12pub(crate) const DESCRIPTOR_NEXT: usize = 14;
13
14/// The chain continues at `next`.
15pub const VIRTQ_DESC_F_NEXT: u16 = 1 << 0;
16/// The device writes this descriptor's bytes; otherwise it reads them.
17pub const VIRTQ_DESC_F_WRITE: u16 = 1 << 1;
18/// The descriptor names an indirect table: not in this profile.
19pub const VIRTQ_DESC_F_INDIRECT: u16 = 1 << 2;
20
21/// Both rings begin `flags: u16, idx: u16` (§2.7.6, §2.7.8).
22pub(crate) const RING_FLAGS: u64 = 0;
23pub(crate) const RING_INDEX: u64 = 2;
24pub(crate) const RING_HEADER: u64 = 4;
25/// An available-ring entry is a descriptor index.
26pub(crate) const AVAILABLE_ENTRY: u64 = 2;
27/// A used-ring entry is `id: u32, len: u32`.
28pub(crate) const USED_ENTRY: u64 = 8;
29
30/// The driver asks not to be interrupted when the device uses a chain.
31pub const VIRTQ_AVAIL_F_NO_INTERRUPT: u16 = 1 << 0;
32/// The device asks not to be notified when the driver publishes a chain.
33pub const VIRTQ_USED_F_NO_NOTIFY: u16 = 1 << 0;
34
35/// Alignments §2.7 requires of each part.
36const DESCRIPTOR_ALIGN: u64 = 16;
37const AVAILABLE_ALIGN: u64 = 2;
38const USED_ALIGN: u64 = 4;
39
40/// Where a driver put a queue's three parts, as device addresses: what it
41/// writes to the transport's descriptor, driver and device area registers.
42#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
43pub struct RingAddresses {
44    /// The descriptor table.
45    pub descriptors: u64,
46    /// The available ring, which the driver writes.
47    pub available: u64,
48    /// The used ring, which the device writes.
49    pub used: u64,
50}
51
52impl RingAddresses {
53    /// Bytes of descriptor table a queue of `size` has.
54    pub const fn descriptor_table_bytes(size: QueueSize) -> u64 {
55        size.get() as u64 * DESCRIPTOR_BYTES
56    }
57
58    /// Bytes of available ring a queue of `size` has. The trailing
59    /// `used_event` word exists only with event indices, which this profile
60    /// does not negotiate.
61    pub const fn available_ring_bytes(size: QueueSize) -> u64 {
62        RING_HEADER + size.get() as u64 * AVAILABLE_ENTRY
63    }
64
65    /// Bytes of used ring a queue of `size` has.
66    pub const fn used_ring_bytes(size: QueueSize) -> u64 {
67        RING_HEADER + size.get() as u64 * USED_ENTRY
68    }
69
70    /// The three parts one after another from `base`, each aligned as §2.7
71    /// requires, and the bytes the whole takes. `None` when `base` is not
72    /// aligned for a descriptor table or the queue would wrap the address
73    /// space.
74    pub const fn contiguous(base: u64, size: QueueSize) -> Option<(Self, u64)> {
75        if base % DESCRIPTOR_ALIGN != 0 {
76            return None;
77        }
78        // A descriptor table's length is a multiple of the available ring's
79        // alignment, so only the used ring needs rounding up to its own.
80        let Some(available) = base.checked_add(Self::descriptor_table_bytes(size)) else {
81            return None;
82        };
83        let Some(end) = available.checked_add(Self::available_ring_bytes(size)) else {
84            return None;
85        };
86        let Some(used) = end.checked_next_multiple_of(USED_ALIGN) else {
87            return None;
88        };
89        let Some(end) = used.checked_add(Self::used_ring_bytes(size)) else {
90            return None;
91        };
92        Some((
93            Self {
94                descriptors: base,
95                available,
96                used,
97            },
98            end - base,
99        ))
100    }
101
102    /// Each part with its length, for a queue of `size`.
103    const fn parts(&self, size: QueueSize) -> [(u64, u64); 3] {
104        [
105            (self.descriptors, Self::descriptor_table_bytes(size)),
106            (self.available, Self::available_ring_bytes(size)),
107            (self.used, Self::used_ring_bytes(size)),
108        ]
109    }
110
111    /// Whether the three parts are aligned for their entries, do not wrap,
112    /// do not overlap one another, and lie in memory that admits each as
113    /// `access` says (descriptor table, available ring, used ring).
114    pub(crate) fn hold<M: SharedMemory>(
115        &self,
116        memory: &M,
117        size: QueueSize,
118        access: [Access; 3],
119    ) -> bool {
120        let parts = self.parts(size);
121        let aligned = self.descriptors % DESCRIPTOR_ALIGN == 0
122            && self.available % AVAILABLE_ALIGN == 0
123            && self.used % USED_ALIGN == 0;
124        let disjoint =
125            |a: (u64, u64), b: (u64, u64)| match (a.0.checked_add(a.1), b.0.checked_add(b.1)) {
126                (Some(a_end), Some(b_end)) => a_end <= b.0 || b_end <= a.0,
127                _ => false,
128            };
129        aligned
130            && disjoint(parts[0], parts[1])
131            && disjoint(parts[0], parts[2])
132            && disjoint(parts[1], parts[2])
133            && parts
134                .iter()
135                .zip(access)
136                .all(|((at, len), access)| memory.admits(*at, *len, access))
137    }
138}
139
140/// One descriptor's sixteen bytes.
141pub(crate) fn descriptor(
142    address: u64,
143    len: u32,
144    flags: u16,
145    next: u16,
146) -> [u8; DESCRIPTOR_BYTES as usize] {
147    let mut bytes = [0u8; DESCRIPTOR_BYTES as usize];
148    bytes[..DESCRIPTOR_LEN].copy_from_slice(&address.to_le_bytes());
149    bytes[DESCRIPTOR_LEN..DESCRIPTOR_FLAGS].copy_from_slice(&len.to_le_bytes());
150    bytes[DESCRIPTOR_FLAGS..DESCRIPTOR_NEXT].copy_from_slice(&flags.to_le_bytes());
151    bytes[DESCRIPTOR_NEXT..].copy_from_slice(&next.to_le_bytes());
152    bytes
153}
154
155/// The four fields of one descriptor's sixteen bytes.
156pub(crate) fn fields(bytes: &[u8; DESCRIPTOR_BYTES as usize]) -> (u64, u32, u16, u16) {
157    let word = |at: usize, len: usize| {
158        let mut wide = [0u8; 8];
159        wide[..len].copy_from_slice(&bytes[at..at + len]);
160        u64::from_le_bytes(wide)
161    };
162    (
163        word(0, 8),
164        word(DESCRIPTOR_LEN, 4) as u32,
165        word(DESCRIPTOR_FLAGS, 2) as u16,
166        word(DESCRIPTOR_NEXT, 2) as u16,
167    )
168}
169
170/// Visit the spans `len` bytes at `offset` fall in, out of `spans` taken as
171/// one run of bytes: `(address, from, count)` with `from` the offset into the
172/// caller's buffer. The caller has checked that the run holds them.
173pub(crate) fn each_span<E>(
174    spans: impl Iterator<Item = (u64, u32)>,
175    offset: u64,
176    len: usize,
177    mut visit: impl FnMut(u64, usize, usize) -> Result<(), E>,
178) -> Result<(), E> {
179    let (mut skip, mut done) = (offset, 0usize);
180    for (at, span) in spans {
181        let span = u64::from(span);
182        if skip >= span {
183            skip -= span;
184            continue;
185        }
186        if done == len {
187            break;
188        }
189        let count = ((span - skip) as usize).min(len - done);
190        visit(at + skip, done, count)?;
191        done += count;
192        skip = 0;
193    }
194    Ok(())
195}