From 523130a69e6b5a372b482a67f0e7b98ff5364817 Mon Sep 17 00:00:00 2001 From: apio Date: Tue, 1 Nov 2022 10:55:42 +0100 Subject: [PATCH] Kernel: Add try_print! and try_println! --- moon/src/log.rs | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/moon/src/log.rs b/moon/src/log.rs index 711ed888..4a0c317c 100644 --- a/moon/src/log.rs +++ b/moon/src/log.rs @@ -1,19 +1,48 @@ use crate::arch::io::SERIAL; use core::fmt; +/// Locks the serial port and writes formatted output. #[macro_export] macro_rules! print { ($($arg:tt)*) => ($crate::log::_print(format_args!($($arg)*))); } +/// Tries to lock the serial port and writes formatted output. +/// Should be used in interrupt handlers, as it does not block but silently fails. +/// (If we are blocked waiting for interrupted code to unlock a lock, that's an instant deadlock unless we are on SMP and another CPU schedules that code) +#[macro_export] +macro_rules! try_print { + ($($arg:tt)*) => ($crate::log::_try_print(format_args!($($arg)*))); +} + +/// Locks the serial port and writes formatted output with a trailing newline. #[macro_export] macro_rules! println { () => ($crate::print!("\n")); ($($arg:tt)*) => ($crate::print!("{}\n", format_args!($($arg)*))); } +/// Tries to lock the serial port and writes formatted output with a trailing newline. +/// Should be used in interrupt handlers, as it does not block but silently fails. +/// (If we are blocked waiting for interrupted code to unlock a lock, that's an instant deadlock unless we are on SMP and another CPU schedules that code) +#[macro_export] +macro_rules! try_println { + () => ($crate::try_print!("\n")); + ($($arg:tt)*) => ($crate::try_print!("{}\n", format_args!($($arg)*))); +} + #[doc(hidden)] pub fn _print(args: fmt::Arguments) { use core::fmt::Write; SERIAL.lock().write_fmt(args).unwrap(); +} + +#[doc(hidden)] +pub fn _try_print(args: fmt::Arguments) { + use core::fmt::Write; + let serial = SERIAL.try_lock(); + if serial.is_some() + { + serial.unwrap().write_fmt(args).unwrap(); + } } \ No newline at end of file