Skip to main content

strat9_kernel/arch/x86_64/
vgabuf.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//! Bounded, allocation-free SMP queue between logging and framebuffer rendering.
24//! Formatting/rendering never retains a reference to a released queue slot.
25
26#[path = "vga/log_queue.rs"]
27mod log_queue;
28use core::sync::atomic::{AtomicBool, Ordering};
29use log_queue::{Line, LogQueue};
30
31static CONSOLE_TASK_ACTIVE: AtomicBool = AtomicBool::new(false);
32
33pub fn console_task_active() -> bool {
34    CONSOLE_TASK_ACTIVE.load(Ordering::Acquire)
35}
36
37pub const VGABUF_CAPACITY: usize = log_queue::CAPACITY;
38pub const VGABUF_LINE_LEN: usize = log_queue::LINE_LEN;
39static QUEUE: LogQueue = LogQueue::new();
40const FLUSH_BATCH: usize = 30;
41
42pub fn vgabuf_write(line: &[u8]) {
43    QUEUE.push(line);
44}
45pub fn vgabuf_total_written() -> usize {
46    QUEUE.written()
47}
48pub fn vgabuf_total_dropped() -> usize {
49    QUEUE.dropped()
50}
51
52fn write_line(writer: &mut impl core::fmt::Write, line: &Line) {
53    if let Ok(s) = core::str::from_utf8(line.as_bytes()) {
54        let _ = writer.write_str(s);
55        if !s.ends_with('\n') {
56            let _ = writer.write_str("\n");
57        }
58    } else {
59        let _ = writer.write_str("<non-utf8>\n");
60    }
61}
62
63/// Render a bounded batch. Retrying pending presents also displays the last
64/// keyboard echo/log fragment when no subsequent message arrives.
65pub fn vgabuf_flush_to_framebuffer() {
66    if !crate::arch::x86_64::vga::is_available() || !crate::vasistas_state::kernel_fb_allowed() {
67        vgabuf_drain_discard();
68        return;
69    }
70    let Some(mut writer) = crate::arch::x86_64::vga::VGA_WRITER.try_lock() else {
71        return;
72    };
73    let mut flushed = 0;
74    for _ in 0..FLUSH_BATCH {
75        let Some(line) = QUEUE.pop() else {
76            break;
77        };
78        write_line(&mut *writer, &line);
79        flushed += 1;
80    }
81    if flushed > 0 {
82        writer.flush_display();
83    } else {
84        writer.present_if_due(false);
85    }
86}
87
88fn vgabuf_drain_discard() {
89    for _ in 0..VGABUF_CAPACITY {
90        if QUEUE.pop().is_none() {
91            break;
92        }
93    }
94}
95
96pub fn vgabuf_flush_all() {
97    if !crate::arch::x86_64::vga::is_available() || !crate::vasistas_state::kernel_fb_allowed() {
98        vgabuf_drain_discard();
99        return;
100    }
101    let Some(mut writer) = crate::arch::x86_64::vga::VGA_WRITER.try_lock() else {
102        vgabuf_flush_all_direct();
103        return;
104    };
105    for _ in 0..VGABUF_CAPACITY {
106        let Some(line) = QUEUE.pop() else {
107            break;
108        };
109        write_line(&mut *writer, &line);
110    }
111    writer.present_if_due(true);
112}
113
114fn vgabuf_flush_all_direct() {
115    if !crate::vasistas_state::kernel_fb_allowed() {
116        vgabuf_drain_discard();
117        return;
118    }
119    // Own the bytes until drawing completes; released slots may immediately be
120    // reused on another CPU. Limit scratch storage to about 4 KiB in panic context.
121    const MAX_LINES: usize = 16;
122    let mut owned = [Line::EMPTY; MAX_LINES];
123    let mut count = 0;
124    for slot in &mut owned {
125        let Some(line) = QUEUE.pop() else {
126            break;
127        };
128        *slot = line;
129        count += 1;
130    }
131    let mut lines = [""; MAX_LINES];
132    for i in 0..count {
133        lines[i] = core::str::from_utf8(owned[i].as_bytes()).unwrap_or("<non-utf8>");
134    }
135    let mut lines = [""; MAX_LINES];
136    for i in 0..count {
137        lines[i] = core::str::from_utf8(owned[i].as_bytes()).unwrap_or("<non-utf8>");
138    }
139}
140
141/// One render opportunity per timer tick, independent of commands/status I/O.
142///
143/// The console task owns the writer for this whole tick: it drains the mouse
144/// input ring first, then a bounded batch of log lines, then presents once.
145pub extern "C" fn console_task_main() -> ! {
146    CONSOLE_TASK_ACTIVE.store(true, Ordering::Release);
147    let mut input_state = crate::shell::vga_input::InputState::new();
148    let mut last_tick = u64::MAX;
149    loop {
150        // A display server owns the framebuffer: render nothing (no clear, no
151        // panel, no cursor) until kernel_fb_allowed() returns, then resume.
152        if !crate::vasistas_state::kernel_fb_allowed() {
153            crate::process::sleep_current_task_ticks(1);
154            continue;
155        }
156        let tick = crate::process::scheduler::ticks();
157        if tick != last_tick {
158            last_tick = tick;
159            console_render_tick(&mut input_state);
160        }
161        // Rendering is tick-paced; sleep so this worker does not spin between
162        // frames and compete with interactive tasks.
163        crate::process::sleep_current_task_ticks(1);
164    }
165}
166
167/// Single writer acquisition per tick: apply deferred mouse input, drain a
168/// bounded log batch, then present once. If the lock is busy, retry next tick.
169fn console_render_tick(input_state: &mut crate::shell::vga_input::InputState) {
170    if !crate::arch::x86_64::vga::is_available() || !crate::vasistas_state::kernel_fb_allowed() {
171        vgabuf_drain_discard();
172        crate::shell::vga_input::discard();
173        return;
174    }
175    let Some(mut writer) = crate::arch::x86_64::vga::VGA_WRITER.try_lock() else {
176        return;
177    };
178
179    let mut applied = crate::shell::vga_input::take_pending();
180    // Apply every tick (not only when the flag was set) so a deferred visual
181    // still drains when the pointer stops moving while the button is held.
182    applied |= crate::shell::vga_input::apply_input(&mut *writer, input_state);
183    if !crate::debug_cfg::is_quiet() {
184        for _ in 0..FLUSH_BATCH {
185            let Some(line) = QUEUE.pop() else {
186                break;
187            };
188            write_line(&mut *writer, &line);
189            applied = true;
190        }
191    }
192
193    // Eased wheel scroll: advance at most one line per tick, then present.
194    applied |= writer.tick_scroll_anim();
195
196    if applied {
197        writer.flush_display();
198    } else {
199        writer.present_if_due(false);
200    }
201}