garage44.eu/jeroen/pinnacle

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

.. /kernel/src/drivers/gpu3d.rs

raw

//! The 3D virtio-gpu: QEMU's virtio-gpu-gl on PCI, whose contexts of the
//! Venus capset run a guest's Vulkan commands on the host's Vulkan. The
//! screen stays with `gpu` (the 2D device); this one draws nothing yet.
//!
//! Venus needs the device's host-visible memory: a PCI shared memory region
//! (id 1) the host maps what its Vulkan allocates into. QEMU offers it on
//! PCI only (on virtio-mmio, asking for it crashes QEMU 11.1).
//!
//! The kernel carries Venus and speaks none of it: the features agreed, the
//! capsets read, a context per program (its GPU channel, `pinnacle_abi::gpu`)
//! and the host's memory shared into the window. Vulkan itself is the
//! program's (`pinnacle-venus`).
//!
//! The check: Venus's capset
//! fetched, a Venus context made and destroyed, and the shared memory found.

use super::virtio::{self, Buffer, Queue, Transport};
use crate::mm::pages;
use crate::sync::SpinLock;
use alloc::vec::Vec;

const Q_CONTROL: u32 = 0;
const GET_CAPSET_INFO: u32 = 0x0108;
const GET_CAPSET: u32 = 0x0109;
const CTX_CREATE: u32 = 0x0200;
const CTX_DESTROY: u32 = 0x0201;
const CTX_ATTACH_RESOURCE: u32 = 0x0202;
const RESOURCE_UNREF: u32 = 0x0102;
const RESOURCE_CREATE_BLOB: u32 = 0x010c;
const RESOURCE_MAP_BLOB: u32 = 0x0208;
const RESOURCE_UNMAP_BLOB: u32 = 0x0209;
const SUBMIT_3D: u32 = 0x0207;
const RESP_OK_MAP_INFO: u32 = 0x1106;
/// A blob of the host's memory, made by the context's renderer (Venus's
/// shared memory: blob id 0), that the guest may map.
const BLOB_MEM_GUEST: u32 = 1;
const BLOB_MEM_HOST3D: u32 = 2;
const BLOB_FLAG_USE_MAPPABLE: u32 = 1;
const RESP_OK_NODATA: u32 = 0x1100;
const RESP_OK_CAPSET_INFO: u32 = 0x1102;
const RESP_OK_CAPSET: u32 = 0x1103;

/// Features: 3D (virgl), blob resources, contexts of a chosen capset.
const F_VIRGL: u64 = 1 << 0;
const F_RESOURCE_BLOB: u64 = 1 << 3;
const F_CONTEXT_INIT: u64 = 1 << 4;

/// The capset Venus is.
pub const CAPSET_VENUS: u32 = 4;
/// The shared memory region of host-visible memory.
const SHM_HOST_VISIBLE: u8 = 1;

/// A request's header (virtio_gpu_ctrl_hdr): type, flags, fence id, context
/// id, ring index, padding.
const HEADER: usize = 24;
/// Where in a request's page its response goes.
const RESPONSE: usize = 2048;

struct Gpu3d {
    transport: Transport,
    control: Queue,
    /// One page for a request and its response: requests go one at a time.
    page: usize,
    features: u64,
    /// The capsets: id, highest version, size.
    capsets: Vec<(u32, u32, u32)>,
    /// The host-visible window's ranges in use: offset and length.
    window_used: Vec<(u64, u64)>,
    /// The next context's id and the next resource's.
    next_ctx: u32,
    next_resource: u32,
}

/// The granule of the host-visible window: a whole number of any host's
/// pages (16 KiB on a Mac), as a blob mapped into it must be.
const WINDOW_GRANULE: u64 = 64 << 10;

impl Gpu3d {
    /// The host-visible window: kernel address and length.
    fn window(&self) -> Option<(usize, u64)> {
        let (at, _, len) = self.transport.shared_memory(SHM_HOST_VISIBLE)?;
        Some((at, len))
    }

