garage44.eu/jeroen/pinnacle

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

.. /kernel/src/drivers/screen_log.rs

raw

//! The boot log on the screen a loader lit (`scanout`): what the kernel
//! prints, line by line, drawn straight into the screen's memory from the
//! first line after the screen is found until the display server starts,
//! and a panic over whatever is shown then. A laptop has no serial port:
//! on hardware nobody has tried, this is how a first start that stops says
//! where.
//!
//! Lines are drawn down the screen and start again at the top when they
//! reach the bottom, the line below the newest cleared: no scrolling, which
//! would redraw the whole screen a line, through memory that is uncached
//! (on a PC, write-combining: faster, and still not cached for reading).
//! `quiet` on the command line leaves the screen alone.

use super::scanout::Scanout;
use crate::sync::SpinLock;
use core::sync::atomic::{AtomicBool, Ordering};

/// A monospace font: printable ASCII, each glyph a `width` × `height` cell
/// of coverage.
pub struct Font {
    pub width: usize,
    pub height: usize,
    pub cells: &'static [u8],
}

mod fonts {
    use super::Font;
    include!(concat!(env!("OUT_DIR"), "/console_font.rs"));
}

const BACKGROUND: u32 = 0x0010_1418;
const TEXT: u32 = 0x00d8_dce0;
const PANIC: u32 = 0x00ff_8070;
/// From the screen's left edge (and clear of its first column, which the
/// display self-check reads back).
const MARGIN: usize = 12;

struct Log {
    screen: Option<Scanout>,
    font: &'static Font,
    /// The line being written, and the column in it.
    row: usize,
    column: usize,
    colour: u32,
}

static LOG: SpinLock<Log> = SpinLock::new(Log {
    screen: None,
    font: &fonts::SMALL,
    row: 0,
    column: 0,
    colour: TEXT,
});

/// Drawing: from [`start`] until [`stop`], and again for a panic.
static ON: AtomicBool = AtomicBool::new(false);

impl Log {
    fn rows(&self, screen: &Scanout) -> usize {
        (screen.height as usize / self.font.height).max(1)
    }

    fn columns(&self, screen: &Scanout) -> usize {
        (screen.width as usize).saturating_sub(2 * MARGIN) / self.font.width
    }

    fn pixel(screen: &Scanout, x: usize, y: usize, colour: u32) {
        let at = screen.base() + y * screen.stride as usize + x * screen.format.bytes() as usize;
        // SAFETY: inside the screen's memory (callers keep x, y on it),
        // which the allocator never hands out.
        unsafe {
            match screen.format.bytes() {
                4 => (at as *mut u32).write_volatile(screen.format.encode(colour)),
                _ => (at as *mut u16).write_volatile(screen.format.encode(colour) as u16),
            }
        }
    }

    /// Fills text row `row` with the background.
    fn clear_row(&self, screen: &Scanout, row: usize) {
        let top = row * self.font.height;
        for y in top..(top + self.font.height).min(screen.height as usize) {
            for x in MARGIN..screen.width as usize - MARGIN {
                Self::pixel(screen, x, y, BACKGROUND);
            }
        }
    }

    fn glyph(&self, screen: &Scanout, byte: u8) {
        let index = if (b' '..=b'~').contains(&byte) {
            byte - b' '
        } else {
            b'?' - b' '
        };
        let f = self.font;
        let cell = &f.cells[usize::from(index) * f.width * f.height..][..f.width * f.height];
        let (left, top) = (MARGIN + self.column * f.width, self.row * f.height);
        for y in 0..f.height {
            for x in 0..f.width {
                let a = u32::from(cell[y * f.width + x]);
                if a != 0 {
                    Self::pixel(screen, left + x, top + y, blend(BACKGROUND, self.colour, a));
                }
            }
        }
    }

    fn newline(&mut self, screen: &Scanout) {
        self.column = 0;
        self.row = (self.row + 1) % self.rows(screen);
        self.clear_row(screen, self.row);
        // The line after it cleared too, so the newest is plain to see.
        self.clear_row(screen, (self.row + 1) % self.rows(screen));
    }

    fn write(&mut self, bytes: &[u8]) {
        let Some(screen) = self.screen else { return };
        for &byte in bytes {
            match byte {
                b'\n' => self.newline(&screen),
                b'\r' => {}
                _ => {
                    if self.column >= self.columns(&screen) {
                        self.newline(&screen);
                    }
                    self.glyph(&screen, byte);
                    self.column += 1;
                }
            }
        }
        #[cfg(target_arch = "x86_64")]
        crate::mmu::flush_write_combining();
    }
}

/// `a` (0–255) of `top` over `bottom`, channel by channel.
fn blend(bottom: u32, top: u32, a: u32) -> u32 {
    let channel = |shift: u32| {
        let (b, t) = (bottom >> shift & 0xff, top >> shift & 0xff);
        ((t * a + b * (255 - a)) / 255) << shift
    };
    channel(16) | channel(8) | channel(0)
}

/// Starts the log on the lit screen, if there is one and the command line
/// does not say `quiet`: the screen cleared, the larger font on a large
/// screen (2560 pixels wide and more, where the smaller is too small to
/// read from a photograph).
pub fn start() {
    let Some(screen) = super::scanout::get() else {
        return;
    };
    if crate::args::has("quiet") {
        return;
    }
    let mut log = LOG.lock();
    log.font = if screen.width >= 2560 {
        &fonts::LARGE
    } else {
        &fonts::SMALL
    };
    log.screen = Some(screen);
    for row in 0..log.rows(&screen) {
        log.clear_row(&screen, row);
    }
    ON.store(true, Ordering::Relaxed);
}

/// Stops it: the display server draws the screen from now on.
pub fn stop() {
    ON.store(false, Ordering::Relaxed);
}

/// What the console prints, while the log runs.
pub fn write(bytes: &[u8]) {
    if !ON.load(Ordering::Relaxed) {
        return;
    }
    // Never waits: a line printed while another core draws is left to the
    // serial port (and a panic inside the drawing does not deadlock).
    if let Some(mut log) = LOG.try_lock() {
        log.write(bytes);
    }
}

/// A panic: from here on everything printed goes to the screen too, in the
/// panic's colour, whatever the display server drew.
pub fn panicking() {
    let Some(mut log) = LOG.try_lock() else { return };
    if log.screen.is_none() {
        return;
    }
    log.colour = PANIC;
    let screen = log.screen.unwrap();
    log.newline(&screen);
    drop(log);
    ON.store(true, Ordering::Relaxed);
}