garage44.eu/jeroen/pinnacle

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

.. /kernel/src/drivers/gpu.rs

raw

//! The display as a virtio-gpu (2D): the framebuffer is a resource the
//! kernel owns in RAM and the device scans out, and what changed on it is
//! sent across a rectangle at a time (TRANSFER_TO_HOST_2D, then
//! RESOURCE_FLUSH), which is how a board's display controller works too,
//! and the opposite of ramfb, where the screen shows RAM as it is. Only
//! the changed rectangles cross, so an idle screen costs nothing.
//!
//! Requests go on the control queue; those made at setup are waited for,
//! those for a flush are not: a few can be in flight, and the interrupt
//! frees their slots.

use super::virtio::{self, Buffer, Queue, Transport};
use crate::mm::pages;
use crate::mmu::physical;
use crate::sync::SpinLock;

const Q_CONTROL: u32 = 0;
const GET_DISPLAY_INFO: u32 = 0x0100;
const RESOURCE_CREATE_2D: u32 = 0x0101;
const RESOURCE_UNREF: u32 = 0x0102;
const SET_SCANOUT: u32 = 0x0103;
const RESOURCE_FLUSH: u32 = 0x0104;
const TRANSFER_TO_HOST_2D: u32 = 0x0105;
const RESOURCE_ATTACH_BACKING: u32 = 0x0106;
const RESP_OK_NODATA: u32 = 0x1100;
const RESP_OK_DISPLAY_INFO: u32 = 0x1101;
/// B8G8R8X8: a little-endian 0x00RRGGBB pixel, the kernel's.
const FORMAT_BGRX: u32 = 2;
/// The control header: type, flags, fence, context, ring, padding.
const HEADER: usize = 24;
const MAX_SCANOUTS: usize = 16;
/// The device's configuration: events it has to tell (read), and those
/// the driver has seen (written).
const CONFIG_EVENTS_READ: usize = 0;
const CONFIG_EVENTS_CLEAR: usize = 4;
/// The display's size changed: QEMU's window was resized.
const EVENT_DISPLAY: u32 = 1;
/// Requests in flight at once (a flush is two), a page each: the request
/// at 0, its response at 2048.
const SLOTS: usize = 8;
const RESPONSE: usize = 2048;

struct Gpu {
    transport: Transport,
    control: Queue,
    pages: [usize; SLOTS],
    heads: [Option<u16>; SLOTS],
    /// The resource scanned out, and the next id to give.
    scanout: u32,
    next_resource: u32,
    width: u32,
    height: u32,
}

static GPU: SpinLock<Option<Gpu>> = SpinLock::new(None);

fn write_u32(page: usize, at: usize, value: u32) {
    // SAFETY: inside a page of ours.
    unsafe { ((page + at) as *mut u8).copy_from(value.to_le_bytes().as_ptr(), 4) };
}

fn read_u32(page: usize, at: usize) -> u32 {
    // SAFETY: inside a page of ours, which the device may have written.
    unsafe {
        let mut b = [0u8; 4];
        ((page + at) as *const u8).copy_to(b.as_mut_ptr(), 4);
        u32::from_le_bytes(b)
    }
}

impl Gpu {
    fn reap(&mut self) {
        while let Some((head, _)) = self.control.take_used() {
            if let Some(slot) = self.heads.iter().position(|h| *h == Some(head)) {
                self.heads[slot] = None;
            }
        }
    }

    /// A free slot, waiting for one if every slot is in flight.
    fn slot(&mut self) -> usize {
        loop {
            self.reap();
            if let Some(slot) = self.heads.iter().position(Option::is_none) {
                return slot;
            }
            core::hint::spin_loop();
        }
    }

    /// Writes a request of `kind` with `words` after the header into
    /// `slot`'s page and offers it; `response_len` bytes of response fit
    /// after the response header.
    fn offer(&mut self, slot: usize, kind: u32, words: &[u32], response_len: usize) {
        let page = self.pages[slot];
        // SAFETY: the slot's page, ours while not in flight.
        unsafe { core::ptr::write_bytes(page as *mut u8, 0, HEADER + words.len() * 4) };
        write_u32(page, 0, kind);
        for (i, w) in words.iter().enumerate() {
            write_u32(page, HEADER + i * 4, *w);
        }
        write_u32(page, RESPONSE, 0);
        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.heads[slot] = self.control.offer(&[request, response]);
    }

    /// Sends a request and waits for its response: its type, in the slot's
    /// page after [`RESPONSE`].
    fn request(&mut self, kind: u32, words: &[u32], response_len: usize) -> (usize, u32) {
        let slot = self.slot();
        self.offer(slot, kind, words, response_len);
        let Some(mine) = self.heads[slot] else {
            return (slot, 0);
        };
        loop {
            if let Some((head, _)) = self.control.take_used() {
                if let Some(s) = self.heads.iter().position(|h| *h == Some(head)) {
                    self.heads[s] = None;
                }
                if head == mine {
                    return (slot, read_u32(self.pages[slot], RESPONSE));
                }
            }
            core::hint::spin_loop();
        }
    }

    /// The size of the first enabled scanout, as the device reports it.
    fn display_size(&mut self) -> Option<(u32, u32)> {
        let (slot, kind) = self.request(GET_DISPLAY_INFO, &[], MAX_SCANOUTS * 24);
        if kind != RESP_OK_DISPLAY_INFO {
            return None;
        }
        // Each pmode: a rect (x, y, width, height), enabled, flags.
        let page = self.pages[slot];
        (0..MAX_SCANOUTS)
            .map(|i| RESPONSE + HEADER + i * 24)
            .find(|&at| read_u32(page, at + 16) != 0)
            .map(|at| (read_u32(page, at + 8), read_u32(page, at + 12)))
    }
}

