Skip to main content

proka_kernel/output/
serial.rs

1extern crate alloc;
2use crate::config::SERIAL_LOG_PORT;
3use crate::drivers::DEVICE_MANAGER;
4use uart_16550::SerialPort;
5
6pub fn serial_fallback(args: ::core::fmt::Arguments) {
7    use core::fmt::Write;
8    let mut serial_port = unsafe { SerialPort::new(SERIAL_LOG_PORT as u16) };
9    serial_port.init();
10    serial_port
11        .write_fmt(args)
12        .expect("Printing to serial failed");
13}
14
15/* The functions and macros in debug mode */
16#[doc(hidden)]
17#[cfg(debug_assertions)]
18pub fn _print(args: ::core::fmt::Arguments) {
19    use core::fmt::Write;
20
21    // 获取设备管理器锁
22    let device_manager = DEVICE_MANAGER.read();
23
24    // 尝试获取设备号为 (1, 0) 的字符设备
25    match device_manager.get_device_by_major_minor(1, 0) {
26        Some(device) => {
27            // 尝试将设备转换为字符设备
28            if let Some(char_device_arc) = device.as_char_device() {
29                let mut buffer = alloc::string::String::new();
30                buffer.write_fmt(args).expect("Failed to format string");
31
32                char_device_arc
33                    .write(buffer.as_bytes())
34                    .expect("Printing to serial failed");
35            } else {
36                serial_fallback(args);
37            }
38        }
39        None => {
40            // 设备 (1,0) 未找到
41            serial_fallback(args);
42        }
43    }
44}
45
46/// Prints to the host through the serial interface.
47#[macro_export]
48#[cfg(debug_assertions)]
49macro_rules! serial_print {
50    ($($arg:tt)*) => {
51        $crate::output::serial::_print(format_args!($($arg)*));
52    };
53}
54
55/// Prints to the host through the serial interface, appending a newline.
56#[macro_export]
57#[cfg(debug_assertions)]
58macro_rules! serial_println {
59    () => ($crate::serial_print!("\n"));
60    ($fmt:expr) => ($crate::serial_print!(concat!($fmt, "\n")));
61    ($fmt:expr, $($arg:tt)*) => ($crate::serial_print!(
62        concat!($fmt, "\n"), $($arg)*));
63}
64
65/* The macros and function not in debug mode (empty) */
66#[doc(hidden)]
67#[cfg(not(debug_assertions))]
68pub fn _print(args: ::core::fmt::Arguments) {}
69
70#[macro_export]
71#[cfg(not(debug_assertions))]
72macro_rules! serial_print {
73    ($($arg:tt)*) => {};
74}
75
76#[macro_export]
77#[cfg(not(debug_assertions))]
78macro_rules! serial_println {
79    () => {};
80    ($fmt:expr) => {};
81    ($fmt:expr, $($arg:tt)*) => {};
82}