garage44.eu/jeroen/pinnacle

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

.. /kernel/src/drivers/nvme.rs

raw

//! NVMe (NVM Express 2.0): the disks of most laptops and PCs, on PCI
//! (class 01:08:02). One admin queue to set the controller up and ask what
//! it holds, one I/O queue pair for the requests; each namespace it has is
//! a disk (`nvme0n1`). Requests go in batches of up to [`SLOTS`], one
//! 4 KiB block each, and complete by interrupt (MSI-X on a PC, INTx on
//! ARM), as `block::wait` has it.

use super::block::{self, BLOCK, Controller, Data, Op};
use crate::mm::pages;
use crate::mmu::physical;
use crate::println;
use crate::sync::SpinLock;
use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::sync::atomic::{Ordering, fence};

const CLASS: u32 = 0x01_08_02;

const REG_CAP: usize = 0x00;
const REG_VS: usize = 0x08;
const REG_INTMC: usize = 0x10;
const REG_CC: usize = 0x14;
const REG_CSTS: usize = 0x1c;
const REG_AQA: usize = 0x24;
const REG_ASQ: usize = 0x28;
const REG_ACQ: usize = 0x30;
const DOORBELLS: usize = 0x1000;

const CC_ENABLE: u32 = 1;
/// 64-byte submission and 16-byte completion entries.
const CC_ENTRY_SIZES: u32 = 6 << 16 | 4 << 20;
const CSTS_READY: u32 = 1;
const CSTS_FATAL: u32 = 1 << 1;

const ADMIN_CREATE_SQ: u8 = 0x01;
const ADMIN_CREATE_CQ: u8 = 0x05;
const ADMIN_IDENTIFY: u8 = 0x06;
const ADMIN_SET_FEATURES: u8 = 0x09;
const IO_FLUSH: u8 = 0x00;
const IO_WRITE: u8 = 0x01;
const IO_READ: u8 = 0x02;

/// Entries in each queue: a page of submissions (64 bytes each).
const ENTRIES: usize = 64;
/// Requests in flight at once, each with a page of data.
const SLOTS: usize = 32;

/// A submission and its completion queue, in a page each.
struct QueuePair {
    id: u16,
    sq: usize,
    cq: usize,
    tail: u16,
    head: u16,
    phase: bool,
}

impl QueuePair {
    fn new(id: u16) -> Option<QueuePair> {
        let (sq, cq) = (pages::alloc(0)?, pages::alloc(0)?);
        // SAFETY: two fresh pages, ours.
        unsafe {
            core::ptr::write_bytes(sq as *mut u8, 0, crate::mm::PAGE);
            core::ptr::write_bytes(cq as *mut u8, 0, crate::mm::PAGE);
        }
        Some(QueuePair {
            id,
            sq,
            cq,
            tail: 0,
            head: 0,
            phase: true,
        })
    }
}

/// A command, as its 16 double words.
#[derive(Clone, Copy, Default)]
struct Command {
    opcode: u8,
    nsid: u32,
    prp1: u64,
    cdw10: u32,
    cdw11: u32,
    cdw12: u32,
}

/// The controller: its registers, its queues, the requests in flight.
struct Inner {
    regs: usize,
    stride: usize,
    admin: QueuePair,
    io: Option<QueuePair>,
    /// Which slot's request each command ID is (the ID is the slot), and
    /// the status each completed with.
    busy: [bool; SLOTS],
    status: [u16; SLOTS],
    outstanding: usize,
    data: [usize; SLOTS],
    waiter: Option<usize>,
    /// The admin command in flight's status, once completed.
    admin_done: Option<u16>,
}

impl Inner {
    fn read32(&self, offset: usize) -> u32 {
        // SAFETY: the controller's registers, in its BAR.
        unsafe { ((self.regs + offset) as *const u32).read_volatile() }
    }

    fn write32(&self, offset: usize, value: u32) {
        // SAFETY: as in `read32`.
        unsafe { ((self.regs + offset) as *mut u32).write_volatile(value) }
    }

    fn write64(&self, offset: usize, value: u64) {
        self.write32(offset, value as u32);
        self.write32(offset + 4, (value >> 32) as u32);
    }

    fn sq_doorbell(&self, q: u16) -> usize {
        DOORBELLS + (2 * q as usize) * self.stride
    }

    fn cq_doorbell(&self, q: u16) -> usize {
        DOORBELLS + (2 * q as usize + 1) * self.stride
    }

