1use core::fmt;
13use lazy_static::lazy_static;
14use spin::Mutex;
15use volatile::Volatile;
16
17const UART_BASE_ADDRESS: usize = 0x1000_0000;
19
20const UART_THR: usize = 0; const UART_LSR: usize = 5; const UART_LSR_THRE: u8 = 1 << 5; pub struct SerialPort {
29 base_address: usize,
30}
31
32impl SerialPort {
33 pub unsafe fn new(base_address: usize) -> Self {
40 SerialPort { base_address }
41 }
42
43 pub fn init(&mut self) {
45 }
47
48 fn send(&mut self, byte: u8) {
50 unsafe {
51 while !self.is_transmit_empty() {}
53
54 let thr = (self.base_address + UART_THR) as *mut Volatile<u8>;
56 (*thr).write(byte);
57 }
58 }
59
60 fn is_transmit_empty(&self) -> bool {
62 unsafe {
63 let lsr = (self.base_address + UART_LSR) as *const Volatile<u8>;
64 (*lsr).read() & UART_LSR_THRE != 0
65 }
66 }
67}
68
69impl fmt::Write for SerialPort {
70 fn write_str(&mut self, s: &str) -> fmt::Result {
71 for byte in s.bytes() {
72 self.send(byte);
73 }
74 Ok(())
75 }
76}
77
78pub fn write_bytes(data: &[u8]) {
80 crate::interrupts::without_interrupts(|| {
81 let mut port = SERIAL1.lock();
82 for &byte in data {
83 port.send(byte);
84 }
85 });
86}
87
88lazy_static! {
89 pub static ref SERIAL1: Mutex<SerialPort> = {
94 let mut serial_port = unsafe { SerialPort::new(UART_BASE_ADDRESS) };
95 serial_port.init();
96 Mutex::new(serial_port)
97 };
98}
99
100#[doc(hidden)]
109pub fn _print(args: ::core::fmt::Arguments) {
110 use core::fmt::Write;
111
112 crate::interrupts::without_interrupts(|| {
115 SERIAL1
116 .lock()
117 .write_fmt(args)
118 .expect("Printing to serial failed");
119 });
120}
121
122#[macro_export]
130macro_rules! serial_print {
131 ($($arg:tt)*) => {
132 $crate::serial::_print(format_args!($($arg)*));
133 };
134}
135
136#[macro_export]
145macro_rules! serial_println {
146 () => ($crate::serial_print!("\n"));
147 ($fmt:expr) => ($crate::serial_print!(concat!($fmt, "\n")));
148 ($fmt:expr, $($arg:tt)*) => ($crate::serial_print!(
149 concat!($fmt, "\n"), $($arg)*));
150}