use core::fmt;
use lazy_static::lazy_static;
use spin::Mutex;
use volatile::Volatile;
const UART_BASE_ADDRESS: usize = 0x1000_0000;
const UART_THR: usize = 0; const UART_LSR: usize = 5;
const UART_LSR_THRE: u8 = 1 << 5;
pub struct SerialPort {
base_address: usize,
}
impl SerialPort {
pub unsafe fn new(base_address: usize) -> Self {
SerialPort { base_address }
}
pub fn init(&mut self) {
}
fn send(&mut self, byte: u8) {
unsafe {
while !self.is_transmit_empty() {}
let thr = (self.base_address + UART_THR) as *mut Volatile<u8>;
(*thr).write(byte);
}
}
fn is_transmit_empty(&self) -> bool {
unsafe {
let lsr = (self.base_address + UART_LSR) as *const Volatile<u8>;
(*lsr).read() & UART_LSR_THRE != 0
}
}
}
impl fmt::Write for SerialPort {
fn write_str(&mut self, s: &str) -> fmt::Result {
for byte in s.bytes() {
self.send(byte);
}
Ok(())
}
}
pub fn write_bytes(data: &[u8]) {
crate::interrupts::without_interrupts(|| {
let mut port = SERIAL1.lock();
for &byte in data {
port.send(byte);
}
});
}
lazy_static! {
pub static ref SERIAL1: Mutex<SerialPort> = {
let mut serial_port = unsafe { SerialPort::new(UART_BASE_ADDRESS) };
serial_port.init();
Mutex::new(serial_port)
};
}
#[doc(hidden)]
pub fn _print(args: ::core::fmt::Arguments) {
use core::fmt::Write;
crate::interrupts::without_interrupts(|| {
SERIAL1
.lock()
.write_fmt(args)
.expect("Printing to serial failed");
});
}
#[macro_export]
macro_rules! serial_print {
($($arg:tt)*) => {
$crate::serial::_print(format_args!($($arg)*));
};
}
#[macro_export]
macro_rules! serial_println {
() => ($crate::serial_print!("\n"));
($fmt:expr) => ($crate::serial_print!(concat!($fmt, "\n")));
($fmt:expr, $($arg:tt)*) => ($crate::serial_print!(
concat!($fmt, "\n"), $($arg)*));
}