    /// A new context of Venus's capset, named `name` for the host's logs.
    fn create_context(&mut self, name: &[u8; 4]) -> Option<u32> {
        let ctx = self.next_ctx;
        self.next_ctx += 1;
        // ctx_create: the debug name's length, the capset the context is of,
        // then the name (64 bytes).
        let mut words = [0u32; 2 + 16];
        words[..3].copy_from_slice(&[4, CAPSET_VENUS, u32::from_le_bytes(*name)]);
        (self.request(CTX_CREATE, ctx, &words, 0) == RESP_OK_NODATA).then_some(ctx)
    }

    /// Host memory for context `ctx`, mapped into the window: a blob of
    /// `size` bytes (rounded up to the window's granule) of `blob_id` (0:
    /// Venus's own memory; else a VkDeviceMemory's id). Returns the
    /// resource, its offset in the window and its size.
    fn blob(&mut self, ctx: u32, blob_id: u64, size: u64) -> Result<(u32, u64, u64), &'static str> {
        let size = size.max(1).next_multiple_of(WINDOW_GRANULE);
        let (_, window_len) = self.window().ok_or("no host-visible memory")?;
        // The lowest free range that fits.
        let mut offset = 0;
        let mut used = self.window_used.clone();
        used.sort_unstable();
        for &(at, len) in &used {
            if offset + size <= at {
                break;
            }
            offset = offset.max(at + len);
        }
        if offset + size > window_len {
            let used: u64 = self.window_used.iter().map(|&(_, len)| len).sum();
            crate::println!(
                "gpu3d: the host-visible window is full: {} KiB asked, {} blobs hold {} of {} KiB",
                size >> 10,
                self.window_used.len(),
                used >> 10,
                window_len >> 10
            );
            return Err("the host-visible window is full");
        }
        let resource = self.next_resource;
        self.next_resource += 1;
        // resource_create_blob: resource, blob_mem, blob_flags, nr_entries,
        // blob_id (u64), size (u64).
        let blob = [
            resource,
            BLOB_MEM_HOST3D,
            BLOB_FLAG_USE_MAPPABLE,
            0,
            blob_id as u32,
            (blob_id >> 32) as u32,
            size as u32,
            (size >> 32) as u32,
        ];
        if self.request(RESOURCE_CREATE_BLOB, ctx, &blob, 0) != RESP_OK_NODATA {
            return Err("the host's memory was not made");
        }
        // resource_map_blob: resource, padding, offset into the window (u64).
        let map = [resource, 0, offset as u32, (offset >> 32) as u32];
        if self.request(CTX_ATTACH_RESOURCE, ctx, &[resource, 0], 0) != RESP_OK_NODATA
            || self.request(RESOURCE_MAP_BLOB, 0, &map, 8) != RESP_OK_MAP_INFO
        {
            let _ = self.request(RESOURCE_UNREF, 0, &[resource, 0], 0);
            return Err("the host's memory was not mapped");
        }
        self.window_used.push((offset, size));
        self.say_window("+", size);
        Ok((resource, offset, size))
    }

    /// Makes the guest's pages at `physical` (`size` bytes, contiguous) a
    /// blob of context `ctx`: the host uses them as they are, through no
    /// window. Its resource id.
    fn guest_blob(&mut self, ctx: u32, physical: u64, size: u64) -> Option<u32> {
        let resource = self.next_resource;
        self.next_resource += 1;
        // resource_create_blob: resource, blob_mem, blob_flags, nr_entries,
        // blob_id (u64), size (u64); then one entry: address (u64), length,
        // padding.
        let blob = [
            resource,
            BLOB_MEM_GUEST,
            0,
            1,
            0,
            0,
            size as u32,
            (size >> 32) as u32,
            physical as u32,
            (physical >> 32) as u32,
            size as u32,
            0,
        ];
        if self.request(RESOURCE_CREATE_BLOB, ctx, &blob, 0) != RESP_OK_NODATA {
            return None;
        }
        if self.request(CTX_ATTACH_RESOURCE, ctx, &[resource, 0], 0) != RESP_OK_NODATA {
            let _ = self.request(RESOURCE_UNREF, 0, &[resource, 0], 0);
            return None;
        }
        Some(resource)
    }

    /// With the profiler on, says a blob taken (`+`) or given back (`-`) and
    /// how full the window is then: whether its use only grows.
    fn say_window(&self, sign: &str, size: u64) {
        #[cfg(target_arch = "aarch64")]
        if crate::profile::on() {
            let used: u64 = self.window_used.iter().map(|&(_, len)| len).sum();
            crate::println!(
                "gpu3d: window {sign}{} KiB: {} blobs, {} KiB",
                size >> 10,
                self.window_used.len(),
                used >> 10
            );
        }
        let _ = (sign, size);
    }

    /// Lets go of a blob [`blob`](Self::blob) made, and its range.
    fn unblob(&mut self, resource: u32, offset: u64) {
        let _ = self.request(RESOURCE_UNMAP_BLOB, 0, &[resource, 0], 0);
        let _ = self.request(RESOURCE_UNREF, 0, &[resource, 0], 0);
        let size = self
            .window_used
            .iter()
            .find(|&&(at, _)| at == offset)
            .map_or(0, |&(_, len)| len);
        self.window_used.retain(|&(at, _)| at != offset);
        self.say_window("-", size);
    }

    /// Sends a command stream to context `ctx`.
    fn submit(&mut self, ctx: u32, bytes: &[u8]) -> bool {
        let mut words = alloc::vec![bytes.len() as u32, 0];
        words.extend(bytes.chunks(4).map(|c| {
            let mut w = [0; 4];
            w[..c.len()].copy_from_slice(c);
            u32::from_le_bytes(w)
        }));
        self.request(SUBMIT_3D, ctx, &words, 0) == RESP_OK_NODATA
    }
}

