Skip to main content

strat9_kernel/arch/x86_64/vga/
log_queue.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//! Fixed-storage log queue. Safe publication under SMP and bounded overflow.
24use core::sync::atomic::{AtomicUsize, Ordering};
25use heapless::mpmc::Queue;
26
27pub const CAPACITY: usize = 512;
28pub const LINE_LEN: usize = 256;
29
30#[derive(Clone, Copy)]
31pub struct Line {
32    pub bytes: [u8; LINE_LEN],
33    pub len: usize,
34}
35
36impl Line {
37    pub const EMPTY: Self = Self {
38        bytes: [0; LINE_LEN],
39        len: 0,
40    };
41
42    pub fn as_bytes(&self) -> &[u8] {
43        &self.bytes[..self.len]
44    }
45}
46
47pub struct LogQueue {
48    queue: Queue<Line, CAPACITY>,
49    written: AtomicUsize,
50    dropped: AtomicUsize,
51}
52
53impl LogQueue {
54    // This lossy log sink permits transient enqueue failures and retries
55    // dequeue on the next display tick, as required by heapless::mpmc.
56    #[expect(deprecated, reason = "log drops and delayed dequeue are supported")]
57    pub const fn new() -> Self {
58        Self {
59            queue: Queue::new(),
60            written: AtomicUsize::new(0),
61            dropped: AtomicUsize::new(0),
62        }
63    }
64
65    pub fn push(&self, bytes: &[u8]) {
66        if bytes.is_empty() {
67            return;
68        }
69        let mut line = Line::EMPTY;
70        line.len = bytes.len().min(LINE_LEN - 1);
71        line.bytes[..line.len].copy_from_slice(&bytes[..line.len]);
72        if self.queue.enqueue(line).is_ok() {
73            self.written.fetch_add(1, Ordering::Relaxed);
74        } else {
75            self.dropped.fetch_add(1, Ordering::Relaxed);
76        }
77    }
78
79    pub fn pop(&self) -> Option<Line> {
80        self.queue.dequeue()
81    }
82    pub fn written(&self) -> usize {
83        self.written.load(Ordering::Relaxed)
84    }
85    pub fn dropped(&self) -> usize {
86        self.dropped.load(Ordering::Relaxed)
87    }
88}