garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /kernel/src/drivers/virtio_blk.rs

raw

//! virtio-blk: QEMU's disks. Requests go to the device in batches of up to
//! [`SLOTS`] and complete by interrupt (`block::wait` has how a task waits
//! for them).

use super::block::{self, BLOCK, Controller, Data, Op};
use super::virtio::{self, Buffer, Queue, Transport};
use crate::mm::pages;
use crate::sync::SpinLock;
use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec::Vec;

const SECTOR: u64 = 512;
const READ: u32 = 0;
const WRITE: u32 = 1;
const FLUSH: u32 = 4;
const STATUS_OK: u8 = 0;
/// The device has a write cache, which FLUSH empties.
const F_FLUSH: u64 = 1 << 9;
/// Requests in flight at once: each takes three of the queue's descriptors
/// and a page of data.
const SLOTS: usize = 16;
/// Each slot's part of the scratch page: its header at 0, its status at 64.
const SLOT_SCRATCH: usize = 128;
const _: () = assert!(SLOTS * SLOT_SCRATCH <= crate::mm::PAGE);

/// What the interrupt handler and the disk's user share.
struct Inner {
    transport: Transport,
    queue: Queue,
    scratch: usize,
    data: [usize; SLOTS],
    /// The head descriptor of the request each slot has in flight.
    heads: [Option<u16>; SLOTS],
    outstanding: usize,
    /// The task to wake when the last request in flight completes.
    waiter: Option<usize>,
}

impl Inner {
    /// Offers `kind` on `block` as slot `slot`'s request. False when the
    /// queue is full.
    fn offer(&mut self, slot: usize, kind: u32, block: u64) -> bool {
        let scratch = self.scratch + slot * SLOT_SCRATCH;
        // SAFETY: the slot's part of the scratch page, ours alone.
        unsafe {
            let header = scratch as *mut u8;
            core::ptr::write_bytes(header, 0, 16);
            (header as *mut u32).write(kind);
            (header.add(8) as *mut u64).write(block * (BLOCK as u64 / SECTOR));
            header.add(64).write(0xff);
        }
        let header = Buffer {
            address: scratch,
            len: 16,
            device_writes: false,
        };
        let status = Buffer {
            address: scratch + 64,
            len: 1,
            device_writes: true,
        };
        let data = Buffer {
            address: self.data[slot],
            len: BLOCK,
            device_writes: kind == READ,
        };
        let head = if kind == FLUSH {
            self.queue.offer(&[header, status])
        } else {
            self.queue.offer(&[header, data, status])
        };
        match head {
            Some(head) => {
                self.heads[slot] = Some(head);
                self.outstanding += 1;
                true
            }
            None => false,
        }
    }

    fn status(&self, slot: usize) -> u8 {
        // SAFETY: the device wrote the slot's status byte.
        unsafe { ((self.scratch + slot * SLOT_SCRATCH + 64) as *const u8).read_volatile() }
    }

    /// Takes what the device has finished. True when nothing is in flight.
    fn collect(&mut self) -> bool {
        while let Some((head, _)) = self.queue.take_used() {
            if let Some(slot) = self.heads.iter().position(|h| *h == Some(head)) {
                self.heads[slot] = None;
                self.outstanding -= 1;
            }
        }
        self.outstanding == 0
    }
}

pub struct VirtioBlk {
    inner: Arc<SpinLock<Inner>>,
    sectors: u64,
    write_cache: bool,
    name: String,
}

