garage44.eu/jeroen/pinnacle

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

.. /kernel/src/drivers/display.rs

raw

//! The display: one framebuffer in RAM. Behind a virtio-gpu (QEMU's, and
//! the model a board's display controller follows) the framebuffer is a
//! resource the device scans out, and what changed is sent across a
//! rectangle at a time ([`flush`]); behind a `ramfb` (QEMU without the gpu
//! module) the screen shows RAM as it is and nothing needs flushing. On a
//! board whose loader left its screen lit (`scanout`) the framebuffer is
//! copied onto that screen's memory as it changes, at the screen's one size.

use super::{gpu, scanout};
use crate::object::Memory;
use crate::sync::SpinLock;
use alloc::sync::Arc;
use core::sync::atomic::{AtomicU32, Ordering};

pub struct Display {
    /// The framebuffer: little-endian 0x00RRGGBB pixels. Lent to the display
    /// server through handles; when the screen changes size a new one takes
    /// its place, and the old one's pages go back once the server lets go.
    pub memory: Arc<Memory>,
    pub width: u32,
    pub height: u32,
}

pub static DISPLAY: SpinLock<Option<Display>> = SpinLock::new(None);

impl Display {
    pub fn pixels(&mut self) -> &mut [u32] {
        // SAFETY: the framebuffer is ours, width × height pixels.
        unsafe {
            core::slice::from_raw_parts_mut(
                self.memory.address as *mut u32,
                (self.width * self.height) as usize,
            )
        }
    }
}

/// The screen's size when nothing says otherwise: a phone's, portrait.
pub const DEFAULT_SIZE: (u32, u32) = (720, 1440);

/// Device pixels to each of the size the virtio-gpu reports: QEMU's window
/// on a HiDPI desktop reports its size in the desktop's logical pixels, and
/// a framebuffer that many times larger is drawn one to one on the
/// monitor's own. From the fw_cfg file `opt/pinnacle/scale` ("2"), else 1.
static SCALE: AtomicU32 = AtomicU32::new(1);

/// A file of QEMU's fw_cfg, as text (at most 16 bytes).
fn fw_cfg_text<'a>(name: &[u8], buffer: &'a mut [u8; 16]) -> Option<&'a str> {
    // A PC's fw_cfg is on I/O ports, not in memory.
    #[cfg(target_arch = "x86_64")]
    let n = crate::board::fw_cfg_file(name, buffer)?;
    #[cfg(not(target_arch = "x86_64"))]
    let n = {
        let fw_cfg = crate::board::FW_CFG?;
        let (selector, size) = fw_cfg::find_sized(fw_cfg, name)?;
        fw_cfg::read(fw_cfg, selector, size, buffer)
    };
    core::str::from_utf8(&buffer[..n])
        .ok()
        .map(|t| t.trim_end_matches(['\0', '\n']))
}

/// The framebuffer for a display the device reports as `width` × `height`:
/// [`SCALE`] times that, halved while it is more than a framebuffer can be
/// (QEMU stretches it to fill the window then). None if it cannot be had.
pub fn scaled(width: u32, height: u32) -> Option<(u32, u32)> {
    let scale = SCALE.load(Ordering::Relaxed);
    let (mut w, mut h) = (width.saturating_mul(scale), height.saturating_mul(scale));
    while u64::from(w) * u64::from(h) * 4 > 16 << 20 {
        (w, h) = (w / 2, h / 2);
    }
    fits(w, h).then_some((w, h))
}

/// The screen's size: what the virtio-gpu reports (times the scale); else,
/// on QEMU, what the fw_cfg file `opt/pinnacle/screen` says ("1280x800");
/// else [`DEFAULT_SIZE`]. Pinnacle runs on screens of every shape, and
/// everything above the kernel lays out from this.
pub fn screen_size() -> (u32, u32) {
    let mut buffer = [0u8; 16];
    if let Some(scale) = fw_cfg_text(b"opt/pinnacle/scale", &mut buffer)
        .and_then(|t| t.parse::<u32>().ok())
        .filter(|s| (1..=4).contains(s))
    {
        SCALE.store(scale, Ordering::Relaxed);
    }
    if let Some(lit) = scanout::get() {
        return (lit.width, lit.height);
    }
    if let Some(size) = gpu::size().and_then(|(w, h)| scaled(w, h)) {
        return size;
    }
    let parse = || {
        let fw_cfg = crate::board::FW_CFG?;
        let (selector, size) = fw_cfg::find_sized(fw_cfg, b"opt/pinnacle/screen")?;
        let mut buffer = [0u8; 16];
        let n = fw_cfg::read(fw_cfg, selector, size, &mut buffer);
        let text = core::str::from_utf8(&buffer[..n])
            .ok()?
            .trim_end_matches(['\0', '\n']);
        let (w, h) = text.split_once('x')?;
        let (w, h): (u32, u32) = (w.parse().ok()?, h.parse().ok()?);
        fits(w, h).then_some((w, h))
    };
    parse().unwrap_or(DEFAULT_SIZE)
}