static GPU3D: SpinLock<Option<Gpu3d>> = SpinLock::new(None);
/// The programs' contexts: each one's id and the kernel's end of its
/// channel. Apart from [`GPU3D`]: replying (or a reply dropped) may give
/// memory back, which takes that lock.
static CONTEXTS: SpinLock<Vec<(u32, alloc::sync::Arc<crate::object::Endpoint>)>> = SpinLock::new(Vec::new());

/// A context on the 3D GPU for a program: its end of the channel
/// ([`pinnacle_abi::gpu`]).
pub fn open() -> Option<alloc::sync::Arc<crate::object::Endpoint>> {
    let ctx = {
        let mut guard = GPU3D.lock();
        let gpu = guard.as_mut()?;
        gpu.capsets.iter().find(|(id, ..)| *id == CAPSET_VENUS)?;
        gpu.create_context(b"prog")?
    };
    let (program, kernel) = crate::object::Endpoint::pair_with_sink(crate::object::Sink::Gpu(ctx));
    CONTEXTS.lock().push((ctx, kernel));
    Some(program)
}

/// A program's message on its context's channel.
pub fn sink_send(ctx: u32, bytes: &[u8]) {
    use pinnacle_abi::gpu;
    let Some((kind, body)) = bytes.split_first_chunk::<4>() else {
        return;
    };
    match u32::from_le_bytes(*kind) {
        gpu::SUBMIT => {
            if let Some(gpu) = GPU3D.lock().as_mut() {
                gpu.submit(ctx, body);
            }
        }
        gpu::BLOB => {
            let Some((blob_id, rest)) = body.split_first_chunk::<8>() else {
                return;
            };
            let Some((size, _)) = rest.split_first_chunk::<8>() else {
                return;
            };
            let (blob_id, size) = (u64::from_le_bytes(*blob_id), u64::from_le_bytes(*size));
            let made = GPU3D.lock().as_mut().map(|gpu| {
                let (window, _) = gpu.window()?;
                let (resource, offset, size) = gpu.blob(ctx, blob_id, size).ok()?;
                let at = window + offset as usize;
                Some((
                    crate::object::Memory::gpu(at, size as usize, resource, offset),
                    resource,
                ))
            });
            reply(ctx, gpu::BLOB, made.flatten());
        }
        gpu::GUEST_BLOB => {
            let Some((size, _)) = body.split_first_chunk::<8>() else {
                return;
            };
            let size = u64::from_le_bytes(*size) as usize;
            let made = crate::object::Memory::guest_gpu(size, |physical, size| {
                GPU3D.lock().as_mut()?.guest_blob(ctx, physical, size)
            });
            reply(ctx, gpu::GUEST_BLOB, made);
        }
        _ => {}
    }
}