    /// Puts `command` with ID `id` on queue `admin` or the I/O one, without
    /// ringing its doorbell.
    fn push(&mut self, admin: bool, id: u16, c: Command) {
        let q = if admin {
            &mut self.admin
        } else {
            self.io.as_mut().unwrap()
        };
        let at = q.sq + q.tail as usize * 64;
        let mut words = [0u32; 16];
        words[0] = u32::from(c.opcode) | u32::from(id) << 16;
        words[1] = c.nsid;
        words[6] = c.prp1 as u32;
        words[7] = (c.prp1 >> 32) as u32;
        words[10] = c.cdw10;
        words[11] = c.cdw11;
        words[12] = c.cdw12;
        // SAFETY: the queue's next free entry, which the device reads only
        // once the doorbell says so.
        unsafe { core::ptr::copy_nonoverlapping(words.as_ptr(), at as *mut u32, 16) };
        q.tail = (q.tail + 1) % ENTRIES as u16;
    }

    fn ring(&self, admin: bool) {
        fence(Ordering::SeqCst);
        let q = if admin {
            &self.admin
        } else {
            self.io.as_ref().unwrap()
        };
        self.write32(self.sq_doorbell(q.id), u32::from(q.tail));
    }

    /// The admin queue pair, or the I/O one once it is made.
    fn queue(&mut self, admin: bool) -> Option<&mut QueuePair> {
        if admin {
            Some(&mut self.admin)
        } else {
            self.io.as_mut()
        }
    }

    /// Takes every completion waiting on both queues. True when one came.
    fn collect(&mut self) -> bool {
        let mut any = false;
        for admin in [true, false] {
            while let Some(q) = self.queue(admin) {
                let at = q.cq + q.head as usize * 16;
                // SAFETY: the completion queue's entry at its head.
                let (status, id) = unsafe {
                    (
                        ((at + 14) as *const u16).read_volatile(),
                        ((at + 12) as *const u16).read_volatile(),
                    )
                };
                if (status & 1 == 1) != q.phase {
                    break;
                }
                fence(Ordering::SeqCst);
                q.head = (q.head + 1) % ENTRIES as u16;
                if q.head == 0 {
                    q.phase = !q.phase;
                }
                let (qid, head) = (q.id, q.head);
                self.write32(self.cq_doorbell(qid), u32::from(head));
                any = true;
                if admin {
                    self.admin_done = Some(status >> 1);
                } else if let Some(slot) = Some(id as usize).filter(|&s| s < SLOTS && self.busy[s]) {
                    self.busy[slot] = false;
                    self.status[slot] = status >> 1;
                    self.outstanding -= 1;
                }
            }
        }
        any
    }
}

/// Runs one admin command and waits for it, as the boot does. Its status
/// (0: success).
fn admin(inner: &Arc<SpinLock<Inner>>, c: Command) -> u16 {
    {
        let mut i = inner.lock();
        i.admin_done = None;
        i.push(true, 0, c);
        i.ring(true);
    }
    let deadline = crate::timer::now_ms() + 5_000;
    loop {
        let mut i = inner.lock();
        i.collect();
        if let Some(status) = i.admin_done.take() {
            return status;
        }
        drop(i);
        if crate::timer::now_ms() > deadline {
            return u16::MAX;
        }
        core::hint::spin_loop();
    }
}

/// One namespace: a disk.
pub struct Namespace {
    inner: Arc<SpinLock<Inner>>,
    nsid: u32,
    /// log2 of its logical block's size.
    lba_shift: u32,
    lbas: u64,
    name: String,
    model: String,
}

impl Namespace {
    fn lbas_per_block(&self) -> u64 {
        BLOCK as u64 >> self.lba_shift
    }
}

