Move the log lock to a better location

This commit is contained in:
Ruihan Li
2025-04-15 22:22:07 +08:00
committed by Tate, Hongliang Tian
parent 67e5e5a651
commit d6e40933b8
6 changed files with 46 additions and 73 deletions

View File

@ -15,12 +15,6 @@ impl log::Log for AsterLogger {
fn log(&self, record: &Record) {
let timestamp = Jiffies::elapsed().as_duration().as_secs_f64();
// Use a global lock to prevent interleaving of log messages.
use ostd::sync::SpinLock;
static RECORD_LOCK: SpinLock<()> = SpinLock::new(());
let _lock = RECORD_LOCK.disable_irq().lock();
print_logs(record, timestamp);
}

View File

@ -5,26 +5,34 @@
//! FIXME: It will print to all `virtio-console` devices, which is not a good choice.
//!
use core::fmt::{Arguments, Write};
use alloc::{collections::btree_map::BTreeMap, fmt, string::String, sync::Arc};
use core::fmt::Write;
struct VirtioConsolesPrinter;
impl Write for VirtioConsolesPrinter {
fn write_str(&mut self, s: &str) -> core::fmt::Result {
// We must call `all_devices_lock` instead of `all_devices` here, as `all_devices` invokes
// the clone method of String and Arc, which may lead to a deadlock when there is low memory
// in the heap (The heap allocator will log a message when memory is low.).
let devices = aster_console::all_devices_lock();
for (_, device) in devices.iter() {
device.send(s.as_bytes());
}
Ok(())
}
}
use aster_console::AnyConsoleDevice;
use ostd::sync::{LocalIrqDisabled, SpinLockGuard};
/// Prints the formatted arguments to the standard output.
pub fn _print(args: Arguments) {
VirtioConsolesPrinter.write_fmt(args).unwrap();
pub fn _print(args: fmt::Arguments) {
// We must call `all_devices_lock` instead of `all_devices` here, as `all_devices` invokes the
// `clone` method of `String` and `Arc`, which may lead to a deadlock when there is low memory
// in the heap. (The heap allocator will log a message when memory is low.)
//
// Also, holding the lock will prevent the logs from interleaving.
let devices = aster_console::all_devices_lock();
struct Printer<'a>(
SpinLockGuard<'a, BTreeMap<String, Arc<dyn AnyConsoleDevice>>, LocalIrqDisabled>,
);
impl Write for Printer<'_> {
fn write_str(&mut self, s: &str) -> fmt::Result {
self.0
.values()
.for_each(|console| console.send(s.as_bytes()));
Ok(())
}
}
Printer(devices).write_fmt(args).unwrap();
}
/// Copied from Rust std: <https://github.com/rust-lang/rust/blob/master/library/std/src/macros.rs>