/// Answers a blob message of `kind` on context `ctx`'s channel: a status,
/// the resource's id and the memory's handle when made.
fn reply(ctx: u32, kind: u32, made: Option<(alloc::sync::Arc<crate::object::Memory>, u32)>) {
    let (status, resource, handles) = match made {
        Some((memory, resource)) => (0u32, resource, alloc::vec![crate::object::Object::Memory(memory)]),
        None => (1, 0, Vec::new()),
    };
    let mut reply = Vec::with_capacity(12);
    reply.extend_from_slice(&kind.to_le_bytes());
    reply.extend_from_slice(&status.to_le_bytes());
    reply.extend_from_slice(&resource.to_le_bytes());
    let end = CONTEXTS
        .lock()
        .iter()
        .find(|(c, _)| *c == ctx)
        .map(|(_, end)| end.clone());
    // Outside both locks: a reply the program can no longer take drops its
    // memory, which gives it back.
    if let Some(end) = end {
        end.send(crate::object::Message {
            bytes: reply,
            handles,
        });
    }
}

/// The program let go of its context's channel: the context ends. Memory it
/// still holds stays the host's until that goes too.
pub fn sink_close(ctx: u32) {
    let end = {
        let mut contexts = CONTEXTS.lock();
        let at = contexts.iter().position(|(c, _)| *c == ctx);
        at.map(|i| contexts.swap_remove(i))
    };
    if let Some(gpu) = GPU3D.lock().as_mut() {
        let _ = gpu.request(CTX_DESTROY, ctx, &[], 0);
    }
    drop(end);
}

/// A guest blob, let go by its last holder: the host first, then its pages.
pub fn release_guest_blob(resource: u32) {
    if let Some(gpu) = GPU3D.lock().as_mut() {
        let _ = gpu.request(RESOURCE_UNREF, 0, &[resource, 0], 0);
    }
}

/// Memory a blob shared, let go by its last holder.
pub fn release_blob(resource: u32, offset: u64, _size: u64) {
    if let Some(gpu) = GPU3D.lock().as_mut() {
        gpu.unblob(resource, offset);
    }
}
/// Its transport, for the interrupt handler, which must not wait on [`GPU3D`]:
/// a request holds that while its device's interrupt may come on its core.
static IRQ: SpinLock<Option<Transport>> = SpinLock::new(None);

fn write_u32(at: usize, value: u32) {
    // SAFETY: inside the driver's own page.
    unsafe { (at as *mut u32).write_unaligned(value) }
}

fn read_u32(at: usize) -> u32 {
    // SAFETY: inside the driver's own page.
    unsafe { (at as *const u32).read_unaligned() }
}

impl Gpu3d {
    /// Sends a request of `kind` for context `ctx` (0: none) with `words`
    /// after the header and waits for its response, `response_len` bytes
    /// after the response's header. Returns the response's type.
    fn request(&mut self, kind: u32, ctx: u32, words: &[u32], response_len: usize) -> u32 {
        let page = self.page;
        // SAFETY: the driver's page; no request is in flight.
        unsafe { core::ptr::write_bytes(page as *mut u8, 0, 4096) };
        write_u32(page, kind);
        write_u32(page + 16, ctx);
        for (i, w) in words.iter().enumerate() {
            write_u32(page + HEADER + i * 4, *w);
        }
        let request = Buffer {
            address: page,
            len: HEADER + words.len() * 4,
            device_writes: false,
        };
        let response = Buffer {
            address: page + RESPONSE,
            len: HEADER + response_len,
            device_writes: true,
        };
        self.control.submit_and_wait(&[request, response]);
        read_u32(page + RESPONSE)
    }