impl Controller for Namespace {
    fn transfer(&self, op: Op, blocks: &[u64], mut data: Data) -> bool {
        let opcode = match op {
            Op::Read => IO_READ,
            Op::Write => IO_WRITE,
            Op::Flush => IO_FLUSH,
        };
        let mut ok = true;
        let mut at = 0;
        while at < blocks.len() {
            let n = SLOTS.min(blocks.len() - at);
            {
                let mut i = self.inner.lock();
                for k in 0..n {
                    if let Data::From(from) = &data {
                        // SAFETY: the slot's data page, ours while no request is in flight.
                        unsafe {
                            core::ptr::copy_nonoverlapping(from[at + k].as_ptr(), i.data[k] as *mut u8, BLOCK)
                        };
                    }
                    let lba = blocks[at + k] * self.lbas_per_block();
                    let command = Command {
                        opcode,
                        nsid: self.nsid,
                        prp1: physical(i.data[k]) as u64,
                        cdw10: lba as u32,
                        cdw11: (lba >> 32) as u32,
                        cdw12: (self.lbas_per_block() - 1) as u32,
                    };
                    i.busy[k] = true;
                    i.outstanding += 1;
                    i.push(false, k as u16, command);
                }
                i.ring(false);
            }
            block::wait(
                &self.inner,
                |i| &mut i.waiter,
                |i| {
                    i.collect();
                    i.outstanding == 0
                },
            );
            let i = self.inner.lock();
            for k in 0..n {
                if let Data::Into(into) = &mut data {
                    // SAFETY: the device filled the slot's data page.
                    unsafe {
                        core::ptr::copy_nonoverlapping(
                            i.data[k] as *const u8,
                            into[at + k].as_mut_ptr(),
                            BLOCK,
                        )
                    };
                }
                ok &= i.status[k] == 0;
            }
            drop(i);
            at += n;
        }
        ok
    }

    fn blocks(&self) -> u64 {
        self.lbas / self.lbas_per_block()
    }

    fn sector(&self) -> u64 {
        1 << self.lba_shift
    }

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

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

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

    fn reset(&self) {
        let i = self.inner.lock();
        i.write32(REG_CC, i.read32(REG_CC) & !CC_ENABLE);
    }
}

/// Every controller, with its interrupt, for the handler.
static CONTROLLERS: SpinLock<Vec<(u32, Arc<SpinLock<Inner>>)>> = SpinLock::new(Vec::new());

/// Text from an identify page: ASCII, padded with spaces.
fn text(bytes: &[u8]) -> String {
    String::from(String::from_utf8_lossy(bytes).trim())
}

/// Sets up every NVMe controller and returns its namespaces.
pub fn find() -> Vec<Arc<dyn Controller>> {
    let mut found: Vec<Arc<dyn Controller>> = Vec::new();
    for (n, f) in crate::pci::find_class(CLASS).into_iter().enumerate() {
        crate::pci::claim(&f, "nvme", crate::device::Class::Storage);
        let Some(regs) = f.bar_address(0, 0) else {
            println!("nvme{n}: no registers");
            continue;
        };
        let Some(intid) = f.take_interrupt() else {
            println!("nvme{n}: no interrupt");
            continue;
        };
        match start(n, regs, intid) {
            Some(namespaces) => found.extend(namespaces),
            None => println!("nvme{n}: did not start"),
        }
    }
    found
}