impl Controller for VirtioBlk {
    fn transfer(&self, op: Op, blocks: &[u64], mut data: Data) -> bool {
        let kind = match op {
            Op::Read => READ,
            Op::Write => WRITE,
            Op::Flush => FLUSH,
        };
        let mut ok = true;
        let mut at = 0;
        while at < blocks.len() {
            let submitted = {
                let mut inner = self.inner.lock();
                let mut n = 0;
                while n < SLOTS && at + n < blocks.len() {
                    if let Data::From(from) = &data {
                        // SAFETY: the slot's data page, ours while the request is not in flight.
                        unsafe {
                            core::ptr::copy_nonoverlapping(
                                from[at + n].as_ptr(),
                                inner.data[n] as *mut u8,
                                BLOCK,
                            )
                        };
                    }
                    if !inner.offer(n, kind, blocks[at + n]) {
                        break;
                    }
                    n += 1;
                }
                n
            };
            assert!(submitted > 0, "the disk's queue holds no request");
            block::wait(
                &self.inner,
                |i| &mut i.waiter,
                |i| i.outstanding == 0 || i.collect(),
            );
            let inner = self.inner.lock();
            for n in 0..submitted {
                if let Data::Into(into) = &mut data {
                    // SAFETY: the device filled the slot's data page.
                    unsafe {
                        core::ptr::copy_nonoverlapping(
                            inner.data[n] as *const u8,
                            into[at + n].as_mut_ptr(),
                            BLOCK,
                        )
                    };
                }
                ok &= inner.status(n) == STATUS_OK;
            }
            drop(inner);
            at += submitted;
        }
        ok
    }

    fn blocks(&self) -> u64 {
        self.sectors * SECTOR / BLOCK as u64
    }

    fn write_cache(&self) -> bool {
        self.write_cache
    }

    fn name(&self) -> &str {
        &self.name
    }

    fn model(&self) -> &str {
        "virtio-blk"
    }

    fn whole_disk_file_system(&self) -> bool {
        true
    }

    fn reset(&self) {
        let inner = self.inner.lock();
        assert_eq!(inner.outstanding, 0, "a disk request outstanding at a hand-over");
        inner.transport.reset();
    }
}

/// Every device, by its interrupt, for the handler.
static DEVICES: SpinLock<Vec<(u32, Arc<SpinLock<Inner>>)>> = SpinLock::new(Vec::new());

/// Sets up every virtio-blk disk.
pub fn find() -> Vec<Arc<dyn Controller>> {
    let mut found: Vec<Arc<dyn Controller>> = Vec::new();
    for transport in virtio::find(virtio::device::BLOCK) {
        let Some(agreed) = transport.begin(F_FLUSH) else {
            continue;
        };
        let sectors = u64::from(transport.config_u32(0)) | u64::from(transport.config_u32(4)) << 32;
        let queue = Queue::new(transport, 0);
        transport.ready();
        let Some(scratch) = pages::alloc(0) else { break };
        let mut data = [0; SLOTS];
        for page in &mut data {
            let Some(p) = pages::alloc(0) else { break };
            *page = p;
        }
        if data.contains(&0) {
            break;
        }
        let inner = Arc::new(SpinLock::new(Inner {
            transport,
            queue,
            scratch,
            data,
            heads: [None; SLOTS],
            outstanding: 0,
            waiter: None,
        }));
        DEVICES.lock().push((transport.intid, inner.clone()));
        // Only now: an interrupt before the device is listed would find no one.
        block::route_interrupt(transport.intid);
        found.push(Arc::new(VirtioBlk {
            inner,
            sectors,
            write_cache: agreed & F_FLUSH != 0,
            name: alloc::format!("vd{}", (b'a' + found.len() as u8) as char),
        }));
    }
    found
}

/// A disk's interrupt: its requests completed. False if `intid` is no disk's.
pub fn interrupt(intid: u32) -> bool {
    let devices: Vec<_> = DEVICES
        .lock()
        .iter()
        .filter(|(i, _)| *i == intid)
        .map(|(_, d)| d.clone())
        .collect();
    for device in &devices {
        let waiter = {
            let mut inner = device.lock();
            inner.transport.acknowledge();
            if inner.collect() {
                inner.waiter.take()
            } else {
                None
            }
        };
        block::wake(waiter);
    }
    !devices.is_empty()
}