    /// The response's body, `at` bytes in.
    fn body(&self, at: usize) -> u32 {
        read_u32(self.page + RESPONSE + HEADER + at)
    }
}

/// Finds the 3D virtio-gpu (on PCI), agrees its features and reads its
/// capsets. Returns whether there is one.
pub fn init() -> bool {
    // Only a GPU that offers 3D: a PC's plain virtio-gpu is its screen, which
    // the 2D driver holds and a reset here would blank.
    let Some(transport) =
        virtio::find(virtio::device::GPU).find(|t| t.is_pci() && t.offered() & F_VIRGL != 0)
    else {
        return false;
    };
    let Some(features) = transport.begin(F_VIRGL | F_RESOURCE_BLOB | F_CONTEXT_INIT) else {
        return false;
    };
    let control = Queue::new(transport, Q_CONTROL);
    transport.ready();
    // Answerable before the first request: the device raises its INTx for
    // each, and on a line another driver has turned on (QEMU's OHCI shares
    // it on `virt`) an interrupt nobody acknowledges fires for ever.
    *IRQ.lock() = Some(transport);
    let Some(page) = pages::alloc(0) else { return false };
    let mut gpu = Gpu3d {
        transport,
        control,
        page,
        features,
        capsets: Vec::new(),
        window_used: Vec::new(),
        next_ctx: 1,
        next_resource: 1,
    };
    if features & F_VIRGL != 0 {
        // virtio_gpu_config: events_read, events_clear, num_scanouts, num_capsets.
        for index in 0..transport.config_u32(12).min(16) {
            if gpu.request(GET_CAPSET_INFO, 0, &[index, 0], 16) == RESP_OK_CAPSET_INFO {
                gpu.capsets.push((gpu.body(0), gpu.body(4), gpu.body(8)));
            }
        }
    }
    *GPU3D.lock() = Some(gpu);
    true
}

/// What a check of the 3D device found.
pub struct Found {
    pub capsets: Vec<(u32, u32, u32)>,
    pub venus_version: u32,
    pub venus_bytes: usize,
    /// The host-visible memory: its size in bytes.
    pub host_visible: u64,
}

/// Venus's capset fetched, a Venus context made and destroyed, and the
/// host-visible memory found: the first step of a Vulkan run on the host's.
pub fn check() -> Result<Found, &'static str> {
    let mut guard = GPU3D.lock();
    let gpu = guard.as_mut().ok_or("no 3D virtio-gpu")?;
    if gpu.features & F_VIRGL == 0 {
        return Err("no 3D");
    }
    if gpu.features & F_CONTEXT_INIT == 0 || gpu.features & F_RESOURCE_BLOB == 0 {
        return Err("no contexts of a chosen capset, or no blob resources");
    }
    let &(_, version, size) = gpu
        .capsets
        .iter()
        .find(|(id, ..)| *id == CAPSET_VENUS)
        .ok_or("no Venus capset")?;
    let size = (size as usize).min(4096 - RESPONSE - HEADER);
    if gpu.request(GET_CAPSET, 0, &[CAPSET_VENUS, version], size) != RESP_OK_CAPSET {
        return Err("the Venus capset was not given");
    }
    // It begins with Venus's wire format version: never zero.
    if gpu.body(0) == 0 {
        return Err("an empty Venus capset");
    }
    let ctx = gpu.create_context(b"pinn").ok_or("a Venus context was refused")?;
    if gpu.request(CTX_DESTROY, ctx, &[], 0) != RESP_OK_NODATA {
        return Err("the Venus context would not go");
    }
    let (_, _, host_visible) = gpu
        .transport
        .shared_memory(SHM_HOST_VISIBLE)
        .ok_or("no host-visible memory")?;
    Ok(Found {
        capsets: gpu.capsets.clone(),
        venus_version: version,
        venus_bytes: size,
        host_visible,
    })
}

/// The 3D device's interrupt: requests are waited for, so only acknowledged.
pub fn interrupt(intid: u32) -> bool {
    let Some(transport) = *IRQ.lock() else {
        return false;
    };
    if transport.intid != intid {
        return false;
    }
    transport.acknowledge();
    true
}