/// Whether a screen of `width` × `height` can be had: within what one block
/// of pages holds (16 MiB), and not absurd.
pub fn fits(width: u32, height: u32) -> bool {
    (320..=4096).contains(&width) && (320..=4096).contains(&height) && width * height * 4 <= 16 << 20
}

/// Which driver shows the screen.
pub fn driver() -> &'static str {
    if let Some(lit) = scanout::get() {
        lit.source
    } else if gpu::present() {
        "virtio-gpu"
    } else {
        "ramfb"
    }
}

/// Sets up a framebuffer of `width` × `height` and shows it. Returns false
/// without a display. Called again, it changes the screen's size: the
/// display shows the new framebuffer at once, and the old one lives on
/// while anything holds it.
pub fn init(width: u32, height: u32) -> bool {
    if !fits(width, height) {
        return false;
    }
    let lit = scanout::get();
    // A lit screen has the size the loader gave it, and no other.
    if lit.is_some_and(|lit| (lit.width, lit.height) != (width, height)) {
        return false;
    }
    // Zeroed by the allocator.
    let Some(memory) = Memory::new((width * height * 4) as usize) else {
        return false;
    };
    let shown = if let Some(lit) = lit {
        let class = crate::device::Class::Display;
        crate::device::mark_compatible("simple-framebuffer", "lit screen", class);
        crate::device::mark_compatible("rockchip,rk3399-vop-big", "lit screen", class);
        crate::device::mark_compatible("rockchip,rk3399-vop-lit", "lit screen", class);
        // SAFETY: the new framebuffer, width × height pixels, zeroed.
        let pixels =
            unsafe { core::slice::from_raw_parts(memory.address as *const u32, (width * height) as usize) };
        #[cfg(target_arch = "x86_64")]
        time_full_frame(&lit, pixels);
        lit.copy(pixels, 0, 0, width as i32, height as i32);
        true
    } else if gpu::present() {
        gpu::set_framebuffer(memory.address, width, height)
    } else {
        crate::device::mark_compatible("qemu,fw-cfg-mmio", "ramfb", crate::device::Class::Display);
        ramfb(&memory, width, height)
    };
    if !shown {
        return false;
    }
    // The old framebuffer, if any, is dropped here: freed unless lent.
    *DISPLAY.lock() = Some(Display {
        memory,
        width,
        height,
    });
    true
}

/// Says on the boot log, once, how long a whole frame takes to reach a lit
/// screen through its write-combining window and through the direct map
/// (uncached), each copied once: the numbers a laptop's photograph of its
/// boot log brings back. In a virtual machine both are the CPU's own time,
/// as memory there has no bus behind it.
#[cfg(target_arch = "x86_64")]
fn time_full_frame(lit: &scanout::Scanout, pixels: &[u32]) {
    static TOLD: core::sync::atomic::AtomicBool = core::sync::atomic::AtomicBool::new(false);
    if !lit.write_combining() || TOLD.swap(true, Ordering::Relaxed) {
        return;
    }
    let (w, h) = (lit.width as i32, lit.height as i32);
    let micros = |copy: &dyn Fn()| {
        let start = crate::arch::tsc();
        copy();
        (crate::arch::tsc() - start) * 1_000_000 / crate::timer::frequency().max(1)
    };
    let uncached = micros(&|| lit.copy_uncached(pixels, 0, 0, w, h));
    let combined = micros(&|| lit.copy(pixels, 0, 0, w, h));
    crate::println!(
        "display: a whole frame ({w}x{h}) to the screen in {combined} us write-combining, {uncached} us uncached"
    );
}

/// Sends the rectangle of the framebuffer to the screen, where the driver
/// needs telling (the gpu) or the screen is memory of its own (a lit
/// screen); a ramfb shows it already.
pub fn flush(x: i32, y: i32, width: i32, height: i32) {
    if let Some(lit) = scanout::get() {
        if let Some(display) = DISPLAY.lock().as_mut() {
            lit.copy(display.pixels(), x, y, width, height);
        }
        return;
    }
    gpu::flush(x, y, width, height);
}