/// Sets up the first virtio-gpu. Returns the screen's size as the device
/// reports it (its first enabled scanout), or None without a device.
pub fn init() -> Option<(u32, u32)> {
    let transport = virtio::find(virtio::device::GPU).next()?;
    transport.begin(0)?;
    transport.signal_config_changes();
    let control = Queue::new(transport, Q_CONTROL);
    transport.ready();
    let mut pages = [0; SLOTS];
    for page in &mut pages {
        *page = pages::alloc(0)?;
    }
    let mut gpu = Gpu {
        transport,
        control,
        pages,
        heads: [None; SLOTS],
        scanout: 0,
        next_resource: 1,
        width: 0,
        height: 0,
    };
    // What the size was before now is the size now.
    transport.set_config_u32(CONFIG_EVENTS_CLEAR, transport.config_u32(CONFIG_EVENTS_READ));
    let (width, height) = gpu.display_size()?;
    (gpu.width, gpu.height) = (width, height);
    let intid = transport.intid;
    *GPU.lock() = Some(gpu);
    crate::gic::enable_shared(intid);
    Some((width, height))
}

pub fn present() -> bool {
    GPU.lock().is_some()
}

/// The screen's size as the device reports it, if there is one.
pub fn size() -> Option<(u32, u32)> {
    GPU.lock().as_ref().map(|g| (g.width, g.height))
}

/// Makes `address` (physically contiguous, `width` × `height` pixels) the
/// framebuffer: a new resource, backed by it, scanned out; the one before
/// is let go of. False if the device refused.
pub fn set_framebuffer(address: usize, width: u32, height: u32) -> bool {
    let mut guard = GPU.lock();
    let Some(gpu) = guard.as_mut() else { return false };
    let id = gpu.next_resource;
    gpu.next_resource += 1;
    let (_, kind) = gpu.request(RESOURCE_CREATE_2D, &[id, FORMAT_BGRX, width, height], 0);
    if kind != RESP_OK_NODATA {
        return false;
    }
    let bytes = width * height * 4;
    let p = physical(address) as u64;
    let (_, kind) = gpu.request(
        RESOURCE_ATTACH_BACKING,
        &[id, 1, p as u32, (p >> 32) as u32, bytes, 0],
        0,
    );
    if kind != RESP_OK_NODATA {
        return false;
    }
    let (_, kind) = gpu.request(SET_SCANOUT, &[0, 0, width, height, 0, id], 0);
    if kind != RESP_OK_NODATA {
        return false;
    }
    let old = core::mem::replace(&mut gpu.scanout, id);
    (gpu.width, gpu.height) = (width, height);
    if old != 0 {
        gpu.request(RESOURCE_UNREF, &[old, 0], 0);
    }
    // The whole of it, once.
    flush_locked(gpu, 0, 0, width, height);
    true
}

fn flush_locked(gpu: &mut Gpu, x: u32, y: u32, width: u32, height: u32) {
    let id = gpu.scanout;
    if id == 0 || width == 0 || height == 0 {
        return;
    }
    // The transfer's offset: where the rectangle starts in the resource.
    let offset = u64::from(y) * u64::from(gpu.width) * 4 + u64::from(x) * 4;
    let slot = gpu.slot();
    gpu.offer(
        slot,
        TRANSFER_TO_HOST_2D,
        &[x, y, width, height, offset as u32, (offset >> 32) as u32, id, 0],
        0,
    );
    let slot = gpu.slot();
    gpu.offer(slot, RESOURCE_FLUSH, &[x, y, width, height, id, 0], 0);
}

/// Sends the rectangle of the framebuffer across and shows it. Clipped to
/// the screen; nothing without a device (ramfb needs no flush).
pub fn flush(x: i32, y: i32, width: i32, height: i32) {
    let mut guard = GPU.lock();
    let Some(gpu) = guard.as_mut() else { return };
    let (sw, sh) = (gpu.width as i32, gpu.height as i32);
    let (x0, y0) = (x.clamp(0, sw), y.clamp(0, sh));
    let (x1, y1) = ((x + width).clamp(0, sw), (y + height).clamp(0, sh));
    if x1 <= x0 || y1 <= y0 {
        return;
    }
    flush_locked(gpu, x0 as u32, y0 as u32, (x1 - x0) as u32, (y1 - y0) as u32);
}

/// The device's interrupt: requests done, or the display's size changed
/// (QEMU's window resized), which goes to the display server as an input
/// event; it takes a framebuffer of the new size. False if `intid` is not
/// its.
pub fn interrupt(intid: u32) -> bool {
    let mut guard = GPU.lock();
    let Some(gpu) = guard.as_mut() else { return false };
    if gpu.transport.intid != intid {
        return false;
    }
    gpu.transport.acknowledge();
    gpu.reap();
    let events = gpu.transport.config_u32(CONFIG_EVENTS_READ);
    if events == 0 {
        return true;
    }
    gpu.transport.set_config_u32(CONFIG_EVENTS_CLEAR, events);
    let size = (events & EVENT_DISPLAY != 0)
        .then(|| gpu.display_size())
        .flatten();
    drop(guard);
    if let Some((width, height)) = size.and_then(|(w, h)| super::display::scaled(w, h)) {
        crate::drivers::input::screen_changed(width, height);
    }
    true
}