Skip to main content

strat9_kernel/s9vm/
virtio.rs

1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23//! s9vm : virtio split-queue core (pure).
24//!
25//! A virtio device exchanges buffers with its driver through a *split
26//! virtqueue*: a descriptor table, an available ring (driver → device) and a
27//! used ring (device → driver). The layout is transport-independent, which is
28//! why this module is a pure model: it only needs guest-physical memory
29//! access, and the transport layer (MMIO page or PCI BAR) is a thin register
30//! file on top.
31//!
32//! Implemented here:
33//!
34//! - descriptor encoding/decoding (16 bytes: `addr`, `len`, `flags`, `next`);
35//! - available-ring consumption (`idx` and `ring[]`) with wrap-around;
36//! - chain walking, including one level of *indirect* descriptor tables;
37//! - used-ring completion (`id` + written length), with wrap-around;
38//! - modern feature negotiation ([`DeviceFeatures`]), device-status
39//!   transitions ([`apply_status`]) and queue-programming validation
40//!   ([`QueueState`], [`QueueNotify`]);
41//! - used-ring event suppression (`VIRTQ_AVAIL_F_NO_INTERRUPT`).
42//!
43//! The transport layer (MMIO page or PCI BAR) remains a thin register file on
44//! top of these primitives.
45
46use alloc::vec::Vec;
47
48/// Size of one descriptor in the table.
49pub const DESCRIPTOR_SIZE: u64 = 16;
50/// Descriptor flag: the chain continues in `next`.
51pub const DESC_F_NEXT: u16 = 1;
52/// Descriptor flag: the buffer is written by the device.
53pub const DESC_F_WRITE: u16 = 2;
54/// Descriptor flag: `addr` points to an indirect descriptor table.
55pub const DESC_F_INDIRECT: u16 = 4;
56/// Highest queue size accepted by the legacy interface.
57pub const MAX_QUEUE_SIZE: u16 = 32768;
58
59/// Available-ring flag: the driver does not want used-ring interrupts.
60pub const VIRTQ_AVAIL_F_NO_INTERRUPT: u16 = 1;
61/// Feature bit `VIRTIO_F_VERSION_1` (modern interface), bit 32 of the
62/// device/driver feature space.
63pub const VIRTIO_F_VERSION_1: u32 = 1;
64/// 64-bit mask of [`VIRTIO_F_VERSION_1`].
65const VERSION_1_MASK: u64 = 1u64 << 32;
66
67/// Device-status bits (virtio specification, transport independent).
68pub mod status {
69    /// Guest acknowledged the device.
70    pub const ACKNOWLEDGE: u32 = 1;
71    /// Guest knows how to drive the device.
72    pub const DRIVER: u32 = 2;
73    /// Guest finished driver initialization.
74    pub const DRIVER_OK: u32 = 4;
75    /// Guest accepted the feature set.
76    pub const FEATURES_OK: u32 = 8;
77    /// Device requests a reset (legacy alias of `DEVICE_NEEDS_RESET`).
78    pub const NEEDS_RESET: u32 = 64;
79    /// Device failed and must be reset.
80    pub const FAILED: u32 = 128;
81}
82
83/// Mask of every status bit the models understand.
84pub const STATUS_KNOWN: u32 = status::ACKNOWLEDGE
85    | status::DRIVER
86    | status::DRIVER_OK
87    | status::FEATURES_OK
88    | status::NEEDS_RESET
89    | status::FAILED;
90
91/// Feature-negotiation failure.
92#[derive(Debug, Clone, Copy, PartialEq, Eq)]
93pub enum FeatureError {
94    /// The driver requested a bit the device does not offer.
95    Unsupported,
96    /// A driver that negotiated features did not accept
97    /// [`VIRTIO_F_VERSION_1`].
98    Version1Required,
99}
100
101/// Modern feature negotiation state: device offer, driver request and the
102/// mask committed when the driver writes `FEATURES_OK`.
103///
104/// A driver that requests no feature bit at all is treated as a
105/// pre-negotiation driver: `FEATURES_OK` is accepted with an empty negotiated
106/// mask, so transports that predate feature negotiation keep working. As soon
107/// as the driver requests any bit, [`Self::negotiate`] enforces the device
108/// offer and [`VIRTIO_F_VERSION_1`].
109#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
110pub struct DeviceFeatures {
111    device: u64,
112    driver: u64,
113    negotiated: u64,
114}
115
116impl DeviceFeatures {
117    /// Creates a negotiation state with the features offered by the device.
118    pub const fn new(device: u64) -> Self {
119        Self {
120            device,
121            driver: 0,
122            negotiated: 0,
123        }
124    }
125
126    /// Features offered by the device.
127    pub const fn device(&self) -> u64 {
128        self.device
129    }
130
131    /// Features requested by the driver (raw mask).
132    pub const fn driver(&self) -> u64 {
133        self.driver
134    }
135
136    /// Features committed at `FEATURES_OK` (`driver & device`).
137    pub const fn negotiated(&self) -> u64 {
138        self.negotiated
139    }
140
141    /// Updates one 32-bit half of the driver feature request.
142    pub fn write_driver_word(&mut self, select: u32, value: u32) {
143        if select == 0 {
144            self.driver = (self.driver & 0xFFFF_FFFF_0000_0000) | u64::from(value);
145        } else {
146            self.driver = (self.driver & 0xFFFF_FFFF) | (u64::from(value) << 32);
147        }
148        // A new request invalidates the previously committed mask.
149        self.negotiated = 0;
150    }
151
152    /// Reads one 32-bit half of the driver feature request.
153    pub fn read_driver_word(&self, select: u32) -> u32 {
154        feature_word(self.driver, select)
155    }
156
157    /// Reads one 32-bit half of the device feature offer.
158    pub fn read_device_word(&self, select: u32) -> u32 {
159        feature_word(self.device, select)
160    }
161
162    /// Validates the driver request and commits `driver & device`.
163    pub fn negotiate(&mut self) -> Result<u64, FeatureError> {
164        if self.driver & !self.device != 0 {
165            return Err(FeatureError::Unsupported);
166        }
167        if self.driver != 0 && self.driver & VERSION_1_MASK == 0 {
168            return Err(FeatureError::Version1Required);
169        }
170        self.negotiated = self.driver & self.device;
171        Ok(self.negotiated)
172    }
173
174    /// Drops the committed mask (driver cleared `FEATURES_OK`).
175    pub fn clear_negotiated(&mut self) {
176        self.negotiated = 0;
177    }
178
179    /// True if [`VIRTIO_F_VERSION_1`] was negotiated.
180    pub const fn version_1(&self) -> bool {
181        self.negotiated & VERSION_1_MASK != 0
182    }
183}
184
185/// One 32-bit half of a 64-bit feature mask.
186const fn feature_word(features: u64, select: u32) -> u32 {
187    if select == 0 {
188        features as u32
189    } else {
190        (features >> 32) as u32
191    }
192}
193
194/// Applies one guest write to the device-status register.
195///
196/// Returns the new status value. Any invalid write (unknown bit, unsupported
197/// feature request, missing [`VIRTIO_F_VERSION_1`], `DRIVER_OK` without
198/// `FEATURES_OK`) leaves the device in the `FAILED` state, as required by the
199/// specification. `written` is the full value the driver wrote, since the
200/// status register is cumulative.
201pub fn apply_status(current: u32, written: u32, features: &mut DeviceFeatures) -> u32 {
202    if written & !STATUS_KNOWN != 0 {
203        features.clear_negotiated();
204        return (current & !status::FEATURES_OK) | status::FAILED;
205    }
206    let mut next = written & !status::NEEDS_RESET;
207    if written & status::FAILED != 0 {
208        return next | status::FAILED;
209    }
210    if written & status::FEATURES_OK != 0 {
211        if current & status::FEATURES_OK == 0 && features.negotiate().is_err() {
212            features.clear_negotiated();
213            return (next & !status::FEATURES_OK) | status::FAILED;
214        }
215        next |= status::FEATURES_OK;
216    } else {
217        features.clear_negotiated();
218    }
219    if written & status::DRIVER_OK != 0 && next & status::FEATURES_OK == 0 {
220        return next | status::FAILED;
221    }
222    next
223}
224
225/// Queue configuration or access error.
226#[derive(Debug, Clone, Copy, PartialEq, Eq)]
227pub enum QueueError {
228    /// The size is zero, not a power of two, or above [`MAX_QUEUE_SIZE`].
229    BadSize,
230    /// A table address is misaligned for its element size.
231    BadAddress,
232    /// The queue was used before `QUEUE_READY` was set.
233    NotReady,
234    /// A queue index (notification or selection) is out of range.
235    BadQueue,
236    /// A descriptor index is outside the table.
237    BadDescriptor,
238    /// A chain loops, is too long, or contains an invalid indirect table.
239    BadChain,
240    /// Guest memory could not be read or written.
241    Memory,
242}
243
244/// Guest physical memory access for the queue.
245pub trait QueueMemory {
246    /// Copies `out.len()` bytes from the guest-physical address `gpa`.
247    fn read_gpa(&mut self, gpa: u64, out: &mut [u8]) -> bool;
248    /// Copies `bytes` to the guest-physical address `gpa`.
249    fn write_gpa(&mut self, gpa: u64, bytes: &[u8]) -> bool;
250
251    /// Reads a little-endian 16-bit value.
252    fn read_u16(&mut self, gpa: u64) -> Option<u16> {
253        let mut bytes = [0u8; 2];
254        if self.read_gpa(gpa, &mut bytes) {
255            Some(u16::from_le_bytes(bytes))
256        } else {
257            None
258        }
259    }
260
261    /// Writes a little-endian 16-bit value.
262    fn write_u16(&mut self, gpa: u64, value: u16) -> bool {
263        self.write_gpa(gpa, &value.to_le_bytes())
264    }
265
266    /// Reads a little-endian 32-bit value.
267    fn read_u32(&mut self, gpa: u64) -> Option<u32> {
268        let mut bytes = [0u8; 4];
269        if self.read_gpa(gpa, &mut bytes) {
270            Some(u32::from_le_bytes(bytes))
271        } else {
272            None
273        }
274    }
275
276    /// Writes a little-endian 32-bit value.
277    fn write_u32(&mut self, gpa: u64, value: u32) -> bool {
278        self.write_gpa(gpa, &value.to_le_bytes())
279    }
280}
281
282/// One split-queue descriptor.
283#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
284pub struct Descriptor {
285    /// Guest-physical address of the buffer (or of an indirect table).
286    pub addr: u64,
287    /// Buffer length in bytes.
288    pub len: u32,
289    /// [`DESC_F_NEXT`], [`DESC_F_WRITE`], [`DESC_F_INDIRECT`].
290    pub flags: u16,
291    /// Index of the next descriptor when [`DESC_F_NEXT`] is set.
292    pub next: u16,
293}
294
295impl Descriptor {
296    /// Decodes a descriptor from its 16-byte representation.
297    pub fn decode(bytes: &[u8; 16]) -> Self {
298        Self {
299            addr: u64::from_le_bytes([
300                bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
301            ]),
302            len: u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]),
303            flags: u16::from_le_bytes([bytes[12], bytes[13]]),
304            next: u16::from_le_bytes([bytes[14], bytes[15]]),
305        }
306    }
307
308    /// Encodes the descriptor into its 16-byte representation.
309    pub fn encode(self) -> [u8; 16] {
310        let mut bytes = [0u8; 16];
311        bytes[..8].copy_from_slice(&self.addr.to_le_bytes());
312        bytes[8..12].copy_from_slice(&self.len.to_le_bytes());
313        bytes[12..14].copy_from_slice(&self.flags.to_le_bytes());
314        bytes[14..].copy_from_slice(&self.next.to_le_bytes());
315        bytes
316    }
317
318    /// True if the device writes this buffer (it is read-only for the driver).
319    pub const fn writable(self) -> bool {
320        self.flags & DESC_F_WRITE != 0
321    }
322
323    /// True if the chain continues in [`Self::next`].
324    pub const fn has_next(self) -> bool {
325        self.flags & DESC_F_NEXT != 0
326    }
327
328    /// True if [`Self::addr`] points to an indirect descriptor table.
329    pub const fn indirect(self) -> bool {
330        self.flags & DESC_F_INDIRECT != 0
331    }
332}
333
334/// One split virtqueue.
335///
336/// All addresses are guest-physical; `avail` points to the available-ring
337/// header and `used` to the used-ring header (the `ring[]` arrays follow their
338/// headers, as defined by the virtio specification).
339#[derive(Debug, Clone, Copy, PartialEq, Eq)]
340pub struct SplitQueue {
341    size: u16,
342    desc: u64,
343    avail: u64,
344    used: u64,
345    last_avail: u16,
346    last_used: u16,
347}
348
349impl SplitQueue {
350    /// Creates a queue from the three table addresses programmed by the
351    /// driver.
352    pub fn new(size: u16, desc: u64, avail: u64, used: u64) -> Result<Self, QueueError> {
353        if size == 0 || size > MAX_QUEUE_SIZE || !size.is_power_of_two() {
354            return Err(QueueError::BadSize);
355        }
356        if desc % DESCRIPTOR_SIZE != 0 || avail % 2 != 0 || used % 4 != 0 {
357            return Err(QueueError::BadAddress);
358        }
359        Ok(Self {
360            size,
361            desc,
362            avail,
363            used,
364            last_avail: 0,
365            last_used: 0,
366        })
367    }
368
369    /// Queue size (number of descriptors).
370    pub const fn size(self) -> u16 {
371        self.size
372    }
373
374    /// Guest-physical address of descriptor `index`.
375    pub fn descriptor_gpa(self, index: u16) -> Option<u64> {
376        if index >= self.size {
377            return None;
378        }
379        Some(self.desc + u64::from(index) * DESCRIPTOR_SIZE)
380    }
381
382    /// Reads one descriptor.
383    pub fn read_descriptor<M: QueueMemory + ?Sized>(
384        self,
385        memory: &mut M,
386        index: u16,
387    ) -> Result<Descriptor, QueueError> {
388        let gpa = self
389            .descriptor_gpa(index)
390            .ok_or(QueueError::BadDescriptor)?;
391        let mut bytes = [0u8; 16];
392        if !memory.read_gpa(gpa, &mut bytes) {
393            return Err(QueueError::Memory);
394        }
395        Ok(Descriptor::decode(&bytes))
396    }
397
398    /// Pops the next available chain head, or `None` when the driver has not
399    /// published anything new. The available index is advanced only when a
400    /// descriptor is actually returned.
401    pub fn pop_available<M: QueueMemory + ?Sized>(
402        &mut self,
403        memory: &mut M,
404    ) -> Result<Option<u16>, QueueError> {
405        let produced = memory.read_u16(self.avail + 2).ok_or(QueueError::Memory)?;
406        if produced == self.last_avail {
407            return Ok(None);
408        }
409        let slot = u64::from(self.last_avail % self.size);
410        let head = memory
411            .read_u16(self.avail + 4 + slot * 2)
412            .ok_or(QueueError::Memory)?;
413        if head >= self.size {
414            return Err(QueueError::BadDescriptor);
415        }
416        self.last_avail = self.last_avail.wrapping_add(1);
417        Ok(Some(head))
418    }
419
420    /// Walks the chain starting at `head`.
421    ///
422    /// One level of indirect descriptors is supported: their table is expanded
423    /// in place and the outer `NEXT` flag then continues the chain.
424    pub fn chain<M: QueueMemory + ?Sized>(
425        self,
426        memory: &mut M,
427        head: u16,
428    ) -> Result<Vec<Descriptor>, QueueError> {
429        let mut chain = Vec::new();
430        let mut index = head;
431        let mut hops = 0u32;
432        // A well-formed chain cannot be longer than the descriptor table.
433        let limit = u32::from(self.size) + 1;
434        loop {
435            if index >= self.size {
436                return Err(QueueError::BadDescriptor);
437            }
438            hops += 1;
439            if hops > limit {
440                return Err(QueueError::BadChain);
441            }
442            let descriptor = self.read_descriptor(memory, index)?;
443            if descriptor.indirect() {
444                self.expand_indirect(memory, descriptor, &mut chain)?;
445            } else {
446                chain.push(descriptor);
447            }
448            if !descriptor.has_next() {
449                return Ok(chain);
450            }
451            index = descriptor.next;
452        }
453    }
454
455    /// Expands an indirect descriptor table into `chain`.
456    fn expand_indirect<M: QueueMemory + ?Sized>(
457        self,
458        memory: &mut M,
459        indirect: Descriptor,
460        chain: &mut Vec<Descriptor>,
461    ) -> Result<(), QueueError> {
462        if indirect.len == 0 || indirect.len % DESCRIPTOR_SIZE as u32 != 0 {
463            return Err(QueueError::BadChain);
464        }
465        let count = indirect.len / DESCRIPTOR_SIZE as u32;
466        if count > u32::from(self.size) {
467            return Err(QueueError::BadChain);
468        }
469        let mut index = 0u32;
470        let mut hops = 0u32;
471        loop {
472            if index >= count {
473                return Ok(());
474            }
475            hops += 1;
476            if hops > count {
477                return Err(QueueError::BadChain);
478            }
479            let gpa = indirect.addr + u64::from(index) * DESCRIPTOR_SIZE;
480            let mut bytes = [0u8; 16];
481            if !memory.read_gpa(gpa, &mut bytes) {
482                return Err(QueueError::Memory);
483            }
484            let descriptor = Descriptor::decode(&bytes);
485            if descriptor.indirect() {
486                return Err(QueueError::BadChain);
487            }
488            chain.push(descriptor);
489            if !descriptor.has_next() {
490                return Ok(());
491            }
492            index = u32::from(descriptor.next);
493        }
494    }
495
496    /// Publishes a completed chain in the used ring.
497    ///
498    /// `written` is the number of bytes the device wrote into the chain, which
499    /// the driver reads after the used-ring entry becomes visible.
500    pub fn push_used<M: QueueMemory + ?Sized>(
501        &mut self,
502        memory: &mut M,
503        head: u16,
504        written: u32,
505    ) -> Result<(), QueueError> {
506        if head >= self.size {
507            return Err(QueueError::BadDescriptor);
508        }
509        let slot = u64::from(self.last_used % self.size);
510        let entry = self.used + 4 + slot * 8;
511        if !memory.write_u32(entry, u32::from(head)) {
512            return Err(QueueError::Memory);
513        }
514        if !memory.write_u32(entry + 4, written) {
515            return Err(QueueError::Memory);
516        }
517        let next = self.last_used.wrapping_add(1);
518        if !memory.write_u16(self.used + 2, next) {
519            return Err(QueueError::Memory);
520        }
521        self.last_used = next;
522        Ok(())
523    }
524}
525
526/// Queue-programming state as written by the driver through the transport.
527///
528/// This mirrors the four queue registers (`QUEUE_NUM`, descriptor/available/
529/// used addresses and `QUEUE_READY`) and validates them before a
530/// [`SplitQueue`] view is built. It is shared by every virtio model so that
531/// size, power-of-two and alignment rules are enforced at one place.
532#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
533pub struct QueueState {
534    /// Number of descriptors written to `QUEUE_NUM`.
535    pub num: u16,
536    /// Descriptor-table base (guest-physical).
537    pub desc: u64,
538    /// Available-ring base (guest-physical).
539    pub avail: u64,
540    /// Used-ring base (guest-physical).
541    pub used: u64,
542    /// `QUEUE_READY` was set by the driver.
543    pub ready: bool,
544}
545
546impl QueueState {
547    /// True once the driver marked the queue ready.
548    pub const fn is_ready(&self) -> bool {
549        self.ready
550    }
551
552    /// Records a new queue size.
553    ///
554    /// Rejects zero, non-power-of-two and sizes above [`MAX_QUEUE_SIZE`], and
555    /// clears `ready` because the queue must be re-programmed.
556    pub fn set_num(&mut self, num: u16) -> Result<(), QueueError> {
557        if num == 0 || num > MAX_QUEUE_SIZE || !num.is_power_of_two() {
558            return Err(QueueError::BadSize);
559        }
560        self.num = num;
561        self.ready = false;
562        Ok(())
563    }
564
565    /// Validates size and table alignments without requiring `ready`.
566    pub fn validate(&self) -> Result<(), QueueError> {
567        if self.num == 0 || self.num > MAX_QUEUE_SIZE || !self.num.is_power_of_two() {
568            return Err(QueueError::BadSize);
569        }
570        if self.desc % DESCRIPTOR_SIZE != 0 || self.avail % 2 != 0 || self.used % 4 != 0 {
571            return Err(QueueError::BadAddress);
572        }
573        Ok(())
574    }
575
576    /// Builds the [`SplitQueue`] view once the driver marked the queue ready.
577    pub fn split(&self) -> Result<SplitQueue, QueueError> {
578        if !self.ready {
579            return Err(QueueError::NotReady);
580        }
581        SplitQueue::new(self.num, self.desc, self.avail, self.used)
582    }
583}
584
585/// Validated value written to `QUEUE_NOTIFY`.
586///
587/// Every model accepts a bounded set of queues; constructing this value is the
588/// single place where an out-of-range notification is rejected.
589#[derive(Debug, Clone, Copy, PartialEq, Eq)]
590pub struct QueueNotify {
591    index: u32,
592}
593
594impl QueueNotify {
595    /// Validates `index` against the number of queues implemented by a device.
596    pub fn new(index: u32, queue_count: u32) -> Result<Self, QueueError> {
597        if index >= queue_count {
598            return Err(QueueError::BadQueue);
599        }
600        Ok(Self { index })
601    }
602
603    /// Queue index to service.
604    pub const fn index(self) -> u32 {
605        self.index
606    }
607
608    /// True if this notification targets `queue`.
609    pub const fn is(self, queue: u32) -> bool {
610        self.index == queue
611    }
612}
613
614impl SplitQueue {
615    /// Reads the available-ring flags word.
616    pub fn avail_flags<M: QueueMemory + ?Sized>(&self, memory: &mut M) -> Result<u16, QueueError> {
617        memory.read_u16(self.avail).ok_or(QueueError::Memory)
618    }
619
620    /// True when the driver set [`VIRTQ_AVAIL_F_NO_INTERRUPT`], i.e. it does
621    /// not want a used-ring interrupt for the buffers it has published.
622    pub fn no_interrupt_requested<M: QueueMemory + ?Sized>(
623        &self,
624        memory: &mut M,
625    ) -> Result<bool, QueueError> {
626        Ok(self.avail_flags(memory)? & VIRTQ_AVAIL_F_NO_INTERRUPT != 0)
627    }
628}