Skip to main content

os/
console.rs

1/*
2 * ============================================
3 * RISC-V 控制台输出模块
4 * ============================================
5 * 功能:提供控制台输出功能(替代 VGA 缓冲区)
6 * 实现:通过串口输出(RISC-V 没有 VGA 设备)
7 *
8 * 在 RISC-V 环境中,我们使用串口作为主要的输出设备
9 * ============================================
10 */
11
12use core::fmt;
13use lazy_static::lazy_static;
14use spin::Mutex;
15
16lazy_static! {
17    /// 全局 Writer 实例
18    pub static ref WRITER: Mutex<Writer> = Mutex::new(Writer::new());
19}
20
21/// 控制台写入器
22pub struct Writer {
23    column_position: usize,
24}
25
26impl Writer {
27    /// 创建新的 Writer
28    pub const fn new() -> Self {
29        Writer { column_position: 0 }
30    }
31
32    /// 写入字节
33    pub fn write_byte(&mut self, byte: u8) {
34        match byte {
35            b'\n' => {
36                self.new_line();
37            }
38            byte => {
39                // 通过串口输出
40                self.write_to_serial(byte);
41                self.column_position += 1;
42            }
43        }
44    }
45
46    /// 写入字符串
47    pub fn write_string(&mut self, s: &str) {
48        for byte in s.bytes() {
49            match byte {
50                // 可打印 ASCII 字符或换行符
51                0x20..=0x7e | b'\n' => self.write_byte(byte),
52                // 不可打印字符,输出 ■
53                _ => self.write_byte(0xfe),
54            }
55        }
56    }
57
58    /// 换行
59    fn new_line(&mut self) {
60        self.write_to_serial(b'\n');
61        self.column_position = 0;
62    }
63
64    /// 通过串口输出字节
65    fn write_to_serial(&mut self, byte: u8) {
66        use crate::serial::SERIAL1;
67        use core::fmt::Write;
68
69        // 直接写入串口(不需要通过临界区,因为已经持有 WRITER 锁)
70        let mut serial = SERIAL1.lock();
71        let _ = serial.write_char(byte as char);
72    }
73}
74
75impl Default for Writer {
76    fn default() -> Self {
77        Self::new()
78    }
79}
80
81impl fmt::Write for Writer {
82    fn write_str(&mut self, s: &str) -> fmt::Result {
83        self.write_string(s);
84        Ok(())
85    }
86}
87
88/// 底层打印函数
89#[doc(hidden)]
90pub fn _print(args: fmt::Arguments) {
91    use crate::interrupts;
92    use core::fmt::Write;
93
94    // 在临界区内执行,禁用中断以防止死锁
95    interrupts::without_interrupts(|| {
96        WRITER.lock().write_fmt(args).unwrap();
97    });
98}
99
100/// 打印宏(不换行)
101///
102/// # 用法
103/// ```rust
104/// print!("Hello");
105/// print!("x = {}", x);
106/// ```
107#[macro_export]
108macro_rules! print {
109    ($($arg:tt)*) => ($crate::console::_print(format_args!($($arg)*)));
110}
111
112/// 打印宏(换行)
113///
114/// # 用法
115/// ```rust
116/// println!();                   // 仅换行
117/// println!("Hello, RISC-V!");   // 打印并换行
118/// println!("x = {}", x);        // 格式化打印
119/// ```
120#[macro_export]
121macro_rules! println {
122    () => ($crate::print!("\n"));
123    ($($arg:tt)*) => ($crate::print!("{}\n", format_args!($($arg)*)));
124}