fn start(n: usize, regs: usize, intid: u32) -> Option<Vec<Arc<dyn Controller>>> {
    let mut data = [0usize; SLOTS];
    for page in &mut data {
        *page = pages::alloc(0)?;
    }
    let mut inner = Inner {
        regs,
        stride: 4,
        admin: QueuePair::new(0)?,
        io: None,
        busy: [false; SLOTS],
        status: [0; SLOTS],
        outstanding: 0,
        data,
        waiter: None,
        admin_done: None,
    };
    let cap = u64::from(inner.read32(REG_CAP)) | u64::from(inner.read32(REG_CAP + 4)) << 32;
    inner.stride = 4 << ((cap >> 32) & 0xf);
    let max_entries = (cap & 0xffff) as usize + 1;
    let timeout = ((cap >> 24) & 0xff).max(1) * 500;
    if max_entries < ENTRIES || cap & (1 << 37) == 0 {
        println!("nvme{n}: queues too short, or no NVM command set");
        return None;
    }
    let version = inner.read32(REG_VS);
    // Off first, as a firmware may have left it on.
    let ready = |inner: &Inner, want: bool| {
        let deadline = crate::timer::now_ms() + timeout;
        loop {
            let csts = inner.read32(REG_CSTS);
            if csts & CSTS_FATAL != 0 {
                return false;
            }
            if (csts & CSTS_READY != 0) == want {
                return true;
            }
            if crate::timer::now_ms() > deadline {
                return false;
            }
            core::hint::spin_loop();
        }
    };
    inner.write32(REG_CC, inner.read32(REG_CC) & !CC_ENABLE);
    if !ready(&inner, false) {
        return None;
    }
    inner.write32(REG_AQA, ((ENTRIES as u32 - 1) << 16) | (ENTRIES as u32 - 1));
    inner.write64(REG_ASQ, physical(inner.admin.sq) as u64);
    inner.write64(REG_ACQ, physical(inner.admin.cq) as u64);
    inner.write32(REG_CC, CC_ENTRY_SIZES | CC_ENABLE);
    if !ready(&inner, true) {
        return None;
    }
    // Every interrupt unmasked (INTx; MSI-X ignores this).
    inner.write32(REG_INTMC, 1);
    let inner = Arc::new(SpinLock::new(inner));
    // Listed before its first command: its completions interrupt.
    CONTROLLERS.lock().push((intid, inner.clone()));
    let page = pages::alloc(0)?;
    let identify = |cns: u32, nsid: u32| {
        // SAFETY: a page of ours, for the device to fill.
        unsafe { core::ptr::write_bytes(page as *mut u8, 0, crate::mm::PAGE) };
        let status = admin(
            &inner,
            Command {
                opcode: ADMIN_IDENTIFY,
                nsid,
                prp1: physical(page) as u64,
                cdw10: cns,
                ..Command::default()
            },
        );
        // SAFETY: the page the device filled.
        (status == 0).then(|| unsafe { core::slice::from_raw_parts(page as *const u8, 4096) }.to_vec())
    };
    let controller = identify(1, 0)?;
    let model = text(&controller[24..64]);
    let list = identify(2, 0)?;
    // One queue pair for I/O: asked for, then made, its completions first.
    admin(
        &inner,
        Command {
            opcode: ADMIN_SET_FEATURES,
            cdw10: 0x07,
            ..Command::default()
        },
    );
    let io = QueuePair::new(1)?;
    let (sq, cq) = (physical(io.sq) as u64, physical(io.cq) as u64);
    inner.lock().io = Some(io);
    let size = (ENTRIES as u32 - 1) << 16 | 1;
    // Physically contiguous, interrupts on, vector 0.
    if admin(
        &inner,
        Command {
            opcode: ADMIN_CREATE_CQ,
            prp1: cq,
            cdw10: size,
            cdw11: 0b11,
            ..Command::default()
        },
    ) != 0
        || admin(
            &inner,
            Command {
                opcode: ADMIN_CREATE_SQ,
                prp1: sq,
                cdw10: size,
                cdw11: 1 << 16 | 1,
                ..Command::default()
            },
        ) != 0
    {
        println!("nvme{n}: its I/O queues were refused");
        return None;
    }
    block::route_interrupt(intid);
    let mut namespaces: Vec<Arc<dyn Controller>> = Vec::new();
    for nsid in list.as_chunks::<4>().0.iter().map(|&c| u32::from_le_bytes(c)) {
        if nsid == 0 {
            break;
        }
        let Some(ns) = identify(0, nsid) else { continue };
        let lbas = u64::from_le_bytes(ns[0..8].try_into().unwrap());
        let format = usize::from(ns[26] & 0xf);
        let lba_shift = u32::from(ns[128 + 4 * format + 2]);
        // Metadata beside each block is not something a file system wants.
        let metadata = u16::from_le_bytes([ns[128 + 4 * format], ns[128 + 4 * format + 1]]);
        if !(9..=12).contains(&lba_shift) || metadata != 0 {
            println!("nvme{n}n{nsid}: blocks of 2^{lba_shift} bytes with metadata {metadata}, left alone");
            continue;
        }
        namespaces.push(Arc::new(Namespace {
            inner: inner.clone(),
            nsid,
            lba_shift,
            lbas,
            name: alloc::format!("nvme{n}n{nsid}"),
            model: model.clone(),
        }));
    }
    pages::free(page, 0);
    println!(
        "nvme{n}: {model}, NVMe {}.{}, {} namespace{}",
        version >> 16,
        (version >> 8) & 0xff,
        namespaces.len(),
        if namespaces.len() == 1 { "" } else { "s" }
    );
    Some(namespaces)
}

/// A controller's interrupt: its completions taken. False if `intid` is no
/// controller's.
pub fn interrupt(intid: u32) -> bool {
    let controllers: Vec<_> = CONTROLLERS
        .lock()
        .iter()
        .filter(|(i, _)| *i == intid)
        .map(|(_, c)| c.clone())
        .collect();
    for c in &controllers {
        let waiter = {
            let mut i = c.lock();
            i.collect();
            if i.outstanding == 0 { i.waiter.take() } else { None }
        };
        block::wake(waiter);
    }
    !controllers.is_empty()
}