/// QEMU's `ramfb`, set up through fw_cfg: the screen shows the memory as it is.
fn ramfb(memory: &Memory, width: u32, height: u32) -> bool {
    let Some(fw_cfg) = crate::board::FW_CFG else {
        return false;
    };
    let Some(select) = fw_cfg::find(fw_cfg, b"etc/ramfb") else {
        return false;
    };

    /// QEMU's RAMFBCfg, big-endian.
    #[repr(C, packed)]
    struct Config {
        address: u64,
        fourcc: u32,
        flags: u32,
        width: u32,
        height: u32,
        stride: u32,
    }
    const XRGB8888: u32 = u32::from_le_bytes(*b"XR24");
    let config = Config {
        address: (crate::mmu::physical(memory.address) as u64).to_be(),
        fourcc: XRGB8888.to_be(),
        flags: 0,
        width: width.to_be(),
        height: height.to_be(),
        stride: (width * 4).to_be(),
    };
    // SAFETY: the config is plain bytes.
    let bytes = unsafe { core::slice::from_raw_parts((&raw const config).cast::<u8>(), size_of::<Config>()) };
    fw_cfg::write(fw_cfg, select, bytes)
}

/// QEMU's firmware configuration device: named files the guest reads and
/// writes, through a selector, a data port and DMA.
pub mod fw_cfg {
    use crate::mmu::physical;
    use core::sync::atomic::{Ordering, fence};

    const DATA: usize = 0x0;
    const SELECTOR: usize = 0x8;
    const DMA: usize = 0x10;
    const FILE_DIR: u16 = 0x19;
    const DMA_ERROR: u32 = 0x01;
    const DMA_SELECT: u32 = 0x08;
    const DMA_WRITE: u32 = 0x10;

    fn select(base: usize, key: u16) {
        // SAFETY: fw_cfg's selector, mapped as Device memory; big-endian.
        unsafe { ((base + SELECTOR) as *mut u16).write_volatile(key.to_be()) }
    }

    fn read_bytes<const N: usize>(base: usize) -> [u8; N] {
        let mut bytes = [0; N];
        for byte in &mut bytes {
            // SAFETY: fw_cfg's data port, read a byte at a time.
            *byte = unsafe { ((base + DATA) as *const u8).read_volatile() };
        }
        bytes
    }

    /// The selector of the file named `name`.
    pub fn find(base: usize, name: &[u8]) -> Option<u16> {
        find_sized(base, name).map(|(selector, _)| selector)
    }

    /// The selector and size of the file named `name`.
    pub fn find_sized(base: usize, name: &[u8]) -> Option<(u16, usize)> {
        select(base, FILE_DIR);
        let count = u32::from_be_bytes(read_bytes(base));
        for _ in 0..count {
            let entry: [u8; 64] = read_bytes(base);
            let selector = u16::from_be_bytes([entry[4], entry[5]]);
            let entry_name = &entry[8..];
            let len = entry_name
                .iter()
                .position(|&b| b == 0)
                .unwrap_or(entry_name.len());
            if &entry_name[..len] == name {
                let size = u32::from_be_bytes([entry[0], entry[1], entry[2], entry[3]]) as usize;
                return Some((selector, size));
            }
        }
        None
    }

    /// Reads the file at `selector` into `buffer`, a byte at a time (for
    /// small files). Returns how many bytes it read.
    pub fn read(base: usize, selector: u16, size: usize, buffer: &mut [u8]) -> usize {
        select(base, selector);
        let n = size.min(buffer.len());
        for byte in &mut buffer[..n] {
            *byte = read_bytes::<1>(base)[0];
        }
        n
    }

    /// Writes `bytes` to the file at `selector`, by DMA.
    pub fn write(base: usize, selector: u16, bytes: &[u8]) -> bool {
        #[repr(C)]
        struct Access {
            control: u32,
            length: u32,
            address: u64,
        }
        let mut buffer = [0u8; 64];
        buffer[..bytes.len()].copy_from_slice(bytes);
        let access = Access {
            control: (u32::from(selector) << 16 | DMA_SELECT | DMA_WRITE).to_be(),
            length: (bytes.len() as u32).to_be(),
            address: (physical(buffer.as_ptr() as usize) as u64).to_be(),
        };
        let at = physical(&raw const access as usize) as u64;
        fence(Ordering::SeqCst);
        // SAFETY: fw_cfg's DMA address register, big-endian, the low half
        // last: writing it starts the transfer.
        unsafe {
            ((base + DMA) as *mut u32).write_volatile(((at >> 32) as u32).to_be());
            ((base + DMA + 4) as *mut u32).write_volatile((at as u32).to_be());
        }
        loop {
            fence(Ordering::SeqCst);
            // SAFETY: QEMU writes the control word back when done.
            let control = u32::from_be(unsafe { (&raw const access.control).read_volatile() });
            if control & !DMA_ERROR == 0 {
                return control & DMA_ERROR == 0;
            }
        }
    }
}