//! virtio (version 1, "modern") over either transport: MMIO windows the //! device tree lists (`virtio,mmio`, most of them empty), as QEMU's `virt` //! machine offers devices, and PCI functions (vendor 0x1af4), as a PC and //! QEMU's 3D GPU do. A driver claims those with its device ID behind them, //! negotiates features and talks to it through split virtqueues in //! ordinary RAM; which transport it is, it never sees. // The block and input drivers use what the display does not yet. #![allow(dead_code)] use crate::device::Class; use crate::mm::{PAGE, pages}; use crate::mmu::physical; use core::sync::atomic::{Ordering, fence}; const MAGIC: u32 = 0x7472_6976; // "virt" const REG_MAGIC: usize = 0x000; const REG_VERSION: usize = 0x004; const REG_DEVICE_ID: usize = 0x008; const REG_DEVICE_FEATURES: usize = 0x010; const REG_DEVICE_FEATURES_SEL: usize = 0x014; const REG_DRIVER_FEATURES: usize = 0x020; const REG_DRIVER_FEATURES_SEL: usize = 0x024; const REG_QUEUE_SEL: usize = 0x030; const REG_QUEUE_NUM_MAX: usize = 0x034; const REG_QUEUE_NUM: usize = 0x038; const REG_QUEUE_READY: usize = 0x044; const REG_QUEUE_NOTIFY: usize = 0x050; const REG_INTERRUPT_STATUS: usize = 0x060; const REG_INTERRUPT_ACK: usize = 0x064; const REG_STATUS: usize = 0x070; const REG_QUEUE_DESC: usize = 0x080; const REG_QUEUE_DRIVER: usize = 0x090; const REG_QUEUE_DEVICE: usize = 0x0a0; pub const REG_CONFIG: usize = 0x100; const STATUS_ACKNOWLEDGE: u32 = 1; const STATUS_DRIVER: u32 = 2; const STATUS_DRIVER_OK: u32 = 4; const STATUS_FEATURES_OK: u32 = 8; /// The one feature every modern device must be offered back. const F_VERSION_1: u64 = 1 << 32; pub mod device { pub const NET: u32 = 1; pub const BLOCK: u32 = 2; pub const CONSOLE: u32 = 3; pub const RNG: u32 = 4; pub const GPU: u32 = 16; pub const INPUT: u32 = 18; pub const SOUND: u32 = 25; } /// One device's registers: a virtio-mmio window, or a virtio-pci /// function's structures in its BARs (common configuration, notification, /// interrupt status, device configuration). #[derive(Clone, Copy)] pub struct Transport { kind: Kind, /// Its interrupt (an INTID on ARM; an MSI-X vector on a PC). pub intid: u32, } #[derive(Clone, Copy)] enum Kind { Mmio(usize), Pci { common: usize, notify: usize, multiplier: u32, isr: usize, device: usize, /// Its queues signal through MSI-X entry 0, not INTx. message: bool, /// A shared memory region (virtio 1.2, 4.1.4.7): its id, kernel and /// physical addresses, and length. One is kept: a GPU's host-visible /// memory, where Venus maps what the host's Vulkan allocates. shared: Option<(u8, usize, u64, u64)>, }, } // virtio-pci's common configuration (virtio 1.x, 4.1.4.3). const PCI_DEVICE_FEATURE_SELECT: usize = 0; const PCI_DEVICE_FEATURE: usize = 4; const PCI_DRIVER_FEATURE_SELECT: usize = 8; const PCI_DRIVER_FEATURE: usize = 12; const PCI_CONFIG_MSIX_VECTOR: usize = 16; const PCI_DEVICE_STATUS: usize = 20; const PCI_QUEUE_SELECT: usize = 22; const PCI_QUEUE_SIZE: usize = 24; const PCI_QUEUE_MSIX_VECTOR: usize = 26; const PCI_QUEUE_ENABLE: usize = 28; const PCI_QUEUE_NOTIFY_OFF: usize = 30; const PCI_QUEUE_DESC: usize = 32; const PCI_QUEUE_DRIVER: usize = 40; const PCI_QUEUE_DEVICE: usize = 48; /// No MSI-X vector. const NO_VECTOR: u16 = 0xffff; fn read8(at: usize) -> u8 { // SAFETY: a device register, mapped uncached. unsafe { (at as *const u8).read_volatile() } } fn write8(at: usize, value: u8) { // SAFETY: as in `read8`. unsafe { (at as *mut u8).write_volatile(value) } } fn read16(at: usize) -> u16 { // SAFETY: as in `read8`. unsafe { (at as *const u16).read_volatile() } } fn write16(at: usize, value: u16) { // SAFETY: as in `read8`. unsafe { (at as *mut u16).write_volatile(value) } } fn read32(at: usize) -> u32 { // SAFETY: as in `read8`. unsafe { (at as *const u32).read_volatile() } } fn write32(at: usize, value: u32) { // SAFETY: as in `read8`. unsafe { (at as *mut u32).write_volatile(value) } } impl Transport { fn mmio(&self) -> usize { match self.kind { Kind::Mmio(base) => base, Kind::Pci { .. } => unreachable!("an MMIO register of a PCI device"), } } fn read(&self, offset: usize) -> u32 { read32(self.mmio() + offset) } fn write(&self, offset: usize, value: u32) { write32(self.mmio() + offset, value) } fn status(&self) -> u32 { match self.kind { Kind::Mmio(_) => self.read(REG_STATUS), Kind::Pci { common, .. } => u32::from(read8(common + PCI_DEVICE_STATUS)), } } fn set_status(&self, status: u32) { match self.kind { Kind::Mmio(_) => self.write(REG_STATUS, status), Kind::Pci { common, .. } => write8(common + PCI_DEVICE_STATUS, status as u8), } } fn features(&self, half: u32) -> u32 { match self.kind { Kind::Mmio(_) => { self.write(REG_DEVICE_FEATURES_SEL, half); self.read(REG_DEVICE_FEATURES) } Kind::Pci { common, .. } => { write32(common + PCI_DEVICE_FEATURE_SELECT, half); read32(common + PCI_DEVICE_FEATURE) } } } fn set_features(&self, half: u32, value: u32) { match self.kind { Kind::Mmio(_) => { self.write(REG_DRIVER_FEATURES_SEL, half); self.write(REG_DRIVER_FEATURES, value); } Kind::Pci { common, .. } => { write32(common + PCI_DRIVER_FEATURE_SELECT, half); write32(common + PCI_DRIVER_FEATURE, value); } } } /// Whether it is a PCI function (a virtio-mmio window otherwise). pub fn is_pci(&self) -> bool { matches!(self.kind, Kind::Pci { .. }) } /// Its shared memory region `id`: kernel address, physical address and /// length (PCI only). pub fn shared_memory(&self, id: u8) -> Option<(usize, u64, u64)> { match self.kind { Kind::Pci { shared: Some((i, at, physical, len)), .. } if i == id => Some((at, physical, len)), _ => None, } } /// The features the device offers, read without resetting it (a driver /// may be using it). pub fn offered(&self) -> u64 { u64::from(self.features(0)) | u64::from(self.features(1)) << 32 } /// A 32-bit word of the device's own configuration, at `offset`. pub fn config_u32(&self, offset: usize) -> u32 { match self.kind { Kind::Mmio(_) => self.read(REG_CONFIG + offset), Kind::Pci { device, .. } => read32(device + offset), } } /// Writes a 32-bit word of the device's own configuration, at `offset`. pub fn set_config_u32(&self, offset: usize, value: u32) { match self.kind { Kind::Mmio(_) => self.write(REG_CONFIG + offset, value), Kind::Pci { device, .. } => write32(device + offset, value), } } /// Configuration changes interrupt as the queues do (on MMIO and with /// INTx they always do; with MSI-X, through the queues' entry 0). pub fn signal_config_changes(&self) { if let Kind::Pci { common, message: true, .. } = self.kind { write16(common + PCI_CONFIG_MSIX_VECTOR, 0); } } /// Resets the device and negotiates `wanted` of its features (plus /// VERSION_1). Returns the features agreed, or `None` if the device is /// not a modern one. pub fn begin(&self, wanted: u64) -> Option { self.set_status(0); // A PCI device says when its reset is done by reading 0. while self.status() != 0 { core::hint::spin_loop(); } self.set_status(STATUS_ACKNOWLEDGE); self.set_status(STATUS_ACKNOWLEDGE | STATUS_DRIVER); let offered = u64::from(self.features(0)) | u64::from(self.features(1)) << 32; let agreed = offered & (wanted | F_VERSION_1); if agreed & F_VERSION_1 == 0 { return None; } self.set_features(0, agreed as u32); self.set_features(1, (agreed >> 32) as u32); let status = STATUS_ACKNOWLEDGE | STATUS_DRIVER | STATUS_FEATURES_OK; self.set_status(status); // Configuration changes signal nothing; the queues say what they use. if let Kind::Pci { common, .. } = self.kind { write16(common + PCI_CONFIG_MSIX_VECTOR, NO_VECTOR); } (self.status() & STATUS_FEATURES_OK != 0).then_some(agreed) } /// Stops the device: it forgets its queues, and uses no more memory and /// raises no more interrupts until a driver sets it up again (another /// kernel's, `chain`). pub fn reset(&self) { self.set_status(0); while self.status() != 0 { core::hint::spin_loop(); } } /// The device may run: its queues are set up. pub fn ready(&self) { self.set_status(self.status() | STATUS_DRIVER_OK); } /// Acknowledges the device's interrupt (reading a PCI device's ISR /// clears it). pub fn acknowledge(&self) { match self.kind { Kind::Mmio(_) => { let status = self.read(REG_INTERRUPT_STATUS); self.write(REG_INTERRUPT_ACK, status); } Kind::Pci { isr, .. } => { read8(isr); } } } /// Selects queue `index` and returns its largest size (0: no queue). fn queue_max(&self, index: u32) -> u32 { match self.kind { Kind::Mmio(_) => { self.write(REG_QUEUE_SEL, index); self.read(REG_QUEUE_NUM_MAX) } Kind::Pci { common, .. } => { write16(common + PCI_QUEUE_SELECT, index as u16); u32::from(read16(common + PCI_QUEUE_SIZE)) } } } /// Sets the selected queue's size and rings, and enables it. fn queue_set(&self, size: u16, descriptors: u64, driver: u64, device: u64) { match self.kind { Kind::Mmio(_) => { self.write(REG_QUEUE_NUM, u32::from(size)); for (register, physical) in [ (REG_QUEUE_DESC, descriptors), (REG_QUEUE_DRIVER, driver), (REG_QUEUE_DEVICE, device), ] { self.write(register, physical as u32); self.write(register + 4, (physical >> 32) as u32); } self.write(REG_QUEUE_READY, 1); } Kind::Pci { common, message, .. } => { write16(common + PCI_QUEUE_SIZE, size); for (register, physical) in [ (PCI_QUEUE_DESC, descriptors), (PCI_QUEUE_DRIVER, driver), (PCI_QUEUE_DEVICE, device), ] { write32(common + register, physical as u32); write32(common + register + 4, (physical >> 32) as u32); } write16( common + PCI_QUEUE_MSIX_VECTOR, if message { 0 } else { NO_VECTOR }, ); write16(common + PCI_QUEUE_ENABLE, 1); } } } /// Tells the device queue `index` has new buffers. fn notify(&self, index: u32) { match self.kind { Kind::Mmio(_) => self.write(REG_QUEUE_NOTIFY, index), Kind::Pci { common, notify, multiplier, .. } => { write16(common + PCI_QUEUE_SELECT, index as u16); let offset = usize::from(read16(common + PCI_QUEUE_NOTIFY_OFF)) * multiplier as usize; write16(notify + offset, index as u16); } } } } /// Every transport holding a device of `id`: the device tree's virtio-mmio /// windows, in transport order, then PCI's virtio functions. pub fn find(id: u32) -> impl Iterator { let (driver, class) = match id { device::NET => ("virtio-net", Class::Network), device::BLOCK => ("virtio-blk", Class::Storage), device::CONSOLE => ("virtio-console", Class::Serial), device::RNG => ("virtio-rng", Class::Random), device::GPU => ("virtio-gpu", Class::Display), device::INPUT => ("virtio-input", Class::Input), device::SOUND => ("virtio-sound", Class::Sound), _ => ("virtio", Class::Other), }; let mmio = crate::device::claim("virtio,mmio", driver, class, |d| { d.base().is_some_and(|base| { read32(base + REG_MAGIC) == MAGIC && read32(base + REG_VERSION) == 2 && read32(base + REG_DEVICE_ID) == id }) }) .into_iter() .filter_map(|d| { Some(Transport { kind: Kind::Mmio(d.base()?), intid: *d.interrupts.first()?, }) }); // A modern virtio-pci device's ID is 0x1040 plus its virtio ID; a // transitional one (QEMU's default on a root bus) has the older ID of // its kind, and the modern structures too. let transitional = match id { device::NET => Some(0x1000), device::BLOCK => Some(0x1001), device::CONSOLE => Some(0x1003), device::RNG => Some(0x1005), _ => None, }; let modern = 0x1040 + id as u16; let pci = crate::pci::find(0x1af4, 0x1000..=modern) .into_iter() .filter(move |f| f.id == modern || Some(f.id) == transitional) .filter_map(move |f| { let transport = pci_transport(&f)?; crate::pci::claim(&f, driver, class); Some(transport) }); mmio.chain(pci) } /// Each PCI function's transport, made once: making one programs the /// function's MSI-X entry with a fresh vector, which a second search for /// the same device (the 3D driver's, after the 2D one's) must not redo, or /// the first driver's interrupts go to a vector no one handles. static PCI_TRANSPORTS: crate::sync::SpinLock> = crate::sync::SpinLock::new(alloc::vec::Vec::new()); /// A PCI function's bus, device and function. type Bdf = (u8, u8, u8); /// A virtio-pci function's structures, from its vendor capabilities, and /// its interrupt: a message where the architecture takes them, else INTx. fn pci_transport(f: &crate::pci::Function) -> Option { let key = (f.bus, f.device, f.function); if let Some(&(_, transport)) = PCI_TRANSPORTS.lock().iter().find(|(k, _)| *k == key) { return Some(transport); } let transport = make_pci_transport(f)?; PCI_TRANSPORTS.lock().push((key, transport)); Some(transport) } fn make_pci_transport(f: &crate::pci::Function) -> Option { const VENDOR: u8 = 0x09; const COMMON: u8 = 1; const NOTIFY: u8 = 2; const ISR: u8 = 3; const DEVICE: u8 = 4; const SHARED_MEMORY: u8 = 8; let (mut common, mut notify, mut isr, mut device, mut multiplier) = (None, None, None, None, 0); let mut shared = None; for (_, cap) in f.capabilities().filter(|&(id, _)| id == VENDOR) { let at = f.bar_address(usize::from(f.read8(cap + 4)), u64::from(f.read32(cap + 8))); match f.read8(cap + 3) { COMMON => common = at, NOTIFY => { notify = at; multiplier = f.read32(cap + 16); } ISR => isr = at, DEVICE => device = at, SHARED_MEMORY => { // virtio_pci_cap64: the BAR's offset and the length, each // with a high half after the cap's own fields. let bar = usize::from(f.read8(cap + 4)); let id = f.read8(cap + 5); let offset = u64::from(f.read32(cap + 8)) | u64::from(f.read32(cap + 16)) << 32; let len = u64::from(f.read32(cap + 12)) | u64::from(f.read32(cap + 20)) << 32; let at = f.bar_address(bar, offset); if let (Some(at), Some(&(base, _))) = (at, f.bars.get(bar)) { shared = Some((id, at, base + offset, len)); } } _ => {} } } let (intid, message) = match crate::gic::message_interrupt() { Some((address, data, vector)) if f.msix(0, address, data) => (vector, true), _ => (f.intx?, false), }; f.enable(!message); Some(Transport { kind: Kind::Pci { common: common?, notify: notify?, multiplier, isr: isr?, device: device.unwrap_or(0), message, shared, }, intid, }) } #[repr(C)] #[derive(Clone, Copy)] struct Descriptor { address: u64, len: u32, flags: u16, next: u16, } const DESC_NEXT: u16 = 1; const DESC_WRITE: u16 = 2; /// A buffer handed to the device: its kernel address and length, and /// whether the device writes it (a response) or reads it (a request). #[derive(Clone, Copy)] pub struct Buffer { pub address: usize, pub len: usize, pub device_writes: bool, } /// A split virtqueue: the descriptor table, the ring the driver offers /// buffers on and the ring the device returns them on, a page each. pub struct Queue { transport: Transport, index: u32, size: u16, descriptors: *mut Descriptor, /// flags, idx, ring[size] available: *mut u16, /// flags, idx, then (id: u32, len: u32) × size used: *mut u16, /// Descriptors not in a chain the device holds. free: [bool; MAX_SIZE], last_used: u16, } // SAFETY: a queue is owned by one driver, which serialises its use. unsafe impl Send for Queue {} const MAX_SIZE: usize = 64; fn zeroed_page() -> usize { let page = pages::alloc(0).expect("out of memory for a virtqueue"); // SAFETY: a page just allocated, ours alone. unsafe { core::ptr::write_bytes(page as *mut u8, 0, PAGE) }; page } impl Queue { pub fn new(transport: Transport, index: u32) -> Self { let size = transport.queue_max(index).min(MAX_SIZE as u32) as u16; assert!(size > 0, "the device has no queue {index}"); let (descriptors, available, used) = (zeroed_page(), zeroed_page(), zeroed_page()); transport.queue_set( size, physical(descriptors) as u64, physical(available) as u64, physical(used) as u64, ); let mut free = [false; MAX_SIZE]; free[..size as usize].fill(true); Self { transport, index, size, descriptors: descriptors as *mut Descriptor, available: available as *mut u16, used: used as *mut u16, free, last_used: 0, } } /// Offers `chain` to the device as one request, without waiting. /// Returns its head descriptor, or `None` when the queue is full. pub fn offer(&mut self, chain: &[Buffer]) -> Option { let mut slots = (0..self.size as usize).filter(|&i| self.free[i]); let mut picked = [0u16; 8]; for slot in picked.iter_mut().take(chain.len()) { *slot = slots.next()? as u16; } for (i, buffer) in chain.iter().enumerate() { let slot = picked[i]; self.free[slot as usize] = false; let last = i + 1 == chain.len(); let descriptor = Descriptor { address: physical(buffer.address) as u64, len: buffer.len as u32, flags: if last { 0 } else { DESC_NEXT } | if buffer.device_writes { DESC_WRITE } else { 0 }, next: if last { 0 } else { picked[i + 1] }, }; // SAFETY: a descriptor slot in this queue's table. unsafe { self.descriptors.add(slot as usize).write_volatile(descriptor) }; } let head = picked[0]; // SAFETY: the available ring: idx at [1], the ring from [2]. unsafe { let idx = self.available.add(1).read_volatile(); self.available .add(2 + (idx % self.size) as usize) .write_volatile(head); fence(Ordering::SeqCst); self.available.add(1).write_volatile(idx.wrapping_add(1)); } fence(Ordering::SeqCst); self.transport.notify(self.index); Some(head) } /// The next request the device has finished: its head descriptor and how /// many bytes the device wrote. Frees its descriptors. pub fn take_used(&mut self) -> Option<(u16, u32)> { fence(Ordering::SeqCst); // SAFETY: the used ring: idx at [1], (id, len) pairs from byte 4. let idx = unsafe { self.used.add(1).read_volatile() }; if idx == self.last_used { return None; } let entry = (self.last_used % self.size) as usize; // SAFETY: as above. let (head, len) = unsafe { let pair = (self.used as *const u32).add(1 + entry * 2); (pair.read_volatile() as u16, pair.add(1).read_volatile()) }; self.last_used = self.last_used.wrapping_add(1); let mut slot = head; loop { self.free[slot as usize] = true; // SAFETY: a descriptor slot in this queue's table. let descriptor = unsafe { self.descriptors.add(slot as usize).read_volatile() }; if descriptor.flags & DESC_NEXT == 0 { break; } slot = descriptor.next; } Some((head, len)) } /// Offers `chain` and waits for the device to finish it: for drivers /// with one request in flight. Returns the bytes the device wrote. pub fn submit_and_wait(&mut self, chain: &[Buffer]) -> u32 { let head = self.offer(chain).expect("the virtqueue is full"); loop { if let Some((done, len)) = self.take_used() { assert_eq!(done, head, "the device finished a request not in flight"); return len; } core::hint::spin_loop(); } } }