Skip to main content

strat9_kernel/arch/x86_64/vga/
console_mode.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//! Console rendering mode selection.
24//!
25//! The framebuffer console has two very different cost profiles:
26//!
27//! * `Full` : the complete graphical console: decorative boot art, status
28//!   bar, scrollback scrollbar, mouse/text cursors, dirty-rect double
29//!   buffering. This is what interactive use (`top`, panels, TUI) expects.
30//! * `Lite` : a deliberately boring, DOS-like text console: no decoration,
31//!   no status bar, no cursor sprites, no scrollbar, no graphical UI. Every
32//!   line of text still reaches the screen, but the only pixels written are
33//!   glyph cells, and scrolling is a single bulk row move.
34//! * `Serial` : no framebuffer touches at all: `/dev/vasistas` stays absent
35//!   and everything is logged to COM1. On a laptop this makes boot as fast
36//!   as the hardware allows, and debugging happens over a USB-serial adapter
37//!   (or QEMU `-serial file:`).
38//!
39//! Selection is a boot parameter so a machine can be switched without
40//! recompiling: `console.mode=lite` (see `/boot/strat9.cfg` on the ESP).
41//! Without an explicit value we pick `Lite` on bare metal and `Full` under a
42//! hypervisor, where the graphical console is known to be cheap and is also
43//! what the test suite screenshots.
44
45use core::sync::atomic::{AtomicU32, AtomicU8, Ordering};
46
47use strat9_abi::boot::KernelArgs;
48
49/// Framebuffer console rendering mode.
50#[derive(Clone, Copy, Debug, PartialEq, Eq)]
51#[repr(u8)]
52pub enum ConsoleMode {
53    /// Full graphical console (decorations, status bar, TUI).
54    Full = 1,
55    /// Minimal text-only console: glyph cells and bulk scrolling.
56    Lite = 2,
57    /// No framebuffer output at all; serial only.
58    Serial = 3,
59}
60
61/// 0 means "not selected yet".
62static CONSOLE_MODE: AtomicU8 = AtomicU8::new(0);
63
64/// Frame budget in scheduler ticks (0 = not configured).
65static PRESENT_INTERVAL_TICKS: AtomicU32 = AtomicU32::new(0);
66
67/// Timer tick rate, matching `PRESENT_MIN_TICKS` in the framebuffer layer.
68const TIMER_HZ: u32 = 100;
69
70/// Default console refresh rate.
71///
72/// `TIMER_HZ / 50 = 2 ticks`, so a present is due every 2 scheduler ticks.
73/// Anything above 50 FPS needs a faster timer: 60+ would compute an interval
74/// of 1 tick and run at the 100 Hz timer rate instead.
75const DEFAULT_FPS: u32 = 50;
76
77impl ConsoleMode {
78    /// Stable name for logs and `/proc`-style reporting.
79    pub const fn as_str(self) -> &'static str {
80        match self {
81            ConsoleMode::Full => "full",
82            ConsoleMode::Lite => "lite",
83            ConsoleMode::Serial => "serial",
84        }
85    }
86
87    /// Parse a boot parameter value.
88    ///
89    /// Accepts the canonical names plus a few synonyms so a typo in a config
90    /// file degrades to "unknown, keep the default" instead of a bare screen.
91    pub fn parse(value: &str) -> Option<Self> {
92        match value.trim().to_ascii_lowercase().as_str() {
93            "full" | "gfx" | "graphical" | "rich" => Some(ConsoleMode::Full),
94            "lite" | "light" | "text" | "simple" | "basic" | "dos" => Some(ConsoleMode::Lite),
95            "serial" | "none" | "off" | "headless" => Some(ConsoleMode::Serial),
96            _ => None,
97        }
98    }
99}
100
101/// `CPUID.01H:ECX[31]` : a hypervisor is present.
102fn hypervisor_present() -> bool {
103    let (_, _, ecx, _) = crate::arch::x86_64::cpuid(1, 0);
104    ecx & (1 << 31) != 0
105}
106
107/// Pick and publish the console mode from the boot environment.
108///
109/// Idempotent: a second call returns the value selected by the first one, so
110/// later code can call it freely without depending on init ordering.
111pub fn select(args: &KernelArgs) -> ConsoleMode {
112    let current = CONSOLE_MODE.load(Ordering::Acquire);
113    if current != 0 {
114        return decode(current);
115    }
116
117    let requested = args
118        .env_get("console.mode")
119        .or_else(|| args.env_get("vga.mode"))
120        .and_then(ConsoleMode::parse);
121
122    let mode = requested.unwrap_or({
123        if hypervisor_present() {
124            ConsoleMode::Full
125        } else {
126            ConsoleMode::Lite
127        }
128    });
129
130    // Optional refresh cap: `console.fps=5` makes a slow panel usable by
131    // trading latency for far fewer full-screen copies.
132    let fps = args
133        .env_get("console.fps")
134        .and_then(|v| v.trim().parse::<u32>().ok())
135        .filter(|fps| (1..=60).contains(fps))
136        .unwrap_or(DEFAULT_FPS);
137    let interval = (TIMER_HZ / fps).max(1);
138    PRESENT_INTERVAL_TICKS.store(interval, Ordering::Release);
139
140    CONSOLE_MODE.store(mode as u8, Ordering::Release);
141    mode
142}
143
144/// Minimum number of scheduler ticks between two console presents.
145pub fn present_min_ticks() -> u64 {
146    let configured = PRESENT_INTERVAL_TICKS.load(Ordering::Relaxed);
147    if configured == 0 {
148        // Not selected yet: use the compile-time default cadence.
149        (TIMER_HZ / DEFAULT_FPS) as u64
150    } else {
151        configured as u64
152    }
153}
154
155/// Currently selected console mode.
156///
157/// Before [`select`] runs, reports the compile-time default (`Full`) so that
158/// early callers never observe an invalid state.
159pub fn current() -> ConsoleMode {
160    decode(CONSOLE_MODE.load(Ordering::Acquire))
161}
162
163fn decode(raw: u8) -> ConsoleMode {
164    match raw {
165        2 => ConsoleMode::Lite,
166        3 => ConsoleMode::Serial,
167        _ => ConsoleMode::Full,
168    }
169}
170
171/// True when the lightweight text console is active.
172#[inline]
173pub fn is_lite() -> bool {
174    current() == ConsoleMode::Lite
175}
176
177/// True when the framebuffer must not be touched at all.
178#[inline]
179pub fn is_serial() -> bool {
180    current() == ConsoleMode::Serial
181}