Skip to main content

strat9_kernel/arch/x86_64/vga/
debug_overlay.rs

1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23/// Live debug framebuffer overlay.
24///
25/// Writes directly to the VGA framebuffer, bypassing VGA_WRITER and all
26/// buffers/locks.  Enabled by `debug_cfg::VGA_DEBUG_LIVE`.
27use super::panic_screen::{
28    panic_pack_rgb, PANIC_FB_ADDR, PANIC_FB_FORMAT, PANIC_FB_PITCH, PANIC_FONT_8X16,
29};
30
31// bypassing all buffers and locks.  Enabled by `debug_cfg::VGA_DEBUG_LIVE`.
32// =============================================================================
33
34/// Current cursor column for the live debug writer (0-based character column).
35static VGA_DEBUG_COL: core::sync::atomic::AtomicUsize = core::sync::atomic::AtomicUsize::new(0);
36/// Current cursor row for the live debug writer (0-based character row).
37static VGA_DEBUG_ROW: core::sync::atomic::AtomicUsize = core::sync::atomic::AtomicUsize::new(0);
38
39/// Maximum columns available on the current framebuffer (cached).
40static VGA_DEBUG_MAX_COL: core::sync::atomic::AtomicUsize = core::sync::atomic::AtomicUsize::new(0);
41/// Maximum rows available on the current framebuffer (cached).
42static VGA_DEBUG_MAX_ROW: core::sync::atomic::AtomicUsize = core::sync::atomic::AtomicUsize::new(0);
43
44/// Serializes COL/ROW mutation so concurrent writers cannot interleave cells.
45static VGA_DEBUG_LOCK: spin::Mutex<()> = spin::Mutex::new(());
46
47/// Initialise or re-initialise the live debug writer's geometry.
48/// Called automatically from `vga::init()`.
49pub fn vga_debug_init(fb_width: usize, fb_height: usize) {
50    let cols = fb_width / 8; // panic_font_8x16 glyph width
51    let rows = fb_height / 16; // panic_font_8x16 glyph height
52    let status_rows = 1; // reserve 1 row for status bar
53                         // Exclude the boot HUD band too: the overlay must never paint the bar.
54    let hud_px = super::boot_progress::band_height(fb_height, 16);
55    let hud_rows = hud_px.div_ceil(16);
56    VGA_DEBUG_MAX_COL.store(cols, core::sync::atomic::Ordering::Relaxed);
57    VGA_DEBUG_MAX_ROW.store(
58        rows.saturating_sub(status_rows + hud_rows),
59        core::sync::atomic::Ordering::Relaxed,
60    );
61    VGA_DEBUG_COL.store(0, core::sync::atomic::Ordering::Relaxed);
62    VGA_DEBUG_ROW.store(0, core::sync::atomic::Ordering::Relaxed);
63}
64
65/// Scroll the live debug area up by one line.
66///
67/// Uses a single memmove to shift pixel data, then fills the exposed line
68/// with the background colour (same technique as Linux fbcon).
69fn vga_debug_scroll() {
70    let fb_addr = PANIC_FB_ADDR.load(core::sync::atomic::Ordering::Acquire);
71    if fb_addr == 0 {
72        return;
73    }
74    let pitch = PANIC_FB_PITCH.load(core::sync::atomic::Ordering::Relaxed) as usize;
75    let max_row = VGA_DEBUG_MAX_ROW.load(core::sync::atomic::Ordering::Relaxed);
76    let fmt = PANIC_FB_FORMAT.load(core::sync::atomic::Ordering::Relaxed);
77    let bpp = (fmt >> 32) as u16;
78    let bpp_bytes = (bpp / 8) as usize;
79    if bpp_bytes < 3 || pitch == 0 || max_row <= 1 {
80        return;
81    }
82
83    let fb = fb_addr as *mut u8;
84    let line_bytes = 16 * pitch; // one text row in bytes
85    let total = (max_row - 1) * line_bytes; // all rows except the first
86    let bg = panic_pack_rgb(fmt, 0x12, 0x16, 0x1E);
87
88    unsafe {
89        // Shift content up by one text line. `copy_forward` uses 8-byte
90        // stores: `core::ptr::copy` lowers to `rep movsb`, which on uncached
91        // framebuffer memory runs at a few MB/s and makes the panel repaint
92        // visibly from top to bottom.
93        super::fastfb::copy_forward(fb, fb.add(line_bytes), total);
94        // Fill the newly exposed last line.
95        let clear = fb.add((max_row - 1) * line_bytes);
96        let line_pixels = if bpp_bytes > 0 { pitch / bpp_bytes } else { 0 };
97        vga_debug_fill_line(clear, pitch, line_pixels, bpp_bytes, bg);
98        super::fastfb::fence();
99    }
100}
101
102/// Fill a single text line (16 pixel rows) with a solid colour.
103unsafe fn vga_debug_fill_line(
104    base: *mut u8,
105    pitch: usize,
106    fill_pixels: usize,
107    bpp_bytes: usize,
108    color: u32,
109) {
110    for row in 0..16 {
111        super::fastfb::fill_pixels(base.add(row * pitch), bpp_bytes, color, fill_pixels);
112    }
113}
114
115/// Clear a single 8×16 character cell with the background colour.
116unsafe fn vga_debug_clear_cell(
117    fb: *mut u8,
118    pitch: usize,
119    x: usize,
120    y: usize,
121    bpp_bytes: usize,
122    bg: u32,
123) {
124    for row in 0..16 {
125        super::fastfb::fill_pixels(fb.add((y + row) * pitch + x * bpp_bytes), bpp_bytes, bg, 8);
126    }
127}
128
129/// Draw a single 8×16 character from the panic font.
130///
131/// First clears the entire cell with `bg`, then draws the glyph's foreground
132/// pixels.  This guarantees crisp, ghost-free text (like Linux fbcon).
133unsafe fn vga_debug_draw_glyph(
134    fb: *mut u8,
135    pitch: usize,
136    x: usize,
137    y: usize,
138    ch: u8,
139    fg: u32,
140    bg: u32,
141    bpp_bytes: usize,
142) {
143    // Clear cell first : no ghosting.
144    vga_debug_clear_cell(fb, pitch, x, y, bpp_bytes, bg);
145
146    let idx = if ch < 0x20 || ch > 0x7E {
147        0usize
148    } else {
149        (ch - 0x20) as usize
150    };
151    let gs = idx * 16;
152
153    // The cell is already background-filled: only the set pixels of each
154    // glyph row are written, as one contiguous 8-pixel store.
155    for row in 0..16 {
156        let mask = PANIC_FONT_8X16[gs + row];
157        if mask == 0 {
158            continue;
159        }
160        let mut colors = [bg; 8];
161        for col in 0..8 {
162            if (mask >> (7 - col)) & 1 != 0 {
163                colors[col] = fg;
164            }
165        }
166        super::fastfb::store_row(
167            fb.add((y + row) * pitch + x * bpp_bytes),
168            bpp_bytes,
169            &colors,
170        );
171    }
172}
173
174/// Write a string directly to the VGA framebuffer in real time.
175///
176/// Each character cell is cleared before drawing, preventing ghosting from
177/// scrolling or rapid updates.  Colours are high-contrast (light grey on
178/// dark navy : similar to Linux fbcon and FreeBSD vt(4)).
179///
180/// Newlines, carriage-returns, and tab stops are handled.  When the cursor
181/// reaches the bottom of the debug area, the content scrolls up one line.
182pub fn vga_debug_write(s: &str) {
183    let fb_addr = PANIC_FB_ADDR.load(core::sync::atomic::Ordering::Acquire);
184    if fb_addr == 0 {
185        return;
186    }
187    // Try-lock only: this path is an early/panic fallback and must never wedge.
188    let Some(_guard) = VGA_DEBUG_LOCK.try_lock() else {
189        return;
190    };
191
192    let pitch = PANIC_FB_PITCH.load(core::sync::atomic::Ordering::Relaxed) as usize;
193    let max_col = VGA_DEBUG_MAX_COL.load(core::sync::atomic::Ordering::Relaxed);
194    let max_row = VGA_DEBUG_MAX_ROW.load(core::sync::atomic::Ordering::Relaxed);
195    let fmt = PANIC_FB_FORMAT.load(core::sync::atomic::Ordering::Relaxed);
196    let bpp = (fmt >> 32) as u16;
197    let bpp_bytes = (bpp / 8) as usize;
198    if max_col == 0 || max_row == 0 || pitch == 0 || bpp_bytes < 3 {
199        return;
200    }
201
202    let fb = fb_addr as *mut u8;
203
204    // High-contrast colours (Linux vt style: light grey on navy).
205    let fg = panic_pack_rgb(fmt, 0xE2, 0xE8, 0xF0);
206    let bg = panic_pack_rgb(fmt, 0x12, 0x16, 0x1E);
207
208    let mut col = VGA_DEBUG_COL.load(core::sync::atomic::Ordering::Relaxed);
209    let mut row = VGA_DEBUG_ROW.load(core::sync::atomic::Ordering::Relaxed);
210
211    for &byte in s.as_bytes() {
212        match byte {
213            b'\n' => {
214                col = 0;
215                row += 1;
216                if row >= max_row {
217                    vga_debug_scroll();
218                    row = max_row - 1;
219                }
220            }
221            b'\r' => {
222                col = 0;
223            }
224            b'\t' => {
225                col = (col + 8) & !7;
226                if col >= max_col {
227                    col = 0;
228                    row += 1;
229                }
230                if row >= max_row {
231                    vga_debug_scroll();
232                    row = max_row - 1;
233                }
234            }
235            _ => {
236                if col >= max_col {
237                    col = 0;
238                    row += 1;
239                    if row >= max_row {
240                        vga_debug_scroll();
241                        row = max_row - 1;
242                    }
243                }
244                // SAFETY: coordinates are bounded by max_col/max_row, pitch is valid.
245                unsafe {
246                    vga_debug_draw_glyph(fb, pitch, col * 8, row * 16, byte, fg, bg, bpp_bytes);
247                }
248                col += 1;
249            }
250        }
251    }
252
253    VGA_DEBUG_COL.store(col, core::sync::atomic::Ordering::Relaxed);
254    VGA_DEBUG_ROW.store(row, core::sync::atomic::Ordering::Relaxed);
255}
256
257/// Write a newline-terminated line to the live VGA debug output.
258pub fn vga_debug_writeln(s: &str) {
259    let mut buf: [u8; 512] = [0u8; 512];
260    let max = buf.len() - 1;
261    let len = if s.len() > max {
262        // Truncate at a valid UTF-8 boundary.
263        let mut truncated = max;
264        let bytes = s.as_bytes();
265        while truncated > 0 && (bytes[truncated] & 0xC0) == 0x80 {
266            truncated -= 1;
267        }
268        truncated
269    } else {
270        s.len()
271    };
272    buf[..len].copy_from_slice(&s.as_bytes()[..len]);
273    buf[len] = b'\n';
274    if let Ok(valid) = core::str::from_utf8(&buf[..len + 1]) {
275        vga_debug_write(valid);
276    }
277}