From 2eab6dd743e94a86a685f1f3c01e599adf86610a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9B=BE=E4=BF=8A?= <110876916+ZZJJWarth@users.noreply.github.com> Date: Thu, 16 May 2024 17:25:23 +0800 Subject: [PATCH] =?UTF-8?q?feat(log):=20=E5=B0=86=E5=86=85=E6=A0=B8?= =?UTF-8?q?=E6=97=A5=E5=BF=97=E7=BB=9F=E4=B8=80=E4=B8=BA=E6=96=B0=E7=9A=84?= =?UTF-8?q?logger=20(#814)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/kernel/locking/mutex.md | 4 +- docs/kernel/locking/spinlock.md | 4 +- kernel/crates/unified-init/src/lib.rs | 6 +- kernel/src/arch/riscv64/driver/of.rs | 4 +- kernel/src/arch/riscv64/init/mod.rs | 11 +- kernel/src/arch/riscv64/interrupt/handle.rs | 40 +++--- kernel/src/arch/riscv64/ipc/signal.rs | 13 +- kernel/src/arch/riscv64/mm/init.rs | 24 ++-- kernel/src/arch/riscv64/pci/pci_host_ecam.rs | 9 +- kernel/src/arch/riscv64/process/idle.rs | 8 +- kernel/src/arch/riscv64/process/mod.rs | 10 +- kernel/src/arch/riscv64/process/syscall.rs | 12 +- kernel/src/arch/riscv64/smp/mod.rs | 14 +- kernel/src/arch/riscv64/syscall/mod.rs | 4 +- kernel/src/arch/riscv64/time.rs | 9 +- kernel/src/arch/x86_64/acpi.rs | 5 +- .../src/arch/x86_64/driver/apic/apic_timer.rs | 19 ++- kernel/src/arch/x86_64/driver/apic/ioapic.rs | 14 +- .../arch/x86_64/driver/apic/lapic_vector.rs | 6 +- kernel/src/arch/x86_64/driver/apic/mod.rs | 14 +- kernel/src/arch/x86_64/driver/apic/x2apic.rs | 11 +- kernel/src/arch/x86_64/driver/apic/xapic.rs | 13 +- kernel/src/arch/x86_64/driver/hpet.rs | 14 +- kernel/src/arch/x86_64/driver/rtc.rs | 4 +- kernel/src/arch/x86_64/driver/tsc.rs | 38 ++--- kernel/src/arch/x86_64/init/mod.rs | 11 +- kernel/src/arch/x86_64/interrupt/ipi.rs | 10 +- kernel/src/arch/x86_64/interrupt/mod.rs | 4 +- kernel/src/arch/x86_64/interrupt/trap.rs | 46 +++---- kernel/src/arch/x86_64/ipc/signal.rs | 40 +++--- kernel/src/arch/x86_64/kvm/mod.rs | 15 +- kernel/src/arch/x86_64/kvm/vmx/mmu.rs | 6 +- kernel/src/arch/x86_64/kvm/vmx/vcpu.rs | 51 +++---- kernel/src/arch/x86_64/kvm/vmx/vmexit.rs | 31 +++-- .../arch/x86_64/kvm/vmx/vmx_asm_wrapper.rs | 13 +- kernel/src/arch/x86_64/mm/fault.rs | 14 +- kernel/src/arch/x86_64/mm/mod.rs | 43 +++--- kernel/src/arch/x86_64/pci/pci.rs | 5 +- kernel/src/arch/x86_64/process/idle.rs | 5 +- kernel/src/arch/x86_64/process/mod.rs | 10 +- kernel/src/arch/x86_64/process/syscall.rs | 16 +-- kernel/src/arch/x86_64/smp/mod.rs | 6 +- kernel/src/arch/x86_64/syscall/mod.rs | 7 +- kernel/src/driver/acpi/mod.rs | 10 +- kernel/src/driver/acpi/sysfs.rs | 12 +- kernel/src/driver/base/block/block_device.rs | 30 ++-- kernel/src/driver/base/char/mod.rs | 8 +- kernel/src/driver/base/device/bus.rs | 13 +- kernel/src/driver/base/device/dd.rs | 35 ++--- kernel/src/driver/base/device/driver.rs | 5 +- kernel/src/driver/base/device/init.rs | 23 ++-- kernel/src/driver/base/device/mod.rs | 19 +-- kernel/src/driver/base/kobject.rs | 6 +- kernel/src/driver/base/platform/subsys.rs | 5 +- .../driver/block/cache/cached_block_device.rs | 3 +- kernel/src/driver/block/virtio_blk.rs | 12 +- kernel/src/driver/clocksource/acpi_pm.rs | 15 +- kernel/src/driver/clocksource/timer_riscv.rs | 2 +- kernel/src/driver/disk/ahci/ahcidisk.rs | 24 ++-- kernel/src/driver/disk/ahci/mod.rs | 26 ++-- kernel/src/driver/firmware/efi/fdt.rs | 5 +- kernel/src/driver/firmware/efi/init.rs | 31 +++-- kernel/src/driver/firmware/efi/memmap.rs | 5 +- kernel/src/driver/firmware/efi/mod.rs | 8 +- kernel/src/driver/firmware/efi/tables.rs | 21 +-- .../driver/input/ps2_mouse/ps_mouse_device.rs | 9 +- .../driver/input/ps2_mouse/ps_mouse_driver.rs | 5 +- kernel/src/driver/input/serio/i8042/mod.rs | 3 +- kernel/src/driver/input/serio/subsys.rs | 5 +- kernel/src/driver/irqchip/riscv_intc.rs | 5 +- .../src/driver/irqchip/riscv_sifive_plic.rs | 35 ++--- kernel/src/driver/net/e1000e/e1000e.rs | 15 +- kernel/src/driver/net/e1000e/e1000e_driver.rs | 4 +- kernel/src/driver/net/virtio_net.rs | 16 +-- kernel/src/driver/open_firmware/fdt.rs | 41 +++--- kernel/src/driver/pci/attr.rs | 9 +- kernel/src/driver/pci/ecam.rs | 6 +- kernel/src/driver/pci/pci.rs | 56 ++++---- kernel/src/driver/pci/pci_irq.rs | 5 +- kernel/src/driver/pci/root.rs | 2 +- kernel/src/driver/pci/subsys.rs | 5 +- kernel/src/driver/rtc/class.rs | 3 +- kernel/src/driver/serial/serial8250/mod.rs | 3 +- kernel/src/driver/tty/tty_driver.rs | 3 +- .../tty/virtual_terminal/virtual_console.rs | 5 +- .../fbdev/base/fbcon/framebuffer_console.rs | 3 +- .../src/driver/video/fbdev/base/fbcon/mod.rs | 11 +- kernel/src/driver/video/fbdev/base/fbmem.rs | 3 +- kernel/src/driver/video/fbdev/base/fbsysfs.rs | 5 +- kernel/src/driver/video/fbdev/base/mod.rs | 2 +- kernel/src/driver/video/fbdev/vesafb.rs | 7 +- kernel/src/driver/video/mod.rs | 6 +- kernel/src/driver/virtio/irq.rs | 3 +- kernel/src/driver/virtio/mmio.rs | 3 +- kernel/src/driver/virtio/sysfs.rs | 15 +- kernel/src/driver/virtio/transport_mmio.rs | 5 +- kernel/src/driver/virtio/transport_pci.rs | 4 +- kernel/src/driver/virtio/virtio.rs | 13 +- kernel/src/driver/virtio/virtio_impl.rs | 2 +- kernel/src/exception/handle.rs | 23 ++-- kernel/src/exception/irqchip.rs | 7 +- kernel/src/exception/irqdomain.rs | 17 +-- kernel/src/exception/manage.rs | 47 +++---- kernel/src/exception/softirq.rs | 18 +-- kernel/src/exception/sysfs.rs | 3 +- kernel/src/filesystem/devfs/mod.rs | 12 +- kernel/src/filesystem/devpts/mod.rs | 3 +- kernel/src/filesystem/fat/bpb.rs | 26 ++-- kernel/src/filesystem/fat/entry.rs | 28 ++-- kernel/src/filesystem/fat/fs.rs | 46 +++---- kernel/src/filesystem/kernfs/mod.rs | 5 +- kernel/src/filesystem/mbr.rs | 5 +- kernel/src/filesystem/procfs/kmsg.rs | 5 +- kernel/src/filesystem/procfs/mod.rs | 8 +- kernel/src/filesystem/sysfs/file.rs | 8 +- kernel/src/filesystem/sysfs/group.rs | 10 +- kernel/src/filesystem/sysfs/mod.rs | 10 +- kernel/src/filesystem/sysfs/symlink.rs | 2 +- kernel/src/filesystem/vfs/core.rs | 22 +-- kernel/src/filesystem/vfs/file.rs | 10 +- kernel/src/filesystem/vfs/mod.rs | 6 +- kernel/src/filesystem/vfs/mount.rs | 2 +- kernel/src/filesystem/vfs/open.rs | 5 +- kernel/src/filesystem/vfs/syscall.rs | 11 +- kernel/src/init/initial_kthread.rs | 8 +- kernel/src/ipc/shm.rs | 5 +- kernel/src/ipc/signal.rs | 18 +-- kernel/src/ipc/signal_types.rs | 2 +- kernel/src/ipc/syscall.rs | 12 +- kernel/src/lib.rs | 4 +- kernel/src/libs/elf.rs | 52 +++---- kernel/src/libs/futex/futex.rs | 5 +- kernel/src/libs/keyboard_parser.rs | 12 +- kernel/src/libs/lib_ui/textui.rs | 12 +- kernel/src/libs/notifier.rs | 8 +- kernel/src/libs/printk.rs | 130 ++++++++++-------- kernel/src/libs/rbtree.rs | 23 ++-- kernel/src/libs/semaphore.rs | 5 +- kernel/src/libs/wait_queue.rs | 6 +- kernel/src/misc/ksysfs.rs | 3 +- kernel/src/mm/allocator/buddy.rs | 40 +++--- kernel/src/mm/allocator/slab.rs | 5 +- kernel/src/mm/c_adapter.rs | 12 +- kernel/src/mm/early_ioremap.rs | 8 +- kernel/src/mm/init.rs | 4 +- kernel/src/mm/kernel_mapper.rs | 2 +- kernel/src/mm/memblock.rs | 5 +- kernel/src/mm/mmio_buddy.rs | 42 +++--- kernel/src/mm/page.rs | 17 ++- kernel/src/mm/syscall.rs | 12 +- kernel/src/mm/ucontext.rs | 50 +++---- kernel/src/net/event_poll/mod.rs | 2 +- kernel/src/net/net_core.rs | 22 +-- kernel/src/net/socket/inet.rs | 86 ++++++------ kernel/src/net/socket/mod.rs | 13 +- kernel/src/net/syscall.rs | 8 +- kernel/src/process/exec.rs | 8 +- kernel/src/process/exit.rs | 11 +- kernel/src/process/fork.rs | 3 +- kernel/src/process/kthread.rs | 10 +- kernel/src/process/mod.rs | 24 ++-- kernel/src/process/syscall.rs | 6 +- kernel/src/process/timer.rs | 2 +- kernel/src/sched/fair.rs | 16 +-- kernel/src/sched/mod.rs | 18 +-- kernel/src/smp/cpu/mod.rs | 9 +- kernel/src/smp/init.rs | 4 +- kernel/src/syscall/misc.rs | 3 +- kernel/src/syscall/mod.rs | 38 ++--- kernel/src/syscall/user_access.rs | 4 +- kernel/src/time/clocksource.rs | 43 +++--- kernel/src/time/jiffies.rs | 7 +- kernel/src/time/syscall.rs | 3 +- kernel/src/time/timekeeping.rs | 14 +- kernel/src/time/timer.rs | 24 ++-- kernel/src/virt/kvm/host_mem.rs | 18 ++- kernel/src/virt/kvm/kvm_dev.rs | 9 +- kernel/src/virt/kvm/mod.rs | 17 +-- kernel/src/virt/kvm/vcpu_dev.rs | 18 ++- kernel/src/virt/kvm/vm.rs | 8 +- kernel/src/virt/kvm/vm_dev.rs | 15 +- 181 files changed, 1321 insertions(+), 1261 deletions(-) diff --git a/docs/kernel/locking/mutex.md b/docs/kernel/locking/mutex.md index 9071de7b..a3eb8484 100644 --- a/docs/kernel/locking/mutex.md +++ b/docs/kernel/locking/mutex.md @@ -59,10 +59,10 @@ let x :Mutex>= Mutex::new(Vec::new()); g.push(2); assert!(g.as_slice() == [1, 2, 2] || g.as_slice() == [2, 2, 1]); // 在此处,Mutex是加锁的状态 - kdebug!("x={:?}", x); + debug!("x={:?}", x); } // 由于上方的变量`g`,也就是Mutex守卫的生命周期结束,自动释放了Mutex。因此,在此处,Mutex是放锁的状态 - kdebug!("x={:?}", x); + debug!("x={:?}", x); ```   对于结构体内部的变量,我们可以使用Mutex进行细粒度的加锁,也就是使用Mutex包裹需要细致加锁的成员变量,比如这样: diff --git a/docs/kernel/locking/spinlock.md b/docs/kernel/locking/spinlock.md index c4b90f01..a9bcf7bd 100644 --- a/docs/kernel/locking/spinlock.md +++ b/docs/kernel/locking/spinlock.md @@ -65,10 +65,10 @@ let x :SpinLock>= SpinLock::new(Vec::new()); g.push(2); assert!(g.as_slice() == [1, 2, 2] || g.as_slice() == [2, 2, 1]); // 在此处,SpinLock是加锁的状态 - kdebug!("x={:?}", x); + debug!("x={:?}", x); } // 由于上方的变量`g`,也就是SpinLock守卫的生命周期结束,自动释放了SpinLock。因此,在此处,SpinLock是放锁的状态 - kdebug!("x={:?}", x); + debug!("x={:?}", x); ```   对于结构体内部的变量,我们可以使用SpinLock进行细粒度的加锁,也就是使用SpinLock包裹需要细致加锁的成员变量,比如这样: diff --git a/kernel/crates/unified-init/src/lib.rs b/kernel/crates/unified-init/src/lib.rs index b1dac7ef..770186d3 100644 --- a/kernel/crates/unified-init/src/lib.rs +++ b/kernel/crates/unified-init/src/lib.rs @@ -40,7 +40,7 @@ macro_rules! define_unified_initializer_slice { static $name: [::unified_init::UnifiedInitializer] = [..]; }; () => { - compile_error!( + compile_kerror!( "define_unified_initializer_slice! requires at least one argument: slice_name" ); }; @@ -54,7 +54,7 @@ macro_rules! define_public_unified_initializer_slice { pub static $name: [::unified_init::UnifiedInitializer] = [..]; }; () => { - compile_error!( + compile_kerror!( "define_unified_initializer_slice! requires at least one argument: slice_name" ); }; @@ -66,7 +66,7 @@ macro_rules! unified_init { ($initializer_slice:ident) => { for initializer in $initializer_slice.iter() { initializer.call().unwrap_or_else(|e| { - kerror!("Failed to call initializer {}: {:?}", initializer.name(), e); + log::error!("Failed to call initializer {}: {:?}", initializer.name(), e); }); } }; diff --git a/kernel/src/arch/riscv64/driver/of.rs b/kernel/src/arch/riscv64/driver/of.rs index 2aa6adbe..4c93b91a 100644 --- a/kernel/src/arch/riscv64/driver/of.rs +++ b/kernel/src/arch/riscv64/driver/of.rs @@ -17,7 +17,7 @@ impl OpenFirmwareFdtDriver { let offset = fdt_paddr.data() & crate::arch::MMArch::PAGE_OFFSET_MASK; let map_size = page_align_up(fdt_size + offset); let map_paddr = PhysAddr::new(fdt_paddr.data() & crate::arch::MMArch::PAGE_MASK); - // kdebug!( + // debug!( // "map_fdt paddr: {:?}, map_pa: {:?},fdt_size: {}, size: {:?}", // fdt_paddr, // map_paddr, @@ -28,7 +28,7 @@ impl OpenFirmwareFdtDriver { // drop the boot params guard in order to avoid deadlock drop(bp_guard); - // kdebug!("map_fdt: map fdt to {:?}, size: {}", map_paddr, map_size); + // debug!("map_fdt: map fdt to {:?}, size: {}", map_paddr, map_size); mmio_guard.map_phys(map_paddr, map_size)?; let mut bp_guard = boot_params().write(); let vaddr = mmio_guard.vaddr() + offset; diff --git a/kernel/src/arch/riscv64/init/mod.rs b/kernel/src/arch/riscv64/init/mod.rs index 166965c7..b71c077d 100644 --- a/kernel/src/arch/riscv64/init/mod.rs +++ b/kernel/src/arch/riscv64/init/mod.rs @@ -1,11 +1,11 @@ use fdt::node::FdtNode; +use log::{debug, info}; use system_error::SystemError; use crate::{ arch::{driver::sbi::SbiDriver, mm::init::mm_early_init}, driver::{firmware::efi::init::efi_init, open_firmware::fdt::open_firmware_fdt_driver}, init::{boot_params, init::start_kernel}, - kdebug, kinfo, mm::{memblock::mem_block_manager, PhysAddr, VirtAddr}, print, println, smp::cpu::ProcessorId, @@ -112,13 +112,12 @@ pub fn early_setup_arch() -> Result<(), SystemError> { arch_boot_params_guard.arch.fdt_paddr = fdt_paddr; arch_boot_params_guard.arch.fdt_size = fdt.total_size(); arch_boot_params_guard.arch.boot_hartid = ProcessorId::new(hartid); - // kdebug!("fdt_paddr: {:?}, fdt_size: {}", fdt_paddr, fdt.total_size()); + // debug!("fdt_paddr: {:?}, fdt_size: {}", fdt_paddr, fdt.total_size()); drop(arch_boot_params_guard); - kinfo!( + info!( "DragonOS kernel is running on hart {}, fdt address:{:?}", - hartid, - fdt_paddr + hartid, fdt_paddr ); mm_early_init(); @@ -127,7 +126,7 @@ pub fn early_setup_arch() -> Result<(), SystemError> { unsafe { parse_dtb() }; for x in mem_block_manager().to_iter() { - kdebug!("before efi: {x:?}"); + debug!("before efi: {x:?}"); } efi_init(); diff --git a/kernel/src/arch/riscv64/interrupt/handle.rs b/kernel/src/arch/riscv64/interrupt/handle.rs index 97f94d29..faff690f 100644 --- a/kernel/src/arch/riscv64/interrupt/handle.rs +++ b/kernel/src/arch/riscv64/interrupt/handle.rs @@ -3,9 +3,10 @@ //! 架构相关的处理逻辑参考: https://code.dragonos.org.cn/xref/linux-6.6.21/arch/riscv/kernel/traps.c use core::hint::spin_loop; +use log::error; use system_error::SystemError; -use crate::{arch::syscall::syscall_handler, driver::irqchip::riscv_intc::riscv_intc_irq, kerror}; +use crate::{arch::syscall::syscall_handler, driver::irqchip::riscv_intc::riscv_intc_irq}; use super::TrapFrame; @@ -52,7 +53,7 @@ fn riscv64_do_exception(trap_frame: &mut TrapFrame) { let handler = EXCEPTION_HANDLERS[code]; handler(trap_frame).ok(); } else { - kerror!("riscv64_do_irq: exception code out of range"); + error!("riscv64_do_irq: exception code out of range"); loop { // kernel die spin_loop(); @@ -61,7 +62,7 @@ fn riscv64_do_exception(trap_frame: &mut TrapFrame) { } fn default_handler(_trap_frame: &mut TrapFrame) -> Result<(), SystemError> { - kerror!("riscv64_do_irq: handler not found"); + error!("riscv64_do_irq: handler not found"); loop { spin_loop(); } @@ -69,7 +70,7 @@ fn default_handler(_trap_frame: &mut TrapFrame) -> Result<(), SystemError> { /// 处理指令地址不对齐异常 #0 fn do_trap_insn_misaligned(_trap_frame: &mut TrapFrame) -> Result<(), SystemError> { - kerror!("riscv64_do_irq: do_trap_insn_misaligned"); + error!("riscv64_do_irq: do_trap_insn_misaligned"); loop { spin_loop(); } @@ -77,7 +78,7 @@ fn do_trap_insn_misaligned(_trap_frame: &mut TrapFrame) -> Result<(), SystemErro /// 处理指令访问异常 #1 fn do_trap_insn_access_fault(_trap_frame: &mut TrapFrame) -> Result<(), SystemError> { - kerror!("riscv64_do_irq: do_trap_insn_access_fault"); + error!("riscv64_do_irq: do_trap_insn_access_fault"); loop { spin_loop(); } @@ -85,7 +86,7 @@ fn do_trap_insn_access_fault(_trap_frame: &mut TrapFrame) -> Result<(), SystemEr /// 处理非法指令异常 #2 fn do_trap_insn_illegal(_trap_frame: &mut TrapFrame) -> Result<(), SystemError> { - kerror!("riscv64_do_irq: do_trap_insn_illegal"); + error!("riscv64_do_irq: do_trap_insn_illegal"); loop { spin_loop(); } @@ -93,7 +94,7 @@ fn do_trap_insn_illegal(_trap_frame: &mut TrapFrame) -> Result<(), SystemError> /// 处理断点异常 #3 fn do_trap_break(_trap_frame: &mut TrapFrame) -> Result<(), SystemError> { - kerror!("riscv64_do_irq: do_trap_break"); + error!("riscv64_do_irq: do_trap_break"); loop { spin_loop(); } @@ -101,7 +102,7 @@ fn do_trap_break(_trap_frame: &mut TrapFrame) -> Result<(), SystemError> { /// 处理加载地址不对齐异常 #4 fn do_trap_load_misaligned(_trap_frame: &mut TrapFrame) -> Result<(), SystemError> { - kerror!("riscv64_do_irq: do_trap_load_misaligned"); + error!("riscv64_do_irq: do_trap_load_misaligned"); loop { spin_loop(); } @@ -109,7 +110,7 @@ fn do_trap_load_misaligned(_trap_frame: &mut TrapFrame) -> Result<(), SystemErro /// 处理加载访问异常 #5 fn do_trap_load_access_fault(_trap_frame: &mut TrapFrame) -> Result<(), SystemError> { - kerror!("riscv64_do_irq: do_trap_load_access_fault"); + error!("riscv64_do_irq: do_trap_load_access_fault"); loop { spin_loop(); } @@ -117,7 +118,7 @@ fn do_trap_load_access_fault(_trap_frame: &mut TrapFrame) -> Result<(), SystemEr /// 处理存储地址不对齐异常 #6 fn do_trap_store_misaligned(_trap_frame: &mut TrapFrame) -> Result<(), SystemError> { - kerror!("riscv64_do_irq: do_trap_store_misaligned"); + error!("riscv64_do_irq: do_trap_store_misaligned"); loop { spin_loop(); } @@ -125,7 +126,7 @@ fn do_trap_store_misaligned(_trap_frame: &mut TrapFrame) -> Result<(), SystemErr /// 处理存储访问异常 #7 fn do_trap_store_access_fault(_trap_frame: &mut TrapFrame) -> Result<(), SystemError> { - kerror!("riscv64_do_irq: do_trap_store_access_fault"); + error!("riscv64_do_irq: do_trap_store_access_fault"); loop { spin_loop(); } @@ -151,11 +152,9 @@ fn do_trap_insn_page_fault(trap_frame: &mut TrapFrame) -> Result<(), SystemError let vaddr = trap_frame.badaddr; let cause = trap_frame.cause; let epc = trap_frame.epc; - kerror!( + error!( "riscv64_do_irq: do_insn_page_fault vaddr: {:#x}, cause: {:?} epc: {:#x}", - vaddr, - cause, - epc + vaddr, cause, epc ); loop { spin_loop(); @@ -167,10 +166,9 @@ fn do_trap_load_page_fault(trap_frame: &mut TrapFrame) -> Result<(), SystemError let vaddr = trap_frame.badaddr; let cause = trap_frame.cause; let epc = trap_frame.epc; - kerror!( + error!( "riscv64_do_irq: do_trap_load_page_fault: epc: {epc:#x}, vaddr={:#x}, cause={:?}", - vaddr, - cause + vaddr, cause ); loop { @@ -182,11 +180,9 @@ fn do_trap_load_page_fault(trap_frame: &mut TrapFrame) -> Result<(), SystemError /// 处理页存储错误异常 #15 fn do_trap_store_page_fault(trap_frame: &mut TrapFrame) -> Result<(), SystemError> { - kerror!( + error!( "riscv64_do_irq: do_trap_store_page_fault: epc: {:#x}, vaddr={:#x}, cause={:?}", - trap_frame.epc, - trap_frame.badaddr, - trap_frame.cause + trap_frame.epc, trap_frame.badaddr, trap_frame.cause ); loop { spin_loop(); diff --git a/kernel/src/arch/riscv64/ipc/signal.rs b/kernel/src/arch/riscv64/ipc/signal.rs index 3ebb66c1..f902e696 100644 --- a/kernel/src/arch/riscv64/ipc/signal.rs +++ b/kernel/src/arch/riscv64/ipc/signal.rs @@ -1,7 +1,8 @@ +use log::error; + use crate::{ arch::{sched::sched, CurrentIrqArch}, exception::InterruptArch, - kerror, process::ProcessManager, }; @@ -68,7 +69,7 @@ impl From for Signal { let ret: Signal = unsafe { core::mem::transmute(value) }; return ret; } else { - kerror!("Try to convert an invalid number to Signal"); + error!("Try to convert an invalid number to Signal"); return Signal::INVALID; } } @@ -83,7 +84,7 @@ impl Into for Signal { impl From for Signal { fn from(value: i32) -> Self { if value < 0 { - kerror!("Try to convert an invalid number to Signal"); + error!("Try to convert an invalid number to Signal"); return Signal::INVALID; } else { return Self::from(value as usize); @@ -127,7 +128,7 @@ impl Signal { pub fn handle_default(&self) { match self { Signal::INVALID => { - kerror!("attempting to handler an Invalid"); + error!("attempting to handler an Invalid"); } Signal::SIGHUP => sig_terminate(self.clone()), Signal::SIGINT => sig_terminate(self.clone()), @@ -312,7 +313,7 @@ fn sig_terminate_dump(sig: Signal) { fn sig_stop(sig: Signal) { let guard = unsafe { CurrentIrqArch::save_and_disable_irq() }; ProcessManager::mark_stop().unwrap_or_else(|e| { - kerror!( + error!( "sleep error :{:?},failed to sleep process :{:?}, with signal :{:?}", e, ProcessManager::current_pcb(), @@ -327,7 +328,7 @@ fn sig_stop(sig: Signal) { /// 信号默认处理函数——继续进程 fn sig_continue(sig: Signal) { ProcessManager::wakeup_stop(&ProcessManager::current_pcb()).unwrap_or_else(|_| { - kerror!( + error!( "Failed to wake up process pid = {:?} with signal :{:?}", ProcessManager::current_pcb().pid(), sig diff --git a/kernel/src/arch/riscv64/mm/init.rs b/kernel/src/arch/riscv64/mm/init.rs index 79a5fade..f545f109 100644 --- a/kernel/src/arch/riscv64/mm/init.rs +++ b/kernel/src/arch/riscv64/mm/init.rs @@ -1,5 +1,6 @@ use core::sync::atomic::{compiler_fence, AtomicBool, Ordering}; +use log::{debug, info}; use system_error::SystemError; use crate::{ @@ -11,7 +12,6 @@ use crate::{ MMArch, }, driver::firmware::efi::efi_manager, - kdebug, kinfo, libs::lib_ui::screen_manager::scm_disable_put_to_window, mm::{ allocator::{buddy::BuddyAllocator, bump::BumpAllocator, page_frame::FrameAllocator}, @@ -56,7 +56,7 @@ unsafe fn init_kernel_addr() { KERNEL_BEGIN_VA = VirtAddr::new(boot_text_start_pa as usize); KERNEL_END_VA = VirtAddr::new(_end as usize); - kdebug!( + debug!( "init_kernel_addr: \n\tKERNEL_BEGIN_PA: {KERNEL_BEGIN_PA:?} \tKERNEL_END_PA: {KERNEL_END_PA:?} \tKERNEL_BEGIN_VA: {KERNEL_BEGIN_VA:?} @@ -78,7 +78,7 @@ pub(super) unsafe fn riscv_mm_init() -> Result<(), SystemError> { // 使用bump分配器,把所有的内存页都映射到页表 { - // kdebug!("to create new page table"); + // debug!("to create new page table"); // 用bump allocator创建新的页表 let mut mapper: crate::mm::page::PageMapper> = crate::mm::page::PageMapper::::create( @@ -87,7 +87,7 @@ pub(super) unsafe fn riscv_mm_init() -> Result<(), SystemError> { ) .expect("Failed to create page mapper"); new_page_table = mapper.table().phys(); - // kdebug!("PageMapper created"); + // debug!("PageMapper created"); // 取消最开始时候,在head.S中指定的映射(暂时不刷新TLB) { @@ -99,12 +99,12 @@ pub(super) unsafe fn riscv_mm_init() -> Result<(), SystemError> { .expect("Failed to empty page table entry"); } } - kdebug!("Successfully emptied page table"); + debug!("Successfully emptied page table"); let total_num = mem_block_manager().total_initial_memory_regions(); for i in 0..total_num { let area = mem_block_manager().get_initial_memory_region(i).unwrap(); - // kdebug!("area: base={:?}, size={:#x}, end={:?}", area.base, area.size, area.base + area.size); + // debug!("area: base={:?}, size={:#x}, end={:?}", area.base, area.size, area.base + area.size); for i in 0..((area.size + MMArch::PAGE_SIZE - 1) / MMArch::PAGE_SIZE) { let paddr = area.base.add(i * MMArch::PAGE_SIZE); let vaddr = unsafe { MMArch::phys_2_virt(paddr) }.unwrap(); @@ -125,7 +125,7 @@ pub(super) unsafe fn riscv_mm_init() -> Result<(), SystemError> { unsafe { INITIAL_PGTABLE_VALUE = new_page_table; } - kdebug!( + debug!( "After mapping all physical memory, DragonOS used: {} KB", bump_allocator.usage().used().bytes() / 1024 ); @@ -134,7 +134,7 @@ pub(super) unsafe fn riscv_mm_init() -> Result<(), SystemError> { let buddy_allocator = unsafe { BuddyAllocator::::new(bump_allocator).unwrap() }; // 设置全局的页帧分配器 unsafe { set_inner_allocator(buddy_allocator) }; - kinfo!("Successfully initialized buddy allocator"); + info!("Successfully initialized buddy allocator"); // 关闭显示输出 scm_disable_put_to_window(); @@ -142,7 +142,7 @@ pub(super) unsafe fn riscv_mm_init() -> Result<(), SystemError> { { let mut binding = INNER_ALLOCATOR.lock(); let mut allocator_guard = binding.as_mut().unwrap(); - kdebug!("To enable new page table."); + debug!("To enable new page table."); compiler_fence(Ordering::SeqCst); let mapper = crate::mm::page::PageMapper::::new( PageTableKind::Kernel, @@ -152,10 +152,10 @@ pub(super) unsafe fn riscv_mm_init() -> Result<(), SystemError> { compiler_fence(Ordering::SeqCst); mapper.make_current(); compiler_fence(Ordering::SeqCst); - // kdebug!("New page table enabled"); + // debug!("New page table enabled"); } - kdebug!("Successfully enabled new page table"); - kinfo!("riscv mm init done"); + debug!("Successfully enabled new page table"); + info!("riscv mm init done"); return Ok(()); } diff --git a/kernel/src/arch/riscv64/pci/pci_host_ecam.rs b/kernel/src/arch/riscv64/pci/pci_host_ecam.rs index 59d658c2..4e1b4ed0 100644 --- a/kernel/src/arch/riscv64/pci/pci_host_ecam.rs +++ b/kernel/src/arch/riscv64/pci/pci_host_ecam.rs @@ -1,4 +1,5 @@ use fdt::{node::FdtNode, Fdt}; +use log::debug; use system_error::SystemError; use crate::{ @@ -6,7 +7,6 @@ use crate::{ open_firmware::fdt::open_firmware_fdt_driver, pci::ecam::{pci_ecam_root_info_manager, EcamRootInfo}, }, - kdebug, mm::PhysAddr, }; @@ -39,7 +39,7 @@ pub(super) fn pci_host_ecam_driver_init(fdt: &Fdt<'_>) -> Result<(), SystemError _ => panic!("Unexpected linux,pci-domain length"), }; - kdebug!( + debug!( "pci_host_ecam_driver_init(): {} paddr: {:#x} size: {:#x} bus-range: {}-{} segement_group_number: {}", node.name, paddr, @@ -61,10 +61,9 @@ pub(super) fn pci_host_ecam_driver_init(fdt: &Fdt<'_>) -> Result<(), SystemError for node in open_firmware_fdt_driver().find_node_by_compatible(&fdt, "pci-host-ecam-generic") { if let Err(err) = do_check(node) { - kdebug!( + debug!( "pci_host_ecam_driver_init(): check {} error: {:?}", - node.name, - err + node.name, err ); } } diff --git a/kernel/src/arch/riscv64/process/idle.rs b/kernel/src/arch/riscv64/process/idle.rs index 196a709e..ed21f51e 100644 --- a/kernel/src/arch/riscv64/process/idle.rs +++ b/kernel/src/arch/riscv64/process/idle.rs @@ -1,6 +1,8 @@ use core::hint::spin_loop; -use crate::{arch::CurrentIrqArch, exception::InterruptArch, kBUG, process::ProcessManager}; +use log::error; + +use crate::{arch::CurrentIrqArch, exception::InterruptArch, process::ProcessManager}; impl ProcessManager { /// 每个核的idle进程 @@ -9,11 +11,11 @@ impl ProcessManager { if CurrentIrqArch::is_irq_enabled() { riscv::asm::wfi(); } else { - kBUG!("Idle process should not be scheduled with IRQs disabled."); + error!("Idle process should not be scheduled with IRQs disabled."); spin_loop(); } - // kdebug!("idle loop"); + // debug!("idle loop"); } } } diff --git a/kernel/src/arch/riscv64/process/mod.rs b/kernel/src/arch/riscv64/process/mod.rs index 32e69929..89ec982d 100644 --- a/kernel/src/arch/riscv64/process/mod.rs +++ b/kernel/src/arch/riscv64/process/mod.rs @@ -6,6 +6,7 @@ use core::{ sync::atomic::{compiler_fence, Ordering}, }; use kdepends::memoffset::offset_of; +use log::error; use riscv::register::sstatus::Sstatus; use system_error::SystemError; @@ -15,7 +16,6 @@ use crate::{ CurrentIrqArch, }, exception::InterruptArch, - kerror, libs::spinlock::SpinLockGuard, mm::VirtAddr, process::{ @@ -166,7 +166,7 @@ impl ProcessManager { /// 参考: https://code.dragonos.org.cn/xref/linux-6.6.21/arch/riscv/include/asm/switch_to.h#76 pub unsafe fn switch_process(prev: Arc, next: Arc) { assert!(!CurrentIrqArch::is_irq_enabled()); - // kdebug!( + // debug!( // "riscv switch process: prev: {:?}, next: {:?}", // prev.pid(), // next.pid() @@ -182,7 +182,7 @@ impl ProcessManager { drop(next_addr_space); compiler_fence(Ordering::SeqCst); - // kdebug!("current sum={}, prev sum={}, next_sum={}", riscv::register::sstatus::read().sum(), prev.arch_info_irqsave().sstatus.sum(), next.arch_info_irqsave().sstatus.sum()); + // debug!("current sum={}, prev sum={}, next_sum={}", riscv::register::sstatus::read().sum(), prev.arch_info_irqsave().sstatus.sum(), next.arch_info_irqsave().sstatus.sum()); // 获取arch info的锁,并强制泄露其守卫(切换上下文后,在switch_finish_hook中会释放锁) let next_arch = SpinLockGuard::leak(next.arch_info_irqsave()) as *mut ArchPCBInfo; @@ -193,7 +193,7 @@ impl ProcessManager { ProcessManager::current_pcb().preempt_enable(); PROCESS_SWITCH_RESULT.as_mut().unwrap().get_mut().prev_pcb = Some(prev); PROCESS_SWITCH_RESULT.as_mut().unwrap().get_mut().next_pcb = Some(next); - // kdebug!("riscv switch process: before to inner"); + // debug!("riscv switch process: before to inner"); compiler_fence(Ordering::SeqCst); // 正式切换上下文 switch_to_inner(prev_arch, next_arch); @@ -326,7 +326,7 @@ impl ProcessControlBlock { // 从内核栈的最低地址处取出pcb的地址 let p = stack_base.data() as *const *const ProcessControlBlock; if core::intrinsics::unlikely((unsafe { *p }).is_null()) { - kerror!("p={:p}", p); + error!("p={:p}", p); panic!("current_pcb is null"); } unsafe { diff --git a/kernel/src/arch/riscv64/process/syscall.rs b/kernel/src/arch/riscv64/process/syscall.rs index 0b446f41..22490653 100644 --- a/kernel/src/arch/riscv64/process/syscall.rs +++ b/kernel/src/arch/riscv64/process/syscall.rs @@ -23,7 +23,7 @@ impl Syscall { // 关中断,防止在设置地址空间的时候,发生中断,然后进调度器,出现错误。 let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() }; let pcb = ProcessManager::current_pcb(); - // crate::kdebug!( + // crate::debug!( // "pid: {:?} do_execve: path: {:?}, argv: {:?}, envp: {:?}\n", // pcb.pid(), // path, @@ -52,20 +52,20 @@ impl Syscall { AddressSpace::is_current(&address_space), "Failed to set address space" ); - // kdebug!("Switch to new address space"); + // debug!("Switch to new address space"); // 切换到新的用户地址空间 unsafe { address_space.read().user_mapper.utable.make_current() }; drop(old_address_space); drop(irq_guard); - // kdebug!("to load binary file"); + // debug!("to load binary file"); let mut param = ExecParam::new(path.as_str(), address_space.clone(), ExecParamFlags::EXEC)?; // 加载可执行文件 let load_result = load_binary_file(&mut param)?; - // kdebug!("load binary file done"); - // kdebug!("argv: {:?}, envp: {:?}", argv, envp); + // debug!("load binary file done"); + // debug!("argv: {:?}, envp: {:?}", argv, envp); param.init_info_mut().args = argv; param.init_info_mut().envs = envp; @@ -91,7 +91,7 @@ impl Syscall { }; address_space.write().user_stack = Some(ustack_message); - // kdebug!("write proc_init_info to user stack done"); + // debug!("write proc_init_info to user stack done"); regs.a0 = param.init_info().args.len(); regs.a1 = argv_ptr.data(); diff --git a/kernel/src/arch/riscv64/smp/mod.rs b/kernel/src/arch/riscv64/smp/mod.rs index a283b450..32969d8c 100644 --- a/kernel/src/arch/riscv64/smp/mod.rs +++ b/kernel/src/arch/riscv64/smp/mod.rs @@ -1,11 +1,9 @@ +use log::warn; use system_error::SystemError; -use crate::{ - kwarn, - smp::{ - cpu::{CpuHpCpuState, ProcessorId}, - SMPArch, - }, +use crate::smp::{ + cpu::{CpuHpCpuState, ProcessorId}, + SMPArch, }; pub struct RiscV64SMPArch; @@ -13,12 +11,12 @@ pub struct RiscV64SMPArch; impl SMPArch for RiscV64SMPArch { #[inline(never)] fn prepare_cpus() -> Result<(), SystemError> { - kwarn!("RiscV64SMPArch::prepare_cpus() is not implemented"); + warn!("RiscV64SMPArch::prepare_cpus() is not implemented"); Ok(()) } fn start_cpu(_cpu_id: ProcessorId, _hp_state: &CpuHpCpuState) -> Result<(), SystemError> { - kwarn!("RiscV64SMPArch::start_cpu() is not implemented"); + warn!("RiscV64SMPArch::start_cpu() is not implemented"); Ok(()) } } diff --git a/kernel/src/arch/riscv64/syscall/mod.rs b/kernel/src/arch/riscv64/syscall/mod.rs index fe1a1908..5609084a 100644 --- a/kernel/src/arch/riscv64/syscall/mod.rs +++ b/kernel/src/arch/riscv64/syscall/mod.rs @@ -18,7 +18,7 @@ macro_rules! syscall_return { if $show { let pid = ProcessManager::current_pcb().pid(); - crate::kdebug!("syscall return:pid={:?},ret= {:?}\n", pid, ret as isize); + log::debug!("syscall return:pid={:?},ret= {:?}\n", pid, ret as isize); } unsafe { @@ -29,7 +29,7 @@ macro_rules! syscall_return { } pub(super) fn syscall_handler(syscall_num: usize, frame: &mut TrapFrame) -> () { - // kdebug!("syscall_handler: syscall_num: {}", syscall_num); + // debug!("syscall_handler: syscall_num: {}", syscall_num); unsafe { CurrentIrqArch::interrupt_enable(); } diff --git a/kernel/src/arch/riscv64/time.rs b/kernel/src/arch/riscv64/time.rs index d6be314a..0b2f1128 100644 --- a/kernel/src/arch/riscv64/time.rs +++ b/kernel/src/arch/riscv64/time.rs @@ -1,6 +1,7 @@ +use log::{debug, info}; + use crate::{ driver::open_firmware::fdt::open_firmware_fdt_driver, - kdebug, kinfo, time::{clocksource::HZ, TimeArch}, }; pub struct RiscV64TimeArch; @@ -14,12 +15,12 @@ static mut TIME_FREQ: usize = 0; /// /// todo: 支持从acpi中获取 fn init_time_freq() { - kdebug!("init_time_freq: init"); + debug!("init_time_freq: init"); let fdt = open_firmware_fdt_driver().fdt_ref(); if fdt.is_err() { panic!("init_time_freq: failed to get fdt"); } - kdebug!("init_time_freq: get fdt"); + debug!("init_time_freq: get fdt"); let fdt = fdt.unwrap(); let cpu_node = fdt.find_node("/cpus"); if cpu_node.is_none() { @@ -36,7 +37,7 @@ fn init_time_freq() { } let time_freq: usize = time_freq.unwrap(); - kinfo!("init_time_freq: timebase-frequency: {}", time_freq); + info!("init_time_freq: timebase-frequency: {}", time_freq); unsafe { TIME_FREQ = time_freq; } diff --git a/kernel/src/arch/x86_64/acpi.rs b/kernel/src/arch/x86_64/acpi.rs index d29b3bcd..0b834ee6 100644 --- a/kernel/src/arch/x86_64/acpi.rs +++ b/kernel/src/arch/x86_64/acpi.rs @@ -1,5 +1,6 @@ use super::smp::SMP_BOOT_DATA; -use crate::{driver::acpi::acpi_manager, kinfo, mm::percpu::PerCpu, smp::cpu::ProcessorId}; +use crate::{driver::acpi::acpi_manager, mm::percpu::PerCpu, smp::cpu::ProcessorId}; +use log::info; use system_error::SystemError; pub(super) fn early_acpi_boot_init() -> Result<(), SystemError> { @@ -24,7 +25,7 @@ pub(super) fn early_acpi_boot_init() -> Result<(), SystemError> { SMP_BOOT_DATA.set_cpu_count(cnt.data()); SMP_BOOT_DATA.mark_initialized(); } - kinfo!( + info!( "early_acpi_boot_init: cpu_count: {}\n", SMP_BOOT_DATA.cpu_count() ); diff --git a/kernel/src/arch/x86_64/driver/apic/apic_timer.rs b/kernel/src/arch/x86_64/driver/apic/apic_timer.rs index 10adfac4..1c8695b8 100644 --- a/kernel/src/arch/x86_64/driver/apic/apic_timer.rs +++ b/kernel/src/arch/x86_64/driver/apic/apic_timer.rs @@ -11,7 +11,6 @@ use crate::exception::irqdesc::{ use crate::exception::manage::irq_manager; use crate::exception::IrqNumber; -use crate::kdebug; use crate::mm::percpu::PerCpu; use crate::process::ProcessManager; use crate::smp::core::smp_get_processor_id; @@ -20,6 +19,7 @@ use crate::time::clocksource::HZ; use alloc::string::ToString; use alloc::sync::Arc; pub use drop; +use log::debug; use system_error::SystemError; use x86::cpuid::cpuid; use x86::msr::{wrmsr, IA32_X2APIC_DIV_CONF, IA32_X2APIC_INIT_COUNT}; @@ -105,7 +105,7 @@ pub(super) fn local_apic_timer_irq_desc_init() { /// 初始化BSP的APIC定时器 /// fn init_bsp_apic_timer() { - kdebug!("init_bsp_apic_timer"); + debug!("init_bsp_apic_timer"); assert!(smp_get_processor_id().data() == 0); let mut local_apic_timer = local_apic_timer_instance_mut(ProcessorId::new(0)); local_apic_timer.init( @@ -113,11 +113,11 @@ fn init_bsp_apic_timer() { LocalApicTimer::periodic_default_initial_count(), LocalApicTimer::DIVISOR as u32, ); - kdebug!("init_bsp_apic_timer done"); + debug!("init_bsp_apic_timer done"); } fn init_ap_apic_timer() { - kdebug!("init_ap_apic_timer"); + debug!("init_ap_apic_timer"); let cpu_id = smp_get_processor_id(); assert!(cpu_id.data() != 0); @@ -127,14 +127,14 @@ fn init_ap_apic_timer() { LocalApicTimer::periodic_default_initial_count(), LocalApicTimer::DIVISOR as u32, ); - kdebug!("init_ap_apic_timer done"); + debug!("init_ap_apic_timer done"); } pub(super) struct LocalApicTimerIntrController; impl LocalApicTimerIntrController { pub(super) fn install(&self) { - kdebug!("LocalApicTimerIntrController::install"); + debug!("LocalApicTimerIntrController::install"); if smp_get_processor_id().data() == 0 { init_bsp_apic_timer(); } else { @@ -150,7 +150,7 @@ impl LocalApicTimerIntrController { } pub(super) fn enable(&self) { - kdebug!("LocalApicTimerIntrController::enable"); + debug!("LocalApicTimerIntrController::enable"); let cpu_id = smp_get_processor_id(); let mut local_apic_timer = local_apic_timer_instance_mut(cpu_id); local_apic_timer.start_current(); @@ -221,10 +221,9 @@ impl LocalApicTimer { } fn install_periodic_mode(&mut self, initial_count: u64, divisor: u32) { - kdebug!( + debug!( "install_periodic_mode: initial_count = {}, divisor = {}", - initial_count, - divisor + initial_count, divisor ); self.mode = LocalApicTimerMode::Periodic; self.set_divisor(divisor); diff --git a/kernel/src/arch/x86_64/driver/apic/ioapic.rs b/kernel/src/arch/x86_64/driver/apic/ioapic.rs index fcfbbb94..b2b46b46 100644 --- a/kernel/src/arch/x86_64/driver/apic/ioapic.rs +++ b/kernel/src/arch/x86_64/driver/apic/ioapic.rs @@ -4,6 +4,7 @@ use acpi::madt::Madt; use alloc::sync::Arc; use bit_field::BitField; use bitflags::bitflags; +use log::{debug, info}; use system_error::SystemError; use crate::{ @@ -16,7 +17,6 @@ use crate::{ manage::irq_manager, IrqNumber, }, - kdebug, kinfo, libs::{ cpumask::CpuMask, once::Once, @@ -68,7 +68,7 @@ impl IoApic { let mut result: Option = None; INIT_STATE.call_once(|| { - kinfo!("Initializing ioapic..."); + info!("Initializing ioapic..."); // get ioapic base from acpi @@ -104,7 +104,7 @@ impl IoApic { mmio_guard.map_phys(phys_base, 0x1000).is_ok(), "IoApic::new(): failed to map phys" ); - kdebug!("Ioapic map ok"); + debug!("Ioapic map ok"); let reg = mmio_guard.vaddr(); result = Some(IoApic { @@ -114,13 +114,13 @@ impl IoApic { phys_base, mmio_guard, }); - kdebug!("IOAPIC: to mask all RTE"); + debug!("IOAPIC: to mask all RTE"); // 屏蔽所有的RTE let res_mut = result.as_mut().unwrap(); for i in 0..res_mut.supported_interrupts() { res_mut.write_rte(i, 0x20 + i, RedirectionEntry::DISABLED, 0); } - kdebug!("Ioapic init done"); + debug!("Ioapic init done"); }); assert!( @@ -393,7 +393,7 @@ impl InnerIoApicChipData { #[inline(never)] pub fn ioapic_init(ignore: &'static [IrqNumber]) { - kinfo!("Initializing ioapic..."); + info!("Initializing ioapic..."); let ioapic = unsafe { IoApic::new() }; unsafe { __IOAPIC = Some(SpinLock::new(ioapic)); @@ -424,7 +424,7 @@ pub fn ioapic_init(ignore: &'static [IrqNumber]) { register_handler(&desc, level); } - kinfo!("IO Apic initialized."); + info!("IO Apic initialized."); } fn register_handler(desc: &Arc, level_triggered: bool) { diff --git a/kernel/src/arch/x86_64/driver/apic/lapic_vector.rs b/kernel/src/arch/x86_64/driver/apic/lapic_vector.rs index 74a1ee79..a267346a 100644 --- a/kernel/src/arch/x86_64/driver/apic/lapic_vector.rs +++ b/kernel/src/arch/x86_64/driver/apic/lapic_vector.rs @@ -2,6 +2,7 @@ use core::intrinsics::unlikely; use alloc::{string::ToString, sync::Arc}; use intertrait::CastFrom; +use log::warn; use system_error::SystemError; use crate::{ @@ -25,7 +26,6 @@ use crate::{ msi::MsiMsg, HardwareIrqNumber, IrqNumber, }, - kwarn, libs::spinlock::{SpinLock, SpinLockGuard}, smp::{core::smp_get_processor_id, cpu::ProcessorId}, }; @@ -206,7 +206,7 @@ pub(super) fn irq_msi_compose_msg(cfg: &HardwareIrqConfig, msg: &mut MsiMsg, dma // 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/arch/x86/kernel/apic/apic.c?fi=__irq_msi_compose_msg#2580 address_lo.set_virt_destid_8_14(cfg.apic_id.data() >> 8); } else if unlikely(cfg.apic_id.data() > 0xff) { - kwarn!( + warn!( "irq_msi_compose_msg: Invalid APIC ID: {}", cfg.apic_id.data() ); @@ -252,7 +252,7 @@ pub fn arch_early_irq_init() -> Result<(), SystemError> { // todo: add vector matrix // 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/arch/x86/kernel/apic/vector.c#803 - kwarn!("arch_early_irq_init: todo: add vector matrix"); + warn!("arch_early_irq_init: todo: add vector matrix"); local_apic_timer_irq_desc_init(); arch_ipi_handler_init(); diff --git a/kernel/src/arch/x86_64/driver/apic/mod.rs b/kernel/src/arch/x86_64/driver/apic/mod.rs index ae78415b..af89dedf 100644 --- a/kernel/src/arch/x86_64/driver/apic/mod.rs +++ b/kernel/src/arch/x86_64/driver/apic/mod.rs @@ -1,6 +1,7 @@ use core::sync::atomic::Ordering; use atomic_enum::atomic_enum; +use log::{debug, info}; use system_error::SystemError; use x86::{apic::Icr, msr::IA32_APIC_BASE}; @@ -10,7 +11,6 @@ use crate::{ io::PortIOArch, CurrentPortIOArch, }, - kdebug, kinfo, mm::PhysAddr, smp::core::smp_get_processor_id, }; @@ -468,7 +468,7 @@ impl CurrentApic { CurrentPortIOArch::out8(0x20, 0x20); CurrentPortIOArch::out8(0xa0, 0x20); - kdebug!("8259A Masked."); + debug!("8259A Masked."); // enable IMCR CurrentPortIOArch::out8(0x22, 0x70); @@ -488,14 +488,14 @@ impl LocalAPIC for CurrentApic { self.mask8259a(); } } - kinfo!("Initializing apic for cpu {:?}", cpu_id); + info!("Initializing apic for cpu {:?}", cpu_id); if X2Apic::support() && X2Apic.init_current_cpu() { if cpu_id.data() == 0 { LOCAL_APIC_ENABLE_TYPE.store(LocalApicEnableType::X2Apic, Ordering::SeqCst); } - kinfo!("x2APIC initialized for cpu {:?}", cpu_id); + info!("x2APIC initialized for cpu {:?}", cpu_id); } else { - kinfo!("x2APIC not supported or failed to initialize, fallback to xAPIC."); + info!("x2APIC not supported or failed to initialize, fallback to xAPIC."); if cpu_id.data() == 0 { LOCAL_APIC_ENABLE_TYPE.store(LocalApicEnableType::XApic, Ordering::SeqCst); } @@ -514,10 +514,10 @@ impl LocalAPIC for CurrentApic { xapic.init_current_cpu(); } - kinfo!("xAPIC initialized for cpu {:?}", cpu_id); + info!("xAPIC initialized for cpu {:?}", cpu_id); } - kinfo!("Apic initialized."); + info!("Apic initialized."); return true; } diff --git a/kernel/src/arch/x86_64/driver/apic/x2apic.rs b/kernel/src/arch/x86_64/driver/apic/x2apic.rs index 7718cb45..e34715ea 100644 --- a/kernel/src/arch/x86_64/driver/apic/x2apic.rs +++ b/kernel/src/arch/x86_64/driver/apic/x2apic.rs @@ -1,12 +1,11 @@ use core::sync::atomic::{fence, Ordering}; +use log::info; use x86::msr::{ rdmsr, wrmsr, IA32_APIC_BASE, IA32_X2APIC_APICID, IA32_X2APIC_EOI, IA32_X2APIC_SIVR, IA32_X2APIC_VERSION, }; -use crate::kinfo; - use super::{hw_irq::ApicId, LVTRegister, LocalAPIC, LVT}; #[derive(Debug)] @@ -45,19 +44,19 @@ impl LocalAPIC for X2Apic { (rdmsr(IA32_X2APIC_SIVR) & 0x100) == 0x100, "x2APIC software enable failed." ); - kinfo!("x2APIC software enabled."); + info!("x2APIC software enabled."); if self.support_eoi_broadcast_suppression() { assert!( (rdmsr(IA32_X2APIC_SIVR) & 0x1000) == 0x1000, "x2APIC EOI broadcast suppression enable failed." ); - kinfo!("x2APIC EOI broadcast suppression enabled."); + info!("x2APIC EOI broadcast suppression enabled."); } } - // kdebug!("x2apic: to mask all lvt"); + // debug!("x2apic: to mask all lvt"); self.mask_all_lvt(); - // kdebug!("x2apic: all lvt masked"); + // debug!("x2apic: all lvt masked"); } true } diff --git a/kernel/src/arch/x86_64/driver/apic/xapic.rs b/kernel/src/arch/x86_64/driver/apic/xapic.rs index 49211e0c..f764d1df 100644 --- a/kernel/src/arch/x86_64/driver/apic/xapic.rs +++ b/kernel/src/arch/x86_64/driver/apic/xapic.rs @@ -4,8 +4,9 @@ use core::{ ptr::{read_volatile, write_volatile}, }; +use log::{debug, error, info}; + use crate::{ - kdebug, kerror, kinfo, mm::{ mmio_buddy::{mmio_pool, MMIOSpaceGuard}, percpu::PerCpu, @@ -157,7 +158,7 @@ impl XApic { g.map_phys(paddr, 4096).expect("Fail to map MMIO for XAPIC"); let addr = g.vaddr() + offset; - kdebug!( + debug!( "XAPIC: {:#x} -> {:#x}, offset={offset}", xapic_base.data(), addr.data() @@ -219,7 +220,7 @@ impl LocalAPIC for XApic { x86::msr::wrmsr(x86::msr::APIC_BASE, (self.xapic_base.data() | 0x800) as u64); let val = x86::msr::rdmsr(x86::msr::APIC_BASE); if val & 0x800 != 0x800 { - kerror!("xAPIC enable failed: APIC_BASE & 0x800 != 0x800"); + error!("xAPIC enable failed: APIC_BASE & 0x800 != 0x800"); return false; } // 设置 Spurious Interrupt Vector Register @@ -229,15 +230,15 @@ impl LocalAPIC for XApic { let val = self.read(XApicOffset::LOCAL_APIC_OFFSET_Local_APIC_SVR); if val & ENABLE == 0 { - kerror!("xAPIC software enable failed."); + error!("xAPIC software enable failed."); return false; } else { - kinfo!("xAPIC software enabled."); + info!("xAPIC software enabled."); } if val & 0x1000 != 0 { - kinfo!("xAPIC EOI broadcast suppression enabled."); + info!("xAPIC EOI broadcast suppression enabled."); } self.mask_all_lvt(); diff --git a/kernel/src/arch/x86_64/driver/hpet.rs b/kernel/src/arch/x86_64/driver/hpet.rs index 36202dbf..98863bdc 100644 --- a/kernel/src/arch/x86_64/driver/hpet.rs +++ b/kernel/src/arch/x86_64/driver/hpet.rs @@ -7,6 +7,7 @@ use core::{ use acpi::HpetInfo; use alloc::{string::ToString, sync::Arc}; +use log::{debug, error, info}; use system_error::SystemError; use crate::{ @@ -21,7 +22,6 @@ use crate::{ manage::irq_manager, InterruptArch, IrqNumber, }, - kdebug, kerror, kinfo, libs::{ rwlock::{RwLock, RwLockReadGuard, RwLockWriteGuard}, volatile::volwrite, @@ -80,8 +80,8 @@ impl Hpet { .unwrap() }; let tm_num = hpet.timers_num(); - kdebug!("HPET0_INTERVAL_USEC: {}", Self::HPET0_INTERVAL_USEC); - kinfo!("HPET has {} timers", tm_num); + debug!("HPET0_INTERVAL_USEC: {}", Self::HPET0_INTERVAL_USEC); + info!("HPET has {} timers", tm_num); hpet_info.hpet_number = tm_num as u8; drop(mmio); @@ -124,10 +124,10 @@ impl Hpet { // !!!这里是临时糊代码的,需要在apic重构的时候修改!!! let (inner_guard, regs) = unsafe { self.hpet_regs_mut() }; let freq = regs.frequency(); - kdebug!("HPET frequency: {} Hz", freq); + debug!("HPET frequency: {} Hz", freq); let ticks = Self::HPET0_INTERVAL_USEC * freq / 1000000; if ticks == 0 || ticks > freq * 8 { - kerror!("HPET enable: ticks '{ticks}' is invalid"); + error!("HPET enable: ticks '{ticks}' is invalid"); return Err(SystemError::EINVAL); } if unlikely(regs.timers_num() == 0) { @@ -166,7 +166,7 @@ impl Hpet { drop(inner_guard); - kinfo!("HPET enabled"); + info!("HPET enabled"); drop(irq_guard); return Ok(()); @@ -239,7 +239,7 @@ impl Hpet { pub fn period(&self) -> u64 { let (inner_guard, regs) = unsafe { self.hpet_regs() }; let period = regs.counter_clock_period(); - kdebug!("HPET period: {}", period); + debug!("HPET period: {}", period); drop(inner_guard); return period; diff --git a/kernel/src/arch/x86_64/driver/rtc.rs b/kernel/src/arch/x86_64/driver/rtc.rs index 0612038e..bb6486a1 100644 --- a/kernel/src/arch/x86_64/driver/rtc.rs +++ b/kernel/src/arch/x86_64/driver/rtc.rs @@ -4,6 +4,7 @@ use alloc::{ string::{String, ToString}, sync::{Arc, Weak}, }; +use log::error; use system_error::SystemError; use unified_init::macros::unified_init; @@ -25,7 +26,6 @@ use crate::{ exception::InterruptArch, filesystem::kernfs::KernFSInode, init::initcall::INITCALL_DEVICE, - kerror, libs::{ mutex::Mutex, rwlock::{RwLockReadGuard, RwLockWriteGuard}, @@ -286,7 +286,7 @@ impl RtcClassOps for CmosRtcClassOps { } fn set_time(&self, _dev: &Arc, _time: &RtcTime) -> Result<(), SystemError> { - kerror!("set_time is not implemented for CmosRtcClassOps"); + error!("set_time is not implemented for CmosRtcClassOps"); Err(SystemError::ENOSYS) } } diff --git a/kernel/src/arch/x86_64/driver/tsc.rs b/kernel/src/arch/x86_64/driver/tsc.rs index f1aab65d..ef97ec6a 100644 --- a/kernel/src/arch/x86_64/driver/tsc.rs +++ b/kernel/src/arch/x86_64/driver/tsc.rs @@ -2,13 +2,13 @@ use crate::{ arch::{io::PortIOArch, CurrentIrqArch, CurrentPortIOArch, CurrentTimeArch}, driver::acpi::pmtmr::{acpi_pm_read_early, ACPI_PM_OVERRUN, PMTMR_TICKS_PER_SEC}, exception::InterruptArch, - kdebug, kerror, kinfo, kwarn, time::{TimeArch, PIT_TICK_RATE}, }; use core::{ cmp::{max, min}, intrinsics::unlikely, }; +use log::{debug, error, info, warn}; use system_error::SystemError; use super::hpet::{hpet_instance, is_hpet_enabled}; @@ -31,13 +31,13 @@ impl TSCManager { let cpuid = x86::cpuid::CpuId::new(); let feat = cpuid.get_feature_info().ok_or(SystemError::ENODEV)?; if !feat.has_tsc() { - kerror!("TSC is not available"); + error!("TSC is not available"); return Err(SystemError::ENODEV); } if unsafe { TSC_KHZ == 0 } { if let Err(e) = Self::determine_cpu_tsc_frequency(false) { - kerror!("Failed to determine CPU TSC frequency: {:?}", e); + error!("Failed to determine CPU TSC frequency: {:?}", e); // todo: mark TSC as unstable clock source return Err(e); } @@ -57,7 +57,7 @@ impl TSCManager { /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/arch/x86/kernel/tsc.c#1438 fn determine_cpu_tsc_frequency(early: bool) -> Result<(), SystemError> { if unlikely(Self::cpu_khz() != 0 || Self::tsc_khz() != 0) { - kwarn!("TSC and CPU frequency already determined"); + warn!("TSC and CPU frequency already determined"); } if early { @@ -79,16 +79,16 @@ impl TSCManager { } if Self::cpu_khz() == 0 { - kerror!("Failed to determine CPU frequency"); + error!("Failed to determine CPU frequency"); return Err(SystemError::ENODEV); } - kinfo!( + info!( "Detected {}.{} MHz processor", Self::cpu_khz() / 1000, Self::cpu_khz() % 1000 ); - kinfo!( + info!( "Detected {}.{} MHz TSC", Self::tsc_khz() / 1000, Self::tsc_khz() % 1000 @@ -102,7 +102,7 @@ impl TSCManager { /// 使用pit、hpet、ptimer来测量CPU总线的频率 fn calibrate_cpu_by_pit_hpet_ptimer() -> Result { let hpet = is_hpet_enabled(); - kdebug!( + debug!( "Calibrating TSC with {}", if hpet { "HPET" } else { "PMTIMER" } ); @@ -143,7 +143,7 @@ impl TSCManager { // HPET或者PTIMER可能是不可用的 if ref1 == ref2 { - kdebug!("HPET/PMTIMER not available"); + debug!("HPET/PMTIMER not available"); continue; } @@ -169,7 +169,7 @@ impl TSCManager { // 如果误差在10%以内,那么认为测量成功 // 返回参考值,因为它是更精确的 if (90..=110).contains(&delta) { - kinfo!( + info!( "PIT calibration matches {}. {} loops", if hpet { "HPET" } else { "PMTIMER" }, i + 1 @@ -185,20 +185,20 @@ impl TSCManager { } if tsc_pit_min == u64::MAX { - kwarn!("Unable to calibrate against PIT"); + warn!("Unable to calibrate against PIT"); // 如果没有参考值,那么禁用tsc if (!hpet) && (global_ref1 == 0) && (global_ref2 == 0) { - kwarn!("No reference (HPET/PMTIMER) available"); + warn!("No reference (HPET/PMTIMER) available"); return Err(SystemError::ENODEV); } if tsc_ref_min == u64::MAX { - kwarn!("Unable to calibrate against HPET/PMTIMER"); + warn!("Unable to calibrate against HPET/PMTIMER"); return Err(SystemError::ENODEV); } - kinfo!( + info!( "Using {} reference calibration", if hpet { "HPET" } else { "PMTIMER" } ); @@ -207,27 +207,27 @@ impl TSCManager { // We don't have an alternative source, use the PIT calibration value if (!hpet) && (global_ref1 == 0) && (global_ref2 == 0) { - kinfo!("Using PIT calibration value"); + info!("Using PIT calibration value"); return Ok(tsc_pit_min); } // The alternative source failed, use the PIT calibration value if tsc_ref_min == u64::MAX { - kwarn!("Unable to calibrate against HPET/PMTIMER, using PIT calibration value"); + warn!("Unable to calibrate against HPET/PMTIMER, using PIT calibration value"); return Ok(tsc_pit_min); } // The calibration values differ too much. In doubt, we use // the PIT value as we know that there are PMTIMERs around // running at double speed. At least we let the user know: - kwarn!( + warn!( "PIT calibration deviates from {}: tsc_pit_min={}, tsc_ref_min={}", if hpet { "HPET" } else { "PMTIMER" }, tsc_pit_min, tsc_ref_min ); - kinfo!("Using PIT calibration value"); + info!("Using PIT calibration value"); return Ok(tsc_pit_min); } @@ -326,7 +326,7 @@ impl TSCManager { } } - kwarn!("TSCManager: Failed to read reference value, tsc delta too high"); + warn!("TSCManager: Failed to read reference value, tsc delta too high"); return (u64::MAX, ref_ret); } diff --git a/kernel/src/arch/x86_64/init/mod.rs b/kernel/src/arch/x86_64/init/mod.rs index 6f392d3a..534b92cf 100644 --- a/kernel/src/arch/x86_64/init/mod.rs +++ b/kernel/src/arch/x86_64/init/mod.rs @@ -1,5 +1,6 @@ use core::sync::atomic::{compiler_fence, Ordering}; +use log::debug; use system_error::SystemError; use x86::dtables::DescriptorTablePointer; @@ -7,7 +8,6 @@ use crate::{ arch::{interrupt::trap::arch_trap_init, process::table::TSSManager}, driver::clocksource::acpi_pm::init_acpi_pm_clocksource, init::init::start_kernel, - kdebug, mm::{MemoryManagementArch, PhysAddr}, }; @@ -68,14 +68,14 @@ unsafe extern "C" fn kernel_main( #[inline(never)] pub fn early_setup_arch() -> Result<(), SystemError> { let stack_start = unsafe { *(head_stack_start as *const u64) } as usize; - kdebug!("head_stack_start={:#x}\n", stack_start); + debug!("head_stack_start={:#x}\n", stack_start); unsafe { let gdt_vaddr = MMArch::phys_2_virt(PhysAddr::new(&GDT_Table as *const usize as usize)).unwrap(); let idt_vaddr = MMArch::phys_2_virt(PhysAddr::new(&IDT_Table as *const usize as usize)).unwrap(); - kdebug!("GDT_Table={:?}, IDT_Table={:?}\n", gdt_vaddr, idt_vaddr); + debug!("GDT_Table={:?}, IDT_Table={:?}\n", gdt_vaddr, idt_vaddr); } set_current_core_tss(stack_start, 0); @@ -107,10 +107,9 @@ pub fn setup_arch_post() -> Result<(), SystemError> { fn set_current_core_tss(stack_start: usize, ist0: usize) { let current_tss = unsafe { TSSManager::current_tss() }; - kdebug!( + debug!( "set_current_core_tss: stack_start={:#x}, ist0={:#x}\n", - stack_start, - ist0 + stack_start, ist0 ); current_tss.set_rsp(x86::Ring::Ring0, stack_start as u64); current_tss.set_ist(0, ist0 as u64); diff --git a/kernel/src/arch/x86_64/interrupt/ipi.rs b/kernel/src/arch/x86_64/interrupt/ipi.rs index 87cc785d..78c6ae78 100644 --- a/kernel/src/arch/x86_64/interrupt/ipi.rs +++ b/kernel/src/arch/x86_64/interrupt/ipi.rs @@ -1,4 +1,5 @@ use alloc::sync::Arc; +use log::error; use system_error::SystemError; use x86::apic::ApicId; @@ -13,7 +14,6 @@ use crate::{ irqdesc::{irq_desc_manager, IrqDesc, IrqFlowHandler, IrqHandler}, HardwareIrqNumber, IrqNumber, }, - kerror, smp::cpu::ProcessorId, }; @@ -122,14 +122,14 @@ impl From for x86::apic::DestinationShorthand { #[inline(always)] pub fn send_ipi(kind: IpiKind, target: IpiTarget) { - // kdebug!("send_ipi: {:?} {:?}", kind, target); + // debug!("send_ipi: {:?} {:?}", kind, target); let ipi_vec = ArchIpiKind::from(kind).into(); let target = ArchIpiTarget::from(target); let shorthand: x86::apic::DestinationShorthand = target.into(); let destination: x86::apic::ApicId = target.into(); let icr = if CurrentApic.x2apic_enabled() { - // kdebug!("send_ipi: x2apic"); + // debug!("send_ipi: x2apic"); x86::apic::Icr::for_x2apic( ipi_vec, destination, @@ -141,7 +141,7 @@ pub fn send_ipi(kind: IpiKind, target: IpiTarget) { x86::apic::TriggerMode::Edge, ) } else { - // kdebug!("send_ipi: xapic"); + // debug!("send_ipi: xapic"); x86::apic::Icr::for_xapic( ipi_vec, destination, @@ -257,7 +257,7 @@ impl IrqFlowHandler for X86_64IpiIrqFlowHandler { CurrentApic.send_eoi(); } _ => { - kerror!("Unknown IPI: {}", irq.data()); + error!("Unknown IPI: {}", irq.data()); CurrentApic.send_eoi(); } } diff --git a/kernel/src/arch/x86_64/interrupt/mod.rs b/kernel/src/arch/x86_64/interrupt/mod.rs index ddd7db57..1d087897 100644 --- a/kernel/src/arch/x86_64/interrupt/mod.rs +++ b/kernel/src/arch/x86_64/interrupt/mod.rs @@ -9,12 +9,12 @@ use core::{ sync::atomic::{compiler_fence, Ordering}, }; +use log::error; use system_error::SystemError; use crate::{ arch::CurrentIrqArch, exception::{InterruptArch, IrqFlags, IrqFlagsGuard, IrqNumber}, - kerror, }; use super::{ @@ -85,7 +85,7 @@ impl InterruptArch for X86_64InterruptArch { } fn ack_bad_irq(irq: IrqNumber) { - kerror!("Unexpected IRQ trap at vector {}", irq.data()); + error!("Unexpected IRQ trap at vector {}", irq.data()); CurrentApic.send_eoi(); } diff --git a/kernel/src/arch/x86_64/interrupt/trap.rs b/kernel/src/arch/x86_64/interrupt/trap.rs index a75c7371..ecc03f8d 100644 --- a/kernel/src/arch/x86_64/interrupt/trap.rs +++ b/kernel/src/arch/x86_64/interrupt/trap.rs @@ -1,9 +1,9 @@ +use log::{error, warn}; use system_error::SystemError; use crate::{ arch::{CurrentIrqArch, MMArch}, exception::InterruptArch, - kerror, kwarn, mm::VirtAddr, process::ProcessManager, smp::core::smp_get_processor_id, @@ -112,7 +112,7 @@ pub fn arch_trap_init() -> Result<(), SystemError> { /// 处理除法错误 0 #DE #[no_mangle] unsafe extern "C" fn do_divide_error(regs: &'static TrapFrame, error_code: u64) { - kerror!( + error!( "do_divide_error(0), \tError code: {:#x},\trsp: {:#x},\trip: {:#x},\t CPU: {}, \tpid: {:?}", error_code, regs.rsp, @@ -126,7 +126,7 @@ unsafe extern "C" fn do_divide_error(regs: &'static TrapFrame, error_code: u64) /// 处理调试异常 1 #DB #[no_mangle] unsafe extern "C" fn do_debug(regs: &'static TrapFrame, error_code: u64) { - kerror!( + error!( "do_debug(1), \tError code: {:#x},\trsp: {:#x},\trip: {:#x},\t CPU: {}, \tpid: {:?}", error_code, regs.rsp, @@ -140,7 +140,7 @@ unsafe extern "C" fn do_debug(regs: &'static TrapFrame, error_code: u64) { /// 处理NMI中断 2 NMI #[no_mangle] unsafe extern "C" fn do_nmi(regs: &'static TrapFrame, error_code: u64) { - kerror!( + error!( "do_nmi(2), \tError code: {:#x},\trsp: {:#x},\trip: {:#x},\t CPU: {}, \tpid: {:?}", error_code, regs.rsp, @@ -154,7 +154,7 @@ unsafe extern "C" fn do_nmi(regs: &'static TrapFrame, error_code: u64) { /// 处理断点异常 3 #BP #[no_mangle] unsafe extern "C" fn do_int3(regs: &'static TrapFrame, error_code: u64) { - kerror!( + error!( "do_int3(3), \tError code: {:#x},\trsp: {:#x},\trip: {:#x},\t CPU: {}, \tpid: {:?}", error_code, regs.rsp, @@ -168,7 +168,7 @@ unsafe extern "C" fn do_int3(regs: &'static TrapFrame, error_code: u64) { /// 处理溢出异常 4 #OF #[no_mangle] unsafe extern "C" fn do_overflow(regs: &'static TrapFrame, error_code: u64) { - kerror!( + error!( "do_overflow(4), \tError code: {:#x},\trsp: {:#x},\trip: {:#x},\t CPU: {}, \tpid: {:?}", error_code, regs.rsp, @@ -182,7 +182,7 @@ unsafe extern "C" fn do_overflow(regs: &'static TrapFrame, error_code: u64) { /// 处理BOUND指令检查异常 5 #BR #[no_mangle] unsafe extern "C" fn do_bounds(regs: &'static TrapFrame, error_code: u64) { - kerror!( + error!( "do_bounds(5), \tError code: {:#x},\trsp: {:#x},\trip: {:#x},\t CPU: {}, \tpid: {:?}", error_code, regs.rsp, @@ -196,7 +196,7 @@ unsafe extern "C" fn do_bounds(regs: &'static TrapFrame, error_code: u64) { /// 处理未定义操作码异常 6 #UD #[no_mangle] unsafe extern "C" fn do_undefined_opcode(regs: &'static TrapFrame, error_code: u64) { - kerror!( + error!( "do_undefined_opcode(6), \tError code: {:#x},\trsp: {:#x},\trip: {:#x},\t CPU: {}, \tpid: {:?}", error_code, regs.rsp, @@ -210,7 +210,7 @@ unsafe extern "C" fn do_undefined_opcode(regs: &'static TrapFrame, error_code: u /// 处理设备不可用异常(FPU不存在) 7 #NM #[no_mangle] unsafe extern "C" fn do_dev_not_avaliable(regs: &'static TrapFrame, error_code: u64) { - kerror!( + error!( "do_dev_not_avaliable(7), \tError code: {:#x},\trsp: {:#x},\trip: {:#x},\t CPU: {}, \tpid: {:?}", error_code, regs.rsp, @@ -224,7 +224,7 @@ unsafe extern "C" fn do_dev_not_avaliable(regs: &'static TrapFrame, error_code: /// 处理双重错误 8 #DF #[no_mangle] unsafe extern "C" fn do_double_fault(regs: &'static TrapFrame, error_code: u64) { - kerror!( + error!( "do_double_fault(8), \tError code: {:#x},\trsp: {:#x},\trip: {:#x},\t CPU: {}, \tpid: {:?}", error_code, regs.rsp, @@ -238,7 +238,7 @@ unsafe extern "C" fn do_double_fault(regs: &'static TrapFrame, error_code: u64) /// 处理协处理器段越界 9 #MF #[no_mangle] unsafe extern "C" fn do_coprocessor_segment_overrun(regs: &'static TrapFrame, error_code: u64) { - kerror!( + error!( "do_coprocessor_segment_overrun(9), \tError code: {:#x},\trsp: {:#x},\trip: {:#x},\t CPU: {}, \tpid: {:?}", error_code, regs.rsp, @@ -272,7 +272,7 @@ unsafe extern "C" fn do_invalid_TSS(regs: &'static TrapFrame, error_code: u64) { ERR_MSG_4 }; - kerror!( + error!( "do_invalid_TSS(10), \tError code: {:#x},\trsp: {:#x},\trip: {:#x},\t CPU: {}, \tpid: {:?}\n{}{}", error_code, regs.rsp, @@ -288,7 +288,7 @@ unsafe extern "C" fn do_invalid_TSS(regs: &'static TrapFrame, error_code: u64) { /// 处理段不存在 11 #NP #[no_mangle] unsafe extern "C" fn do_segment_not_exists(regs: &'static TrapFrame, error_code: u64) { - kerror!( + error!( "do_segment_not_exists(11), \tError code: {:#x},\trsp: {:#x},\trip: {:#x},\t CPU: {}, \tpid: {:?}", error_code, regs.rsp, @@ -302,7 +302,7 @@ unsafe extern "C" fn do_segment_not_exists(regs: &'static TrapFrame, error_code: /// 处理栈段错误 12 #SS #[no_mangle] unsafe extern "C" fn do_stack_segment_fault(regs: &'static TrapFrame, error_code: u64) { - kerror!( + error!( "do_stack_segment_fault(12), \tError code: {:#x},\trsp: {:#x},\trip: {:#x},\t CPU: {}, \tpid: {:?}", error_code, regs.rsp, @@ -343,7 +343,7 @@ unsafe extern "C" fn do_general_protection(regs: &'static TrapFrame, error_code: } else { "" }; - kerror!( + error!( "do_general_protection(13), \tError code: {:#x},\trsp: {:#x},\trip: {:#x},\t rflags: {:#x}\t CPU: {}, \tpid: {:?} {}{}{} Segment Selector Index: {:#x}\n @@ -363,7 +363,7 @@ Segment Selector Index: {:#x}\n /// 处理页错误 14 #PF #[no_mangle] unsafe extern "C" fn do_page_fault(regs: &'static TrapFrame, error_code: u64) { - // kerror!( + // error!( // "do_page_fault(14), \tError code: {:#x},\trsp: {:#x},\trip: {:#x},\t CPU: {}, \tpid: {:?}, \nFault Address: {:#x}", // error_code, // regs.rsp, @@ -401,7 +401,7 @@ unsafe extern "C" fn do_page_fault(regs: &'static TrapFrame, error_code: u64) { // panic!("Page Fault"); CurrentIrqArch::interrupt_disable(); let address = x86::controlregs::cr2(); - // crate::kinfo!( + // crate::info!( // "fault address: {:#x}, error_code: {:#b}, pid: {}\n", // address, // error_code, @@ -421,7 +421,7 @@ unsafe extern "C" fn do_page_fault(regs: &'static TrapFrame, error_code: u64) { /// 处理x87 FPU错误 16 #MF #[no_mangle] unsafe extern "C" fn do_x87_FPU_error(regs: &'static TrapFrame, error_code: u64) { - kerror!( + error!( "do_x87_FPU_error(16), \tError code: {:#x},\trsp: {:#x},\trip: {:#x},\t CPU: {}, \tpid: {:?}", error_code, regs.rsp, @@ -435,7 +435,7 @@ unsafe extern "C" fn do_x87_FPU_error(regs: &'static TrapFrame, error_code: u64) /// 处理对齐检查 17 #AC #[no_mangle] unsafe extern "C" fn do_alignment_check(regs: &'static TrapFrame, error_code: u64) { - kerror!( + error!( "do_alignment_check(17), \tError code: {:#x},\trsp: {:#x},\trip: {:#x},\t CPU: {}, \tpid: {:?}", error_code, regs.rsp, @@ -449,7 +449,7 @@ unsafe extern "C" fn do_alignment_check(regs: &'static TrapFrame, error_code: u6 /// 处理机器检查 18 #MC #[no_mangle] unsafe extern "C" fn do_machine_check(regs: &'static TrapFrame, error_code: u64) { - kerror!( + error!( "do_machine_check(18), \tError code: {:#x},\trsp: {:#x},\trip: {:#x},\t CPU: {}, \tpid: {:?}", error_code, regs.rsp, @@ -463,7 +463,7 @@ unsafe extern "C" fn do_machine_check(regs: &'static TrapFrame, error_code: u64) /// 处理SIMD异常 19 #XM #[no_mangle] unsafe extern "C" fn do_SIMD_exception(regs: &'static TrapFrame, error_code: u64) { - kerror!( + error!( "do_SIMD_exception(19), \tError code: {:#x},\trsp: {:#x},\trip: {:#x},\t CPU: {}, \tpid: {:?}", error_code, regs.rsp, @@ -477,7 +477,7 @@ unsafe extern "C" fn do_SIMD_exception(regs: &'static TrapFrame, error_code: u64 /// 处理虚拟化异常 20 #VE #[no_mangle] unsafe extern "C" fn do_virtualization_exception(regs: &'static TrapFrame, error_code: u64) { - kerror!( + error!( "do_virtualization_exception(20), \tError code: {:#x},\trsp: {:#x},\trip: {:#x},\t CPU: {}, \tpid: {:?}", error_code, regs.rsp, @@ -490,5 +490,5 @@ unsafe extern "C" fn do_virtualization_exception(regs: &'static TrapFrame, error #[no_mangle] unsafe extern "C" fn ignore_int_handler(_regs: &'static TrapFrame, _error_code: u64) { - kwarn!("Unknown interrupt."); + warn!("Unknown interrupt."); } diff --git a/kernel/src/arch/x86_64/ipc/signal.rs b/kernel/src/arch/x86_64/ipc/signal.rs index af4c6026..caf44b53 100644 --- a/kernel/src/arch/x86_64/ipc/signal.rs +++ b/kernel/src/arch/x86_64/ipc/signal.rs @@ -1,5 +1,6 @@ use core::{ffi::c_void, intrinsics::unlikely, mem::size_of}; +use log::error; use system_error::SystemError; use crate::{ @@ -14,7 +15,6 @@ use crate::{ signal::set_current_sig_blocked, signal_types::{SaHandlerType, SigInfo, Sigaction, SigactionType, SignalArch}, }, - kerror, mm::MemoryManagementArch, process::ProcessManager, sched::{schedule, SchedMode}, @@ -86,7 +86,7 @@ impl From for Signal { let ret: Signal = unsafe { core::mem::transmute(value) }; return ret; } else { - kerror!("Try to convert an invalid number to Signal"); + error!("Try to convert an invalid number to Signal"); return Signal::INVALID; } } @@ -101,7 +101,7 @@ impl From for usize { impl From for Signal { fn from(value: i32) -> Self { if value < 0 { - kerror!("Try to convert an invalid number to Signal"); + error!("Try to convert an invalid number to Signal"); return Signal::INVALID; } else { return Self::from(value as usize); @@ -145,7 +145,7 @@ impl Signal { pub fn handle_default(&self) { match self { Signal::INVALID => { - kerror!("attempting to handler an Invalid"); + error!("attempting to handler an Invalid"); } Signal::SIGHUP => sig_terminate(*self), Signal::SIGINT => sig_terminate(*self), @@ -461,7 +461,7 @@ impl SignalArch for X86_64SignalArch { match sigaction.action() { SigactionType::SaHandler(action_type) => match action_type { SaHandlerType::Error => { - kerror!("Trying to handle a Sigerror on Process:{:?}", pcb.pid()); + error!("Trying to handle a Sigerror on Process:{:?}", pcb.pid()); return; } SaHandlerType::Default => { @@ -488,7 +488,7 @@ impl SignalArch for X86_64SignalArch { let res: Result = handle_signal(sig_number, &mut sigaction, &info.unwrap(), &oldset, frame); if res.is_err() { - kerror!( + error!( "Error occurred when handling signal: {}, pid={:?}, errcode={:?}", sig_number as i32, ProcessManager::current_pcb().pid(), @@ -502,7 +502,7 @@ impl SignalArch for X86_64SignalArch { // 如果当前的rsp不来自用户态,则认为产生了错误(或被SROP攻击) if UserBufferWriter::new(frame, size_of::(), true).is_err() { - kerror!("rsp doesn't from user level"); + error!("rsp doesn't from user level"); let _r = Syscall::kill(ProcessManager::current_pcb().pid(), Signal::SIGSEGV as i32) .map_err(|e| e.to_posix_errno()); return trap_frame.rax; @@ -511,7 +511,7 @@ impl SignalArch for X86_64SignalArch { set_current_sig_blocked(&mut sigmask); // 从用户栈恢复sigcontext if !unsafe { &mut (*frame).context }.restore_sigcontext(trap_frame) { - kerror!("unable to restore sigcontext"); + error!("unable to restore sigcontext"); let _r = Syscall::kill(ProcessManager::current_pcb().pid(), Signal::SIGSEGV as i32) .map_err(|e| e.to_posix_errno()); // 如果这里返回 err 值的话会丢失上一个系统调用的返回值 @@ -569,7 +569,7 @@ fn setup_frame( sig.handle_default(); return Ok(0); } else { - kerror!("attempting to execute a signal handler from kernel"); + error!("attempting to execute a signal handler from kernel"); sig.handle_default(); return Err(SystemError::EINVAL); } @@ -578,7 +578,7 @@ fn setup_frame( if sigaction.flags().contains(SigFlags::SA_RESTORER) { ret_code_ptr = sigaction.restorer().unwrap().data() as *mut c_void; } else { - kerror!( + error!( "pid-{:?} forgot to set SA_FLAG_RESTORER for signal {:?}", ProcessManager::current_pcb().pid(), sig as i32 @@ -588,12 +588,12 @@ fn setup_frame( Signal::SIGSEGV as i32, ); if r.is_err() { - kerror!("In setup_sigcontext: generate SIGSEGV signal failed"); + error!("In setup_sigcontext: generate SIGSEGV signal failed"); } return Err(SystemError::EINVAL); } if sigaction.restorer().is_none() { - kerror!( + error!( "restorer in process:{:?} is not defined", ProcessManager::current_pcb().pid() ); @@ -611,12 +611,12 @@ fn setup_frame( }, SigactionType::SaSigaction(_) => { //TODO 这里应该是可以恢复栈的,等后续来做 - kerror!("trying to recover from sigaction type instead of handler"); + error!("trying to recover from sigaction type instead of handler"); return Err(SystemError::EINVAL); } } let frame: *mut SigFrame = get_stack(trap_frame, size_of::()); - // kdebug!("frame=0x{:016x}", frame as usize); + // debug!("frame=0x{:016x}", frame as usize); // 要求这个frame的地址位于用户空间,因此进行校验 let r: Result, SystemError> = UserBufferWriter::new(frame, size_of::(), true); @@ -625,9 +625,9 @@ fn setup_frame( // todo: 生成一个sigsegv let r = Syscall::kill(ProcessManager::current_pcb().pid(), Signal::SIGSEGV as i32); if r.is_err() { - kerror!("In setup frame: generate SIGSEGV signal failed"); + error!("In setup frame: generate SIGSEGV signal failed"); } - kerror!("In setup frame: access check failed"); + error!("In setup frame: access check failed"); return Err(SystemError::EFAULT); } @@ -636,7 +636,7 @@ fn setup_frame( .map_err(|e| -> SystemError { let r = Syscall::kill(ProcessManager::current_pcb().pid(), Signal::SIGSEGV as i32); if r.is_err() { - kerror!("In copy_siginfo_to_user: generate SIGSEGV signal failed"); + error!("In copy_siginfo_to_user: generate SIGSEGV signal failed"); } return e; })?; @@ -650,7 +650,7 @@ fn setup_frame( .map_err(|e: SystemError| -> SystemError { let r = Syscall::kill(ProcessManager::current_pcb().pid(), Signal::SIGSEGV as i32); if r.is_err() { - kerror!("In setup_sigcontext: generate SIGSEGV signal failed"); + error!("In setup_sigcontext: generate SIGSEGV signal failed"); } return e; })? @@ -707,7 +707,7 @@ fn sig_terminate_dump(sig: Signal) { fn sig_stop(sig: Signal) { let guard = unsafe { CurrentIrqArch::save_and_disable_irq() }; ProcessManager::mark_stop().unwrap_or_else(|e| { - kerror!( + error!( "sleep error :{:?},failed to sleep process :{:?}, with signal :{:?}", e, ProcessManager::current_pcb(), @@ -721,7 +721,7 @@ fn sig_stop(sig: Signal) { /// 信号默认处理函数——继续进程 fn sig_continue(sig: Signal) { ProcessManager::wakeup_stop(&ProcessManager::current_pcb()).unwrap_or_else(|_| { - kerror!( + error!( "Failed to wake up process pid = {:?} with signal :{:?}", ProcessManager::current_pcb().pid(), sig diff --git a/kernel/src/arch/x86_64/kvm/mod.rs b/kernel/src/arch/x86_64/kvm/mod.rs index c9b8b19a..d5f6c07a 100644 --- a/kernel/src/arch/x86_64/kvm/mod.rs +++ b/kernel/src/arch/x86_64/kvm/mod.rs @@ -2,13 +2,10 @@ use crate::arch::kvm::vmx::vmcs::VmcsFields; use crate::arch::kvm::vmx::vmx_asm_wrapper::{vmx_vmlaunch, vmx_vmread}; use crate::libs::mutex::Mutex; use crate::virt::kvm::vm; -use crate::{ - kdebug, - kerror, - // libs::spinlock::{SpinLock, SpinLockGuard}, -}; + use alloc::sync::Arc; use core::arch::asm; +use log::{debug, error}; use raw_cpuid::CpuId; use system_error::SystemError; // use crate::virt::kvm::guest_code; @@ -54,7 +51,7 @@ impl X86_64KVMArch { #[deny(clippy::match_single_binding)] pub fn kvm_arch_dev_ioctl(cmd: u32, _arg: usize) -> Result { - kerror!("unknown kvm ioctl cmd: {}", cmd); + error!("unknown kvm ioctl cmd: {}", cmd); return Err(SystemError::EINVAL); } @@ -74,7 +71,7 @@ impl X86_64KVMArch { Ok(_) => {} Err(e) => { let vmx_err = vmx_vmread(VmcsFields::VMEXIT_INSTR_ERR as u32).unwrap(); - kdebug!("vmlaunch failed: {:?}", vmx_err); + debug!("vmlaunch failed: {:?}", vmx_err); return Err(e); } } @@ -103,12 +100,12 @@ impl X86_64KVMArch { #[no_mangle] pub extern "C" fn guest_code() { - kdebug!("guest_code"); + debug!("guest_code"); loop { unsafe { asm!("mov rax, 0", "mov rcx, 0", "cpuid"); } unsafe { asm!("nop") }; - kdebug!("guest_code"); + debug!("guest_code"); } } diff --git a/kernel/src/arch/x86_64/kvm/vmx/mmu.rs b/kernel/src/arch/x86_64/kvm/vmx/mmu.rs index 2c03c238..e28b3f03 100644 --- a/kernel/src/arch/x86_64/kvm/vmx/mmu.rs +++ b/kernel/src/arch/x86_64/kvm/vmx/mmu.rs @@ -1,11 +1,11 @@ use crate::{ arch::kvm::vmx::ept::EptMapper, - kdebug, libs::mutex::Mutex, mm::{page::PageFlags, syscall::ProtFlags}, virt::kvm::host_mem::{__gfn_to_pfn, kvm_vcpu_gfn_to_memslot, PAGE_MASK, PAGE_SHIFT}, }; use bitfield_struct::bitfield; +use log::debug; use system_error::SystemError; use super::{ @@ -105,7 +105,7 @@ fn tdp_page_fault( error_code: u32, prefault: bool, ) -> Result<(), SystemError> { - kdebug!("tdp_page_fault"); + debug!("tdp_page_fault"); let gfn = gpa >> PAGE_SHIFT; // 物理地址右移12位得到物理页框号(相对于虚拟机而言) // 分配缓存池,为了避免在运行时分配空间失败,这里提前分配/填充足额的空间 mmu_topup_memory_caches(vcpu)?; @@ -211,7 +211,7 @@ pub fn __direct_map( pfn: u64, _prefault: bool, ) -> Result { - kdebug!("gpa={}, pfn={}, root_hpa={:x}", gpa, pfn, vcpu.mmu.root_hpa); + debug!("gpa={}, pfn={}, root_hpa={:x}", gpa, pfn, vcpu.mmu.root_hpa); // 判断vcpu.mmu.root_hpa是否有效 if vcpu.mmu.root_hpa == 0 { return Err(SystemError::KVM_HVA_ERR_BAD); diff --git a/kernel/src/arch/x86_64/kvm/vmx/vcpu.rs b/kernel/src/arch/x86_64/kvm/vmx/vcpu.rs index b718f5f6..46f2ed53 100644 --- a/kernel/src/arch/x86_64/kvm/vmx/vcpu.rs +++ b/kernel/src/arch/x86_64/kvm/vmx/vcpu.rs @@ -9,7 +9,7 @@ use crate::arch::kvm::vmx::{VcpuRegIndex, X86_CR0}; use crate::arch::mm::{LockedFrameAllocator, PageMapper}; use crate::arch::x86_64::mm::X86_64MMArch; use crate::arch::MMArch; -use crate::kdebug; + use crate::mm::{phys_2_virt, VirtAddr}; use crate::mm::{MemoryManagementArch, PageTableKind}; use crate::virt::kvm::vcpu::Vcpu; @@ -17,6 +17,7 @@ use crate::virt::kvm::vm::Vm; use alloc::alloc::Global; use alloc::boxed::Box; use core::slice; +use log::debug; use raw_cpuid::CpuId; use system_error::SystemError; use x86; @@ -132,13 +133,13 @@ impl VcpuData { // Get the Virtual Machine Control Structure revision identifier (VMCS revision ID) // (Intel Manual: 25.11.5 VMXON Region) let revision_id = unsafe { (msr::rdmsr(msr::IA32_VMX_BASIC) as u32) & 0x7FFF_FFFF }; - kdebug!("[+] VMXON Region Virtual Address: {:p}", self.vmxon_region); - kdebug!( + debug!("[+] VMXON Region Virtual Address: {:p}", self.vmxon_region); + debug!( "[+] VMXON Region Physical Addresss: 0x{:x}", self.vmxon_region_physical_address ); - kdebug!("[+] VMCS Region Virtual Address: {:p}", self.vmcs_region); - kdebug!( + debug!("[+] VMCS Region Virtual Address: {:p}", self.vmcs_region); + debug!( "[+] VMCS Region Physical Address1: 0x{:x}", self.vmcs_region_physical_address ); @@ -150,7 +151,7 @@ impl VcpuData { impl VmxVcpu { pub fn new(vcpu_id: u32, parent_vm: Vm) -> Result { - kdebug!("Creating processor {}", vcpu_id); + debug!("Creating processor {}", vcpu_id); let instance = Self { vcpu_id, vcpu_ctx: VcpuContextFrame { @@ -251,8 +252,8 @@ impl VmxVcpu { self.vcpu_ctx.regs[VcpuRegIndex::Rsp as usize] as u64, )?; vmx_vmwrite(VmcsFields::GUEST_RIP as u32, self.vcpu_ctx.rip as u64)?; - kdebug!("vmcs init guest rip: {:#x}", self.vcpu_ctx.rip as u64); - kdebug!( + debug!("vmcs init guest rip: {:#x}", self.vcpu_ctx.rip as u64); + debug!( "vmcs init guest rsp: {:#x}", self.vcpu_ctx.regs[VcpuRegIndex::Rsp as usize] as u64 ); @@ -338,7 +339,7 @@ impl VmxVcpu { })?; // vmx_vmwrite(VmcsFields::HOST_RIP as u32, vmx_return as *const () as u64)?; - // kdebug!("vmcs init host rip: {:#x}", vmx_return as *const () as u64); + // debug!("vmcs init host rip: {:#x}", vmx_return as *const () as u64); Ok(()) } @@ -388,7 +389,7 @@ impl VmxVcpu { } fn kvm_mmu_load(&mut self) -> Result<(), SystemError> { - kdebug!("kvm_mmu_load!"); + debug!("kvm_mmu_load!"); // 申请并创建新的页表 let mapper: crate::mm::page::PageMapper = unsafe { PageMapper::create(PageTableKind::EPT, LockedFrameAllocator) @@ -399,7 +400,7 @@ impl VmxVcpu { let set_eptp_fn = self.mmu.set_eptp.unwrap(); set_eptp_fn(ept_root_hpa.data() as u64)?; self.mmu.root_hpa = ept_root_hpa.data() as u64; - kdebug!("ept_root_hpa:{:x}!", ept_root_hpa.data() as u64); + debug!("ept_root_hpa:{:x}!", ept_root_hpa.data() as u64); return Ok(()); } @@ -415,33 +416,33 @@ impl Vcpu for VmxVcpu { fn virtualize_cpu(&mut self) -> Result<(), SystemError> { match has_intel_vmx_support() { Ok(_) => { - kdebug!("[+] CPU supports Intel VMX"); + debug!("[+] CPU supports Intel VMX"); } Err(e) => { - kdebug!("[-] CPU does not support Intel VMX: {:?}", e); + debug!("[-] CPU does not support Intel VMX: {:?}", e); return Err(SystemError::ENOSYS); } }; match enable_vmx_operation() { Ok(_) => { - kdebug!("[+] Enabling Virtual Machine Extensions (VMX)"); + debug!("[+] Enabling Virtual Machine Extensions (VMX)"); } Err(_) => { - kdebug!("[-] VMX operation is not supported on this processor."); + debug!("[-] VMX operation is not supported on this processor."); return Err(SystemError::ENOSYS); } } vmxon(self.data.vmxon_region_physical_address)?; - kdebug!("[+] VMXON successful!"); + debug!("[+] VMXON successful!"); vmx_vmclear(self.data.vmcs_region_physical_address)?; vmx_vmptrld(self.data.vmcs_region_physical_address)?; - kdebug!("[+] VMPTRLD successful!"); + debug!("[+] VMPTRLD successful!"); self.vmcs_init().expect("vncs_init fail"); - kdebug!("[+] VMCS init!"); - // kdebug!("vmcs init host rip: {:#x}", vmx_return as *const () as u64); - // kdebug!("vmcs init host rsp: {:#x}", x86::bits64::registers::rsp()); + debug!("[+] VMCS init!"); + // debug!("vmcs init host rip: {:#x}", vmx_return as *const () as u64); + // debug!("vmcs init host rsp: {:#x}", x86::bits64::registers::rsp()); // vmx_vmwrite(VmcsFields::HOST_RSP as u32, x86::bits64::registers::rsp())?; // vmx_vmwrite(VmcsFields::HOST_RIP as u32, vmx_return as *const () as u64)?; // vmx_vmwrite(VmcsFields::HOST_RSP as u32, x86::bits64::registers::rsp())?; @@ -476,7 +477,7 @@ pub fn get_segment_base(gdt_base: *const u64, gdt_size: u16, segment_selector: u let virtaddr = phys_2_virt(segment_base.try_into().unwrap()) .try_into() .unwrap(); - kdebug!( + debug!( "segment_base={:x}", phys_2_virt(segment_base.try_into().unwrap()) ); @@ -536,7 +537,7 @@ pub fn adjust_vmx_exit_controls() -> u32 { pub fn adjust_vmx_pinbased_controls() -> u32 { let mut controls: u32 = 16; adjust_vmx_controls(0, 0, msr::IA32_VMX_TRUE_PINBASED_CTLS, &mut controls); - // kdebug!("adjust_vmx_pinbased_controls: {:x}", controls); + // debug!("adjust_vmx_pinbased_controls: {:x}", controls); return controls; } @@ -593,11 +594,11 @@ pub fn enable_vmx_operation() -> Result<(), SystemError> { unsafe { controlregs::cr4_write(cr4) }; set_lock_bit()?; - kdebug!("[+] Lock bit set via IA32_FEATURE_CONTROL"); + debug!("[+] Lock bit set via IA32_FEATURE_CONTROL"); set_cr0_bits(); - kdebug!("[+] Mandatory bits in CR0 set/cleared"); + debug!("[+] Mandatory bits in CR0 set/cleared"); set_cr4_bits(); - kdebug!("[+] Mandatory bits in CR4 set/cleared"); + debug!("[+] Mandatory bits in CR4 set/cleared"); Ok(()) } diff --git a/kernel/src/arch/x86_64/kvm/vmx/vmexit.rs b/kernel/src/arch/x86_64/kvm/vmx/vmexit.rs index 32fb3372..b95d51df 100644 --- a/kernel/src/arch/x86_64/kvm/vmx/vmexit.rs +++ b/kernel/src/arch/x86_64/kvm/vmx/vmexit.rs @@ -1,8 +1,9 @@ use super::vmcs::{VmcsFields, VmxExitReason}; use super::vmx_asm_wrapper::{vmx_vmread, vmx_vmwrite}; -use crate::kdebug; + use crate::virt::kvm::vm; use core::arch::asm; +use log::debug; use system_error::SystemError; use x86::vmx::vmcs::ro::GUEST_PHYSICAL_ADDR_FULL; @@ -147,7 +148,7 @@ pub struct GuestCpuContext { #[no_mangle] pub extern "C" fn vmx_return() { - kdebug!("vmx_return!"); + debug!("vmx_return!"); unsafe { save_rpg() }; vmexit_handler(); // XMM registers are vector registers. They're renamed onto the FP/SIMD register file @@ -181,14 +182,14 @@ pub extern "C" fn vmx_return() { #[no_mangle] extern "C" fn vmexit_handler() { // let guest_cpu_context = unsafe { guest_cpu_context_ptr.as_mut().unwrap() }; - // kdebug!("guest_cpu_context_ptr={:p}",guest_cpu_context_ptr); - kdebug!("vmexit handler!"); + // debug!("guest_cpu_context_ptr={:p}",guest_cpu_context_ptr); + debug!("vmexit handler!"); let exit_reason = vmx_vmread(VmcsFields::VMEXIT_EXIT_REASON as u32).unwrap() as u32; let exit_basic_reason = exit_reason & 0x0000_ffff; let guest_rip = vmx_vmread(VmcsFields::GUEST_RIP as u32).unwrap(); // let guest_rsp = vmx_vmread(VmcsFields::GUEST_RSP as u32).unwrap(); - kdebug!("guest_rip={:x}", guest_rip); + debug!("guest_rip={:x}", guest_rip); let _guest_rflags = vmx_vmread(VmcsFields::GUEST_RFLAGS as u32).unwrap(); match VmxExitReason::from(exit_basic_reason as i32) { @@ -205,28 +206,28 @@ extern "C" fn vmexit_handler() { | VmxExitReason::VMFUNC | VmxExitReason::INVEPT | VmxExitReason::INVVPID => { - kdebug!("vmexit handler: vmx instruction!"); + debug!("vmexit handler: vmx instruction!"); vmexit_vmx_instruction_executed().expect("previledge instruction handle error"); } VmxExitReason::CPUID => { - kdebug!("vmexit handler: cpuid instruction!"); + debug!("vmexit handler: cpuid instruction!"); // vmexit_cpuid_handler(guest_cpu_context); adjust_rip(guest_rip).unwrap(); } VmxExitReason::RDMSR => { - kdebug!("vmexit handler: rdmsr instruction!"); + debug!("vmexit handler: rdmsr instruction!"); adjust_rip(guest_rip).unwrap(); } VmxExitReason::WRMSR => { - kdebug!("vmexit handler: wrmsr instruction!"); + debug!("vmexit handler: wrmsr instruction!"); adjust_rip(guest_rip).unwrap(); } VmxExitReason::TRIPLE_FAULT => { - kdebug!("vmexit handler: triple fault!"); + debug!("vmexit handler: triple fault!"); adjust_rip(guest_rip).unwrap(); } VmxExitReason::EPT_VIOLATION => { - kdebug!("vmexit handler: ept violation!"); + debug!("vmexit handler: ept violation!"); let gpa = vmx_vmread(GUEST_PHYSICAL_ADDR_FULL).unwrap(); let exit_qualification = vmx_vmread(VmcsFields::VMEXIT_QUALIFICATION as u32).unwrap(); /* It is a write fault? */ @@ -244,17 +245,17 @@ extern "C" fn vmexit_handler() { .expect("ept page fault error"); } _ => { - kdebug!( + debug!( "vmexit handler: unhandled vmexit reason: {}!", exit_basic_reason ); let info = vmx_vmread(VmcsFields::VMEXIT_INSTR_LEN as u32).unwrap() as u32; - kdebug!("vmexit handler: VMEXIT_INSTR_LEN: {}!", info); + debug!("vmexit handler: VMEXIT_INSTR_LEN: {}!", info); let info = vmx_vmread(VmcsFields::VMEXIT_INSTR_INFO as u32).unwrap() as u32; - kdebug!("vmexit handler: VMEXIT_INSTR_INFO: {}!", info); + debug!("vmexit handler: VMEXIT_INSTR_INFO: {}!", info); let info = vmx_vmread(VmcsFields::CTRL_EXPECTION_BITMAP as u32).unwrap() as u32; - kdebug!("vmexit handler: CTRL_EXPECTION_BITMAP: {}!", info); + debug!("vmexit handler: CTRL_EXPECTION_BITMAP: {}!", info); adjust_rip(guest_rip).unwrap(); // panic!(); diff --git a/kernel/src/arch/x86_64/kvm/vmx/vmx_asm_wrapper.rs b/kernel/src/arch/x86_64/kvm/vmx/vmx_asm_wrapper.rs index 449127ea..2402b07f 100644 --- a/kernel/src/arch/x86_64/kvm/vmx/vmx_asm_wrapper.rs +++ b/kernel/src/arch/x86_64/kvm/vmx/vmx_asm_wrapper.rs @@ -1,6 +1,7 @@ use super::vmcs::VmcsFields; -use crate::kdebug; + use core::arch::asm; +use log::debug; use system_error::SystemError; use x86; /// Enable VMX operation. @@ -8,7 +9,7 @@ pub fn vmxon(vmxon_pa: u64) -> Result<(), SystemError> { match unsafe { x86::bits64::vmx::vmxon(vmxon_pa) } { Ok(_) => Ok(()), Err(e) => { - kdebug!("vmxon fail: {:?}", e); + debug!("vmxon fail: {:?}", e); Err(SystemError::EVMXONFailed) } } @@ -27,8 +28,8 @@ pub fn vmx_vmwrite(vmcs_field: u32, value: u64) -> Result<(), SystemError> { match unsafe { x86::bits64::vmx::vmwrite(vmcs_field, value) } { Ok(_) => Ok(()), Err(e) => { - kdebug!("vmx_write fail: {:?}", e); - kdebug!("vmcs_field: {:x}", vmcs_field); + debug!("vmx_write fail: {:?}", e); + debug!("vmcs_field: {:x}", vmcs_field); Err(SystemError::EVMWRITEFailed) } } @@ -39,7 +40,7 @@ pub fn vmx_vmread(vmcs_field: u32) -> Result { match unsafe { x86::bits64::vmx::vmread(vmcs_field) } { Ok(value) => Ok(value), Err(e) => { - kdebug!("vmx_read fail: {:?}", e); + debug!("vmx_read fail: {:?}", e); Err(SystemError::EVMREADFailed) } } @@ -82,7 +83,7 @@ pub fn vmx_vmlaunch() -> Result<(), SystemError> { // match unsafe { x86::bits64::vmx::vmlaunch() } { // Ok(_) => Ok(()), // Err(e) => { - // kdebug!("vmx_launch fail: {:?}", e); + // debug!("vmx_launch fail: {:?}", e); // Err(SystemError::EVMLAUNCHFailed) // }, // } diff --git a/kernel/src/arch/x86_64/mm/fault.rs b/kernel/src/arch/x86_64/mm/fault.rs index 02f00cbd..00eb4cef 100644 --- a/kernel/src/arch/x86_64/mm/fault.rs +++ b/kernel/src/arch/x86_64/mm/fault.rs @@ -4,6 +4,7 @@ use core::{ }; use alloc::sync::Arc; +use log::error; use x86::{bits64::rflags::RFlags, controlregs::Cr4}; use crate::{ @@ -13,7 +14,6 @@ use crate::{ CurrentIrqArch, MMArch, }, exception::InterruptArch, - kerror, mm::{ fault::{FaultFlags, PageFaultHandler, PageFaultMessage}, ucontext::{AddressSpace, LockedVMA}, @@ -74,27 +74,27 @@ impl X86_64MMArch { if let Some(entry) = mapper.get_entry(address, 0) { if entry.present() { if !entry.flags().has_execute() { - kerror!("kernel tried to execute NX-protected page - exploit attempt?"); + error!("kernel tried to execute NX-protected page - exploit attempt?"); } else if mapper.table().phys().data() & MMArch::ENTRY_FLAG_USER != 0 && unsafe { x86::controlregs::cr4().contains(Cr4::CR4_ENABLE_SMEP) } { - kerror!("unable to execute userspace code (SMEP?)"); + error!("unable to execute userspace code (SMEP?)"); } } } if address.data() < X86_64MMArch::PAGE_SIZE && !regs.is_from_user() { - kerror!( + error!( "BUG: kernel NULL pointer dereference, address: {:#x}", address.data() ); } else { - kerror!( + error!( "BUG: unable to handle page fault for address: {:#x}", address.data() ); } - kerror!( + error!( "#PF: {} {} in {} mode\n", if error_code.contains(X86PfErrorCode::X86_PF_USER) { "user" @@ -114,7 +114,7 @@ impl X86_64MMArch { "kernel" } ); - kerror!( + error!( "#PF: error_code({:#04x}) - {}\n", error_code, if !error_code.contains(X86PfErrorCode::X86_PF_PROT) { diff --git a/kernel/src/arch/x86_64/mm/mod.rs b/kernel/src/arch/x86_64/mm/mod.rs index bfc491ef..6eaf2dd5 100644 --- a/kernel/src/arch/x86_64/mm/mod.rs +++ b/kernel/src/arch/x86_64/mm/mod.rs @@ -6,6 +6,7 @@ pub mod pkru; use alloc::sync::Arc; use alloc::vec::Vec; use hashbrown::HashSet; +use log::{debug, info, warn}; use x86::time::rdtsc; use x86_64::registers::model_specific::EferFlags; @@ -29,7 +30,7 @@ use crate::{ use crate::mm::kernel_mapper::KernelMapper; use crate::mm::page::{PageEntry, PageFlags, PAGE_1G_SHIFT}; use crate::mm::{MemoryManagementArch, PageTableKind, PhysAddr, VirtAddr}; -use crate::{kdebug, kinfo, kwarn}; + use system_error::SystemError; use core::arch::asm; @@ -159,8 +160,8 @@ impl MemoryManagementArch for X86_64MMArch { // 初始化物理内存区域(从multiboot2中获取) Self::init_memory_area_from_multiboot2().expect("init memory area failed"); - kdebug!("bootstrap info: {:?}", unsafe { BOOTSTRAP_MM_INFO }); - kdebug!("phys[0]=virt[0x{:x}]", unsafe { + debug!("bootstrap info: {:?}", unsafe { BOOTSTRAP_MM_INFO }); + debug!("phys[0]=virt[0x{:x}]", unsafe { MMArch::phys_2_virt(PhysAddr::new(0)).unwrap().data() }); @@ -382,18 +383,16 @@ impl X86_64MMArch { info_entry.len as usize, ) .unwrap_or_else(|e| { - kwarn!( + warn!( "Failed to add memory block: base={:#x}, size={:#x}, error={:?}", - info_entry.addr, - info_entry.len, - e + info_entry.addr, info_entry.len, e ); }); areas_count += 1; } } send_to_default_serial8250_port("init_memory_area_from_multiboot2 end\n\0".as_bytes()); - kinfo!("Total memory size: {} MB, total areas from multiboot2: {mb2_count}, valid areas: {areas_count}", total_mem_size / 1024 / 1024); + info!("Total memory size: {} MB, total areas from multiboot2: {mb2_count}, valid areas: {areas_count}", total_mem_size / 1024 / 1024); return Ok(areas_count); } @@ -402,7 +401,7 @@ impl X86_64MMArch { let efer: EferFlags = x86_64::registers::model_specific::Efer::read(); if !efer.contains(EferFlags::NO_EXECUTE_ENABLE) { // NO_EXECUTE_ENABLE是false,那么就设置xd_reserved为true - kdebug!("NO_EXECUTE_ENABLE is false, set XD_RESERVED to true"); + debug!("NO_EXECUTE_ENABLE is false, set XD_RESERVED to true"); XD_RESERVED.store(true, Ordering::Relaxed); } compiler_fence(Ordering::SeqCst); @@ -438,7 +437,7 @@ unsafe fn allocator_init() { .reserve_block(PhysAddr::new(0), phy_offset.data()) .expect("Failed to reserve block"); let mut bump_allocator = BumpAllocator::::new(phy_offset.data()); - kdebug!( + debug!( "BumpAllocator created, offset={:?}", bump_allocator.offset() ); @@ -459,7 +458,7 @@ unsafe fn allocator_init() { ) .expect("Failed to create page mapper"); new_page_table = mapper.table().phys(); - kdebug!("PageMapper created"); + debug!("PageMapper created"); // 取消最开始时候,在head.S中指定的映射(暂时不刷新TLB) { @@ -471,12 +470,12 @@ unsafe fn allocator_init() { .expect("Failed to empty page table entry"); } } - kdebug!("Successfully emptied page table"); + debug!("Successfully emptied page table"); let total_num = mem_block_manager().total_initial_memory_regions(); for i in 0..total_num { let area = mem_block_manager().get_initial_memory_region(i).unwrap(); - // kdebug!("area: base={:?}, size={:#x}, end={:?}", area.base, area.size, area.base + area.size); + // debug!("area: base={:?}, size={:#x}, end={:?}", area.base, area.size, area.base + area.size); for i in 0..((area.size + MMArch::PAGE_SIZE - 1) / MMArch::PAGE_SIZE) { let paddr = area.base.add(i * MMArch::PAGE_SIZE); let vaddr = unsafe { MMArch::phys_2_virt(paddr) }.unwrap(); @@ -494,7 +493,7 @@ unsafe fn allocator_init() { unsafe { INITIAL_CR3_VALUE = new_page_table; } - kdebug!( + debug!( "After mapping all physical memory, DragonOS used: {} KB", bump_allocator.offset() / 1024 ); @@ -503,7 +502,7 @@ unsafe fn allocator_init() { let buddy_allocator = unsafe { BuddyAllocator::::new(bump_allocator).unwrap() }; // 设置全局的页帧分配器 unsafe { set_inner_allocator(buddy_allocator) }; - kinfo!("Successfully initialized buddy allocator"); + info!("Successfully initialized buddy allocator"); // 关闭显示输出 scm_disable_put_to_window(); @@ -511,7 +510,7 @@ unsafe fn allocator_init() { { let mut binding = INNER_ALLOCATOR.lock(); let mut allocator_guard = binding.as_mut().unwrap(); - kdebug!("To enable new page table."); + debug!("To enable new page table."); compiler_fence(Ordering::SeqCst); let mapper = crate::mm::page::PageMapper::::new( PageTableKind::Kernel, @@ -521,9 +520,9 @@ unsafe fn allocator_init() { compiler_fence(Ordering::SeqCst); mapper.make_current(); compiler_fence(Ordering::SeqCst); - kdebug!("New page table enabled"); + debug!("New page table enabled"); } - kdebug!("Successfully enabled new page table"); + debug!("Successfully enabled new page table"); } #[no_mangle] @@ -536,7 +535,7 @@ pub fn test_buddy() { const TOTAL_SIZE: usize = 200 * 1024 * 1024; for i in 0..10 { - kdebug!("Test buddy, round: {i}"); + debug!("Test buddy, round: {i}"); // 存放申请的内存块 let mut v: Vec<(PhysAddr, PageFrameCount)> = Vec::with_capacity(60 * 1024); // 存放已经申请的内存块的地址(用于检查重复) @@ -601,14 +600,14 @@ pub fn test_buddy() { } } - kdebug!( + debug!( "Allocated {} MB memory, release: {} MB, no release: {} bytes", allocated / 1024 / 1024, free_count / 1024 / 1024, (allocated - free_count) ); - kdebug!("Now, to release buddy memory"); + debug!("Now, to release buddy memory"); // 释放所有的内存 for (paddr, allocated_frame_count) in v { unsafe { LockedFrameAllocator.free(paddr, allocated_frame_count) }; @@ -616,7 +615,7 @@ pub fn test_buddy() { free_count += allocated_frame_count.data() * MMArch::PAGE_SIZE; } - kdebug!("release done!, allocated: {allocated}, free_count: {free_count}"); + debug!("release done!, allocated: {allocated}, free_count: {free_count}"); } } diff --git a/kernel/src/arch/x86_64/pci/pci.rs b/kernel/src/arch/x86_64/pci/pci.rs index ce47e1ff..dd08deec 100644 --- a/kernel/src/arch/x86_64/pci/pci.rs +++ b/kernel/src/arch/x86_64/pci/pci.rs @@ -6,10 +6,11 @@ use crate::driver::pci::pci::{ }; use crate::include::bindings::bindings::{io_in32, io_out32}; use crate::init::initcall::INITCALL_SUBSYS; -use crate::kerror; + use crate::mm::PhysAddr; use acpi::mcfg::Mcfg; +use log::error; use system_error::SystemError; use unified_init::macros::unified_init; @@ -51,7 +52,7 @@ impl TraitPciArch for X86_64PciArch { #[unified_init(INITCALL_SUBSYS)] fn x86_64_pci_init() -> Result<(), SystemError> { if let Err(e) = discover_ecam_root() { - kerror!("x86_64_pci_init(): discover_ecam_root error: {:?}", e); + error!("x86_64_pci_init(): discover_ecam_root error: {:?}", e); } pci_init(); diff --git a/kernel/src/arch/x86_64/process/idle.rs b/kernel/src/arch/x86_64/process/idle.rs index 2ce5f509..79dfb8a5 100644 --- a/kernel/src/arch/x86_64/process/idle.rs +++ b/kernel/src/arch/x86_64/process/idle.rs @@ -1,9 +1,10 @@ use core::hint::spin_loop; +use log::error; + use crate::{ arch::CurrentIrqArch, exception::InterruptArch, - kBUG, process::{ProcessFlags, ProcessManager}, sched::{SchedMode, __schedule}, }; @@ -21,7 +22,7 @@ impl ProcessManager { x86::halt(); } } else { - kBUG!("Idle process should not be scheduled with IRQs disabled."); + error!("Idle process should not be scheduled with IRQs disabled."); spin_loop(); } } diff --git a/kernel/src/arch/x86_64/process/mod.rs b/kernel/src/arch/x86_64/process/mod.rs index 49685c22..c4382cdc 100644 --- a/kernel/src/arch/x86_64/process/mod.rs +++ b/kernel/src/arch/x86_64/process/mod.rs @@ -8,13 +8,13 @@ use core::{ use alloc::sync::{Arc, Weak}; use kdepends::memoffset::offset_of; +use log::{error, warn}; use system_error::SystemError; use x86::{controlregs::Cr4, segmentation::SegmentSelector}; use crate::{ arch::process::table::TSSManager, exception::InterruptArch, - kerror, kwarn, libs::spinlock::SpinLockGuard, mm::VirtAddr, process::{ @@ -167,7 +167,7 @@ impl ArchPCBInfo { // 清空浮点寄存器 pub fn clear_fp_state(&mut self) { if unlikely(self.fp_state.is_none()) { - kwarn!("fp_state is none"); + warn!("fp_state is none"); return; } @@ -275,7 +275,7 @@ impl ProcessControlBlock { // 从内核栈的最低地址处取出pcb的地址 let p = stack_base.data() as *const *const ProcessControlBlock; if unlikely((unsafe { *p }).is_null()) { - kerror!("p={:p}", p); + error!("p={:p}", p); panic!("current_pcb is null"); } unsafe { @@ -406,7 +406,7 @@ impl ProcessManager { ); PROCESS_SWITCH_RESULT.as_mut().unwrap().get_mut().prev_pcb = Some(prev); PROCESS_SWITCH_RESULT.as_mut().unwrap().get_mut().next_pcb = Some(next); - // kdebug!("switch tss ok"); + // debug!("switch tss ok"); compiler_fence(Ordering::SeqCst); // 正式切换上下文 switch_to_inner(prev_arch, next_arch); @@ -515,7 +515,7 @@ pub unsafe fn arch_switch_to_user(trap_frame: TrapFrame) -> ! { let trap_frame_vaddr = VirtAddr::new( current_pcb.kernel_stack().stack_max_address().data() - core::mem::size_of::(), ); - // kdebug!("trap_frame_vaddr: {:?}", trap_frame_vaddr); + // debug!("trap_frame_vaddr: {:?}", trap_frame_vaddr); assert!( (x86::current::registers::rsp() as usize) < trap_frame_vaddr.data(), diff --git a/kernel/src/arch/x86_64/process/syscall.rs b/kernel/src/arch/x86_64/process/syscall.rs index 84448893..a356a453 100644 --- a/kernel/src/arch/x86_64/process/syscall.rs +++ b/kernel/src/arch/x86_64/process/syscall.rs @@ -26,7 +26,7 @@ impl Syscall { // 关中断,防止在设置地址空间的时候,发生中断,然后进调度器,出现错误。 let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() }; let pcb = ProcessManager::current_pcb(); - // crate::kdebug!( + // crate::debug!( // "pid: {:?} do_execve: path: {:?}, argv: {:?}, envp: {:?}\n", // pcb.pid(), // path, @@ -55,20 +55,20 @@ impl Syscall { AddressSpace::is_current(&address_space), "Failed to set address space" ); - // kdebug!("Switch to new address space"); + // debug!("Switch to new address space"); // 切换到新的用户地址空间 unsafe { address_space.read().user_mapper.utable.make_current() }; drop(old_address_space); drop(irq_guard); - // kdebug!("to load binary file"); + // debug!("to load binary file"); let mut param = ExecParam::new(path.as_str(), address_space.clone(), ExecParamFlags::EXEC)?; // 加载可执行文件 let load_result = load_binary_file(&mut param)?; - // kdebug!("load binary file done"); - // kdebug!("argv: {:?}, envp: {:?}", argv, envp); + // debug!("load binary file done"); + // debug!("argv: {:?}, envp: {:?}", argv, envp); param.init_info_mut().args = argv; param.init_info_mut().envs = envp; @@ -94,7 +94,7 @@ impl Syscall { }; address_space.write().user_stack = Some(ustack_message); - // kdebug!("write proc_init_info to user stack done"); + // debug!("write proc_init_info to user stack done"); // (兼容旧版libc)把argv的指针写到寄存器内 // TODO: 改写旧版libc,不再需要这个兼容 @@ -116,9 +116,9 @@ impl Syscall { drop(param); - // kdebug!("regs: {:?}\n", regs); + // debug!("regs: {:?}\n", regs); - // crate::kdebug!( + // crate::debug!( // "tmp_rs_execve: done, load_result.entry_point()={:?}", // load_result.entry_point() // ); diff --git a/kernel/src/arch/x86_64/smp/mod.rs b/kernel/src/arch/x86_64/smp/mod.rs index 45046486..1068c8b7 100644 --- a/kernel/src/arch/x86_64/smp/mod.rs +++ b/kernel/src/arch/x86_64/smp/mod.rs @@ -5,12 +5,12 @@ use core::{ }; use kdepends::memoffset::offset_of; +use log::debug; use system_error::SystemError; use crate::{ arch::{mm::LowAddressRemapping, process::table::TSSManager, MMArch}, exception::InterruptArch, - kdebug, libs::{cpumask::CpuMask, rwlock::RwLock}, mm::{percpu::PerCpu, MemoryManagementArch, PhysAddr, VirtAddr, IDLE_PROCESS_ADDRESS_SPACE}, process::ProcessManager, @@ -77,7 +77,7 @@ unsafe extern "sysv64" fn smp_init_switch_stack(st: &ApStartStackInfo) -> ! { unsafe extern "C" fn smp_ap_start_stage1() -> ! { let id = smp_get_processor_id(); - kdebug!("smp_ap_start_stage1: id: {}\n", id.data()); + debug!("smp_ap_start_stage1: id: {}\n", id.data()); let current_idle = ProcessManager::idle_pcb()[smp_get_processor_id().data() as usize].clone(); let tss = TSSManager::current_tss(); @@ -187,7 +187,7 @@ fn print_cpus(s: &str, mask: &CpuMask) { v.push(cpu.data()); } - kdebug!("{s}: cpus: {v:?}\n"); + debug!("{s}: cpus: {v:?}\n"); } pub struct X86_64SMPArch; diff --git a/kernel/src/arch/x86_64/syscall/mod.rs b/kernel/src/arch/x86_64/syscall/mod.rs index f5b8eb15..4ed274c2 100644 --- a/kernel/src/arch/x86_64/syscall/mod.rs +++ b/kernel/src/arch/x86_64/syscall/mod.rs @@ -11,6 +11,7 @@ use crate::{ process::ProcessManager, syscall::{Syscall, SYS_SCHED}, }; +use log::debug; use system_error::SystemError; use super::{ @@ -52,7 +53,7 @@ macro_rules! syscall_return { if $show { let pid = ProcessManager::current_pcb().pid(); - crate::kdebug!("syscall return:pid={:?},ret= {:?}\n", pid, ret as isize); + debug!("syscall return:pid={:?},ret= {:?}\n", pid, ret as isize); } unsafe { @@ -94,7 +95,7 @@ pub extern "sysv64" fn syscall_handler(frame: &mut TrapFrame) { // }; if show { - crate::kdebug!("syscall: pid: {:?}, num={:?}\n", pid, syscall_num); + debug!("syscall: pid: {:?}, num={:?}\n", pid, syscall_num); } // Arch specific syscall @@ -126,7 +127,7 @@ pub extern "sysv64" fn syscall_handler(frame: &mut TrapFrame) { /// 系统调用初始化 pub fn arch_syscall_init() -> Result<(), SystemError> { - // kinfo!("arch_syscall_init\n"); + // info!("arch_syscall_init\n"); unsafe { set_system_trap_gate(0x80, 0, VirtAddr::new(syscall_int as usize)) }; // 系统调用门 unsafe { init_syscall_64() }; return Ok(()); diff --git a/kernel/src/driver/acpi/mod.rs b/kernel/src/driver/acpi/mod.rs index 2d2f644c..8525f5f1 100644 --- a/kernel/src/driver/acpi/mod.rs +++ b/kernel/src/driver/acpi/mod.rs @@ -2,11 +2,11 @@ use core::{fmt::Debug, hint::spin_loop, ptr::NonNull}; use acpi::{AcpiHandler, AcpiTables, PlatformInfo}; use alloc::{string::ToString, sync::Arc}; +use log::{error, info}; use crate::{ arch::MMArch, driver::base::firmware::sys_firmware_kset, - kinfo, libs::align::{page_align_down, page_align_up, AlignedBox}, mm::{ mmio_buddy::{mmio_pool, MMIOSpaceGuard}, @@ -57,7 +57,7 @@ impl AcpiManager { /// /// https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/acpi/bus.c#1390 pub fn init(&self, rsdp_vaddr1: u64, rsdp_vaddr2: u64) -> Result<(), SystemError> { - kinfo!("Initializing Acpi Manager..."); + info!("Initializing Acpi Manager..."); // 初始化`/sys/firmware/acpi`的kset let kset = KSet::new("acpi".to_string()); @@ -67,7 +67,7 @@ impl AcpiManager { } self.map_tables(rsdp_vaddr1, rsdp_vaddr2)?; self.bus_init()?; - kinfo!("Acpi Manager initialized."); + info!("Acpi Manager initialized."); return Ok(()); } @@ -95,7 +95,7 @@ impl AcpiManager { } // 如果rsdpv1和rsdpv2都无法获取到acpi_table,说明有问题,打印报错信息后进入死循环 Err(e2) => { - kerror!("acpi_init(): failed to parse acpi tables, error: (rsdpv1: {:?}) or (rsdpv2: {:?})", e1, e2); + error!("acpi_init(): failed to parse acpi tables, error: (rsdpv1: {:?}) or (rsdpv2: {:?})", e1, e2); Self::drop_rsdp_tmp_box(); loop { spin_loop(); @@ -161,7 +161,7 @@ impl AcpiManager { pub fn platform_info(&self) -> Option> { let r = self.tables()?.platform_info(); if let Err(ref e) = r { - kerror!( + error!( "AcpiManager::platform_info(): failed to get platform info, error: {:?}", e ); diff --git a/kernel/src/driver/acpi/sysfs.rs b/kernel/src/driver/acpi/sysfs.rs index 73e8278f..34bc04b2 100644 --- a/kernel/src/driver/acpi/sysfs.rs +++ b/kernel/src/driver/acpi/sysfs.rs @@ -18,6 +18,7 @@ use alloc::{ sync::Arc, vec::Vec, }; +use log::{debug, error, warn}; use system_error::SystemError; use super::{acpi_kset, AcpiManager}; @@ -109,7 +110,7 @@ impl AcpiManager { let tables = self.tables().unwrap(); let headers = tables.headers(); for header in headers { - kdebug!("ACPI header: {:?}", header); + debug!("ACPI header: {:?}", header); let attr = AttrAcpiTable::new(&header)?; acpi_table_attr_list().write().push(attr); self.acpi_table_data_init(&header)?; @@ -172,7 +173,7 @@ impl AttrAcpiTable { // 将当前实例的序号加1 r.instance += 1; if r.instance > ACPI_MAX_TABLE_INSTANCES as isize { - kwarn!("too many table instances. name: {}", r.name); + warn!("too many table instances. name: {}", r.name); return Err(SystemError::ERANGE); } @@ -289,10 +290,9 @@ impl BinAttribute for AttrAcpiTable { ($name: ident, $tables: expr) => { define_struct!($name); let table = $tables.find_entire_table::<$name>().map_err(|e| { - kwarn!( + warn!( "AttrAcpiTable::read(): failed to find table. name: {}, error: {:?}", - self.name, - e + self.name, e ); SystemError::ENODEV })?; @@ -500,7 +500,7 @@ impl BinAttribute for AttrAcpiTable { } _ => { - kerror!("AttrAcpiTable::read(): unknown table. name: {}", self.name); + error!("AttrAcpiTable::read(): unknown table. name: {}", self.name); return Err(SystemError::ENODEV); } }; diff --git a/kernel/src/driver/base/block/block_device.rs b/kernel/src/driver/base/block/block_device.rs index 37fd975a..729157a6 100644 --- a/kernel/src/driver/base/block/block_device.rs +++ b/kernel/src/driver/base/block/block_device.rs @@ -1,23 +1,21 @@ /// 引入Module -use crate::{ - driver::{ - base::{ - device::{ - device_number::{DeviceNumber, Major}, - Device, DeviceError, IdTable, BLOCKDEVS, - }, - map::{ - DeviceStruct, DEV_MAJOR_DYN_END, DEV_MAJOR_DYN_EXT_END, DEV_MAJOR_DYN_EXT_START, - DEV_MAJOR_HASH_SIZE, DEV_MAJOR_MAX, - }, +use crate::driver::{ + base::{ + device::{ + device_number::{DeviceNumber, Major}, + Device, DeviceError, IdTable, BLOCKDEVS, + }, + map::{ + DeviceStruct, DEV_MAJOR_DYN_END, DEV_MAJOR_DYN_EXT_END, DEV_MAJOR_DYN_EXT_START, + DEV_MAJOR_HASH_SIZE, DEV_MAJOR_MAX, }, - block::cache::{cached_block_device::BlockCache, BlockCacheError, BLOCK_SIZE}, }, - kerror, + block::cache::{cached_block_device::BlockCache, BlockCacheError, BLOCK_SIZE}, }; use alloc::{sync::Arc, vec::Vec}; use core::any::Any; +use log::error; use system_error::SystemError; use super::disk_info::Partition; @@ -475,7 +473,7 @@ impl BlockDeviceOps { let mut major = device_number.major(); let baseminor = device_number.minor(); if major >= DEV_MAJOR_MAX { - kerror!( + error!( "DEV {} major requested {:?} is greater than the maximum {}\n", name, major, @@ -483,7 +481,7 @@ impl BlockDeviceOps { ); } if minorct > DeviceNumber::MINOR_MASK + 1 - baseminor { - kerror!("DEV {} minor range requested ({}-{}) is out of range of maximum range ({}-{}) for a single major\n", + error!("DEV {} minor range requested ({}-{}) is out of range of maximum range ({}-{}) for a single major\n", name, baseminor, baseminor + minorct - 1, 0, DeviceNumber::MINOR_MASK); } let blockdev = DeviceStruct::new(DeviceNumber::new(major, baseminor), minorct, name); @@ -549,7 +547,7 @@ impl BlockDeviceOps { #[allow(dead_code)] pub fn bdev_add(_bdev: Arc, id_table: IdTable) -> Result<(), DeviceError> { if id_table.device_number().data() == 0 { - kerror!("Device number can't be 0!\n"); + error!("Device number can't be 0!\n"); } todo!("bdev_add") // return device_manager().add_device(bdev.id_table(), bdev.device()); diff --git a/kernel/src/driver/base/char/mod.rs b/kernel/src/driver/base/char/mod.rs index cf9483c3..090abef1 100644 --- a/kernel/src/driver/base/char/mod.rs +++ b/kernel/src/driver/base/char/mod.rs @@ -1,6 +1,6 @@ use alloc::sync::Arc; +use log::error; -use crate::kerror; use system_error::SystemError; use super::{ @@ -129,7 +129,7 @@ impl CharDevOps { let mut major = device_number.major(); let baseminor = device_number.minor(); if major >= DEV_MAJOR_MAX { - kerror!( + error!( "DEV {} major requested {:?} is greater than the maximum {}\n", name, major, @@ -137,7 +137,7 @@ impl CharDevOps { ); } if minorct > DeviceNumber::MINOR_MASK + 1 - baseminor { - kerror!("DEV {} minor range requested ({}-{}) is out of range of maximum range ({}-{}) for a single major\n", + error!("DEV {} minor range requested ({}-{}) is out of range of maximum range ({}-{}) for a single major\n", name, baseminor, baseminor + minorct - 1, 0, DeviceNumber::MINOR_MASK); } let chardev = DeviceStruct::new(DeviceNumber::new(major, baseminor), minorct, name); @@ -207,7 +207,7 @@ impl CharDevOps { range: usize, ) -> Result<(), SystemError> { if id_table.device_number().data() == 0 { - kerror!("Device number can't be 0!\n"); + error!("Device number can't be 0!\n"); } device_manager().add_device(cdev.clone())?; kobj_map( diff --git a/kernel/src/driver/base/device/bus.rs b/kernel/src/driver/base/device/bus.rs index a94b1fae..e56e7f1e 100644 --- a/kernel/src/driver/base/device/bus.rs +++ b/kernel/src/driver/base/device/bus.rs @@ -25,6 +25,7 @@ use alloc::{ use core::{ffi::CStr, fmt::Debug, intrinsics::unlikely}; use hashbrown::HashMap; use intertrait::cast::CastArc; +use log::{debug, error, info}; use system_error::SystemError; /// `/sys/bus`的kset @@ -296,7 +297,7 @@ impl BusManager { .bus() .and_then(|bus| bus.upgrade()) .ok_or(SystemError::EINVAL)?; - kdebug!("bus '{}' add driver '{}'", bus.name(), driver.name()); + debug!("bus '{}' add driver '{}'", bus.name(), driver.name()); driver.set_kobj_type(Some(&BusDriverKType)); let kobj = driver.clone() as Arc; @@ -314,7 +315,7 @@ impl BusManager { driver_manager() .add_groups(driver, bus.drv_groups()) .map_err(|e| { - kerror!( + error!( "BusManager::add_driver: driver '{:?}' add_groups failed, err: '{:?}", driver.name(), e @@ -326,7 +327,7 @@ impl BusManager { if !driver.suppress_bind_attrs() { self.add_bind_files(driver) .map_err(|e| { - kerror!( + error!( "BusManager::add_driver: driver '{:?}' add_bind_files failed, err: '{:?}", driver.name(), e @@ -580,7 +581,7 @@ pub fn bus_add_device(dev: &Arc) -> Result<(), SystemError> { /// /// 参考: https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/bus.c?fi=bus_probe_device#478 pub fn bus_probe_device(dev: &Arc) { - kinfo!("bus_probe_device: dev: {:?}", dev.name()); + info!("bus_probe_device: dev: {:?}", dev.name()); bus_manager().probe_device(dev); } @@ -746,7 +747,7 @@ impl Attribute for DriverAttrUnbind { fn store(&self, kobj: Arc, buf: &[u8]) -> Result { let driver = kobj.cast::().map_err(|kobj| { - kerror!( + error!( "Intertrait casting not implemented for kobj: {}", kobj.name() ); @@ -795,7 +796,7 @@ impl Attribute for DriverAttrBind { */ fn store(&self, kobj: Arc, buf: &[u8]) -> Result { let driver = kobj.cast::().map_err(|kobj| { - kerror!( + error!( "Intertrait casting not implemented for kobj: {}", kobj.name() ); diff --git a/kernel/src/driver/base/device/dd.rs b/kernel/src/driver/base/device/dd.rs index 7adb840b..92505e78 100644 --- a/kernel/src/driver/base/device/dd.rs +++ b/kernel/src/driver/base/device/dd.rs @@ -2,6 +2,7 @@ use core::intrinsics::unlikely; use alloc::{string::ToString, sync::Arc}; use intertrait::cast::CastArc; +use log::{debug, error, warn}; use crate::{ driver::base::kobject::KObject, @@ -59,20 +60,20 @@ impl DeviceManager { ) -> Result { if unlikely(allow_async) { // todo!("do_device_attach: allow_async") - kwarn!("do_device_attach: allow_async is true, but currently not supported"); + warn!("do_device_attach: allow_async is true, but currently not supported"); } if dev.is_dead() { return Ok(false); } - kwarn!("do_device_attach: dev: '{}'", dev.name()); + warn!("do_device_attach: dev: '{}'", dev.name()); let mut do_async = false; let mut r = Ok(false); if dev.driver().is_some() { if self.device_is_bound(dev) { - kdebug!( + debug!( "do_device_attach: device '{}' is already bound.", dev.name() ); @@ -86,7 +87,7 @@ impl DeviceManager { return Ok(false); } } else { - kdebug!("do_device_attach: device '{}' is not bound.", dev.name()); + debug!("do_device_attach: device '{}' is not bound.", dev.name()); let bus = dev .bus() .and_then(|bus| bus.upgrade()) @@ -116,7 +117,7 @@ impl DeviceManager { // try them. do_async = true; - kdebug!( + debug!( "do_device_attach: try scheduling asynchronous probe for device: {}", dev.name() ); @@ -153,7 +154,7 @@ impl DeviceManager { if let Err(e) = r { // 如果不是ENOSYS,则总线出错 if e != SystemError::ENOSYS { - kdebug!( + debug!( "do_device_attach_driver: bus.match_device() failed, dev: '{}', err: {:?}", data.dev.name(), e @@ -215,7 +216,7 @@ impl DeviceManager { } if let Err(e) = r.as_ref() { - kerror!( + error!( "device_bind_driver: driver_sysfs_add failed, dev: '{}', err: {:?}", dev.name(), e @@ -401,7 +402,7 @@ impl DriverManager { device.set_driver(Some(Arc::downgrade(driver))); self.add_to_sysfs(device).map_err(|e| { - kerror!( + error!( "really_probe: add_to_sysfs failed, dev: '{}', err: {:?}", device.name(), e @@ -412,7 +413,7 @@ impl DriverManager { })?; self.call_driver_probe(device, driver).map_err(|e| { - kerror!( + error!( "really_probe: call_driver_probe failed, dev: '{}', err: {:?}", device.name(), e @@ -427,7 +428,7 @@ impl DriverManager { device_manager() .add_groups(device, driver.dev_groups()) .map_err(|e| { - kerror!( + error!( "really_probe: add_groups failed, dev: '{}', err: {:?}", device.name(), e @@ -443,7 +444,7 @@ impl DriverManager { device_manager() .create_file(device, &DeviceAttrStateSynced) .map_err(|e| { - kerror!( + error!( "really_probe: create_file failed, dev: '{}', err: {:?}", device.name(), e @@ -515,7 +516,7 @@ impl DriverManager { .ok_or(SystemError::EINVAL)?; let r = bus.probe(device); if r == Err(SystemError::ENOSYS) { - kerror!( + error!( "call_driver_probe: bus.probe() failed, dev: '{}', err: {:?}", device.name(), r @@ -530,7 +531,7 @@ impl DriverManager { let err = r.unwrap_err(); match err { SystemError::ENODEV | SystemError::ENXIO => { - kdebug!( + debug!( "driver'{}': probe of {} rejects match {:?}", driver.name(), device.name(), @@ -539,7 +540,7 @@ impl DriverManager { } _ => { - kwarn!( + warn!( "driver'{}': probe of {} failed with error {:?}", driver.name(), device.name(), @@ -555,7 +556,7 @@ impl DriverManager { /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/dd.c#393 fn driver_bound(&self, device: &Arc) { if self.driver_is_bound(device) { - kwarn!("driver_bound: device '{}' is already bound.", device.name()); + warn!("driver_bound: device '{}' is already bound.", device.name()); return; } @@ -600,7 +601,7 @@ impl Attribute for DeviceAttrStateSynced { fn show(&self, kobj: Arc, buf: &mut [u8]) -> Result { let dev = kobj.cast::().map_err(|kobj| { - kerror!( + error!( "Intertrait casting not implemented for kobj: {}", kobj.name() ); @@ -635,7 +636,7 @@ impl Attribute for DeviceAttrCoredump { fn store(&self, kobj: Arc, buf: &[u8]) -> Result { let dev = kobj.cast::().map_err(|kobj| { - kerror!( + error!( "Intertrait casting not implemented for kobj: {}", kobj.name() ); diff --git a/kernel/src/driver/base/device/driver.rs b/kernel/src/driver/base/device/driver.rs index 0df615e1..256db75c 100644 --- a/kernel/src/driver/base/device/driver.rs +++ b/kernel/src/driver/base/device/driver.rs @@ -15,6 +15,7 @@ use alloc::{ vec::Vec, }; use core::fmt::Debug; +use log::error; use system_error::SystemError; /// @brief: Driver error @@ -193,7 +194,7 @@ impl DriverManager { /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/driver.c#222 pub fn register(&self, driver: Arc) -> Result<(), SystemError> { let bus = driver.bus().and_then(|bus| bus.upgrade()).ok_or_else(|| { - kerror!( + error!( "DriverManager::register() failed: driver.bus() is None. Driver: '{:?}'", driver.name() ); @@ -203,7 +204,7 @@ impl DriverManager { let drv_name = driver.name(); let other = bus.find_driver_by_name(&drv_name); if other.is_some() { - kerror!( + error!( "DriverManager::register() failed: driver '{}' already registered", drv_name ); diff --git a/kernel/src/driver/base/device/init.rs b/kernel/src/driver/base/device/init.rs index 7138d644..62f5e800 100644 --- a/kernel/src/driver/base/device/init.rs +++ b/kernel/src/driver/base/device/init.rs @@ -1,16 +1,13 @@ use alloc::{string::ToString, sync::Arc}; +use log::info; -use crate::{ - driver::base::{ - device::{ - set_sys_dev_block_kset, set_sys_dev_char_kset, set_sys_devices_virtual_kset, - sys_dev_kset, sys_devices_kset, DeviceManager, DEVICES_KSET_INSTANCE, DEVICE_MANAGER, - DEV_KSET_INSTANCE, - }, - kobject::KObject, - kset::KSet, +use crate::driver::base::{ + device::{ + set_sys_dev_block_kset, set_sys_dev_char_kset, set_sys_devices_virtual_kset, sys_dev_kset, + sys_devices_kset, DeviceManager, DEVICES_KSET_INSTANCE, DEVICE_MANAGER, DEV_KSET_INSTANCE, }, - kinfo, + kobject::KObject, + kset::KSet, }; use system_error::SystemError; @@ -54,7 +51,7 @@ pub fn devices_init() -> Result<(), SystemError> { // 创建 `/sys/dev/block` 目录 { - // kdebug!("create /sys/dev/block"); + // debug!("create /sys/dev/block"); let dev_kset = sys_dev_kset(); let dev_block_kset = KSet::new("block".to_string()); let parent = dev_kset.clone() as Arc; @@ -69,7 +66,7 @@ pub fn devices_init() -> Result<(), SystemError> { // 创建 `/sys/dev/char` 目录 { - // kdebug!("create /sys/dev/char"); + // debug!("create /sys/dev/char"); let dev_kset = sys_dev_kset(); let dev_char_kset = KSet::new("char".to_string()); let parent = dev_kset.clone() as Arc; @@ -82,7 +79,7 @@ pub fn devices_init() -> Result<(), SystemError> { unsafe { set_sys_dev_char_kset(dev_char_kset) }; } - kinfo!("devices init success"); + info!("devices init success"); return Ok(()); } diff --git a/kernel/src/driver/base/device/mod.rs b/kernel/src/driver/base/device/mod.rs index 3208936a..6149257a 100644 --- a/kernel/src/driver/base/device/mod.rs +++ b/kernel/src/driver/base/device/mod.rs @@ -3,6 +3,7 @@ use alloc::{ sync::{Arc, Weak}, }; use intertrait::cast::CastArc; +use log::{error, warn}; use crate::{ driver::{ @@ -139,7 +140,7 @@ pub trait Device: KObject { /// 设备释放时的回调函数 fn release(&self) { let name = self.name(); - kwarn!( + warn!( "device {} does not have a release() function, it is broken and must be fixed.", name ); @@ -482,7 +483,7 @@ impl DeviceManager { let actual_parent = self.get_device_parent(&device, current_parent)?; if let Some(actual_parent) = actual_parent { - // kdebug!( + // debug!( // "device '{}' parent is '{}', strong_count: {}", // device.name().to_string(), // actual_parent.name(), @@ -492,7 +493,7 @@ impl DeviceManager { } KObjectManager::add_kobj(device.clone() as Arc, None).map_err(|e| { - kerror!("add device '{:?}' failed: {:?}", device.name(), e); + error!("add device '{:?}' failed: {:?}", device.name(), e); e })?; @@ -552,10 +553,10 @@ impl DeviceManager { device: &Arc, current_parent: Option>, ) -> Result>, SystemError> { - // kdebug!("get_device_parent() device:{:?}", device.name()); + // debug!("get_device_parent() device:{:?}", device.name()); if device.class().is_some() { let parent_kobj: Arc; - // kdebug!("current_parent:{:?}", current_parent); + // debug!("current_parent:{:?}", current_parent); if let Some(cp) = current_parent { if cp.class().is_some() { return Ok(Some(cp.clone() as Arc)); @@ -756,7 +757,7 @@ impl DeviceManager { attr.mode().contains(ModeType::S_IRUGO) && (!attr.support().contains(SysFSOpsSupport::ATTR_SHOW)), ) { - kwarn!( + warn!( "Attribute '{}': read permission without 'show'", attr.name() ); @@ -765,7 +766,7 @@ impl DeviceManager { attr.mode().contains(ModeType::S_IWUGO) && (!attr.support().contains(SysFSOpsSupport::ATTR_STORE)), ) { - kwarn!( + warn!( "Attribute '{}': write permission without 'store'", attr.name() ); @@ -807,7 +808,7 @@ impl DeviceManager { /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/core.c?fi=device_links_force_bind#1226 pub fn device_links_force_bind(&self, _dev: &Arc) { - kwarn!("device_links_force_bind not implemented"); + warn!("device_links_force_bind not implemented"); } /// 把device对象的一些结构进行默认初始化 @@ -872,7 +873,7 @@ impl Attribute for DeviceAttrDev { fn show(&self, kobj: Arc, buf: &mut [u8]) -> Result { let dev = kobj.cast::().map_err(|kobj| { - kerror!( + error!( "Intertrait casting not implemented for kobj: {}", kobj.name() ); diff --git a/kernel/src/driver/base/kobject.rs b/kernel/src/driver/base/kobject.rs index a8659c44..73e3c7ee 100644 --- a/kernel/src/driver/base/kobject.rs +++ b/kernel/src/driver/base/kobject.rs @@ -6,13 +6,13 @@ use alloc::{ }; use driver_base_macros::get_weak_or_clear; use intertrait::CastFromSync; +use log::{debug, error}; use crate::{ filesystem::{ kernfs::KernFSInode, sysfs::{sysfs_instance, Attribute, AttributeGroup, SysFSOps, SysFSOpsSupport}, }, - kerror, libs::{ casting::DowncastArc, rwlock::{RwLock, RwLockReadGuard, RwLockWriteGuard}, @@ -213,7 +213,7 @@ impl KObjectManager { } kobj.set_parent(None); if e == SystemError::EEXIST { - kerror!("KObjectManager::add_kobj() failed with error: {e:?}, kobj:{kobj:?}"); + error!("KObjectManager::add_kobj() failed with error: {e:?}, kobj:{kobj:?}"); } return Err(e); @@ -269,7 +269,7 @@ pub struct DynamicKObjKType; impl KObjType for DynamicKObjKType { fn release(&self, kobj: Arc) { - kdebug!("DynamicKObjKType::release() kobj:{:?}", kobj.name()); + debug!("DynamicKObjKType::release() kobj:{:?}", kobj.name()); } fn sysfs_ops(&self) -> Option<&dyn SysFSOps> { diff --git a/kernel/src/driver/base/platform/subsys.rs b/kernel/src/driver/base/platform/subsys.rs index 26eb3d88..57e5c258 100644 --- a/kernel/src/driver/base/platform/subsys.rs +++ b/kernel/src/driver/base/platform/subsys.rs @@ -3,6 +3,7 @@ use alloc::{ sync::{Arc, Weak}, }; use intertrait::cast::CastArc; +use log::error; use super::{platform_device::PlatformDevice, platform_driver::PlatformDriver}; use crate::{ @@ -58,12 +59,12 @@ impl Bus for PlatformBus { fn probe(&self, device: &Arc) -> Result<(), SystemError> { let drv = device.driver().ok_or(SystemError::EINVAL)?; let pdrv = drv.cast::().map_err(|_|{ - kerror!("PlatformBus::probe() failed: device.driver() is not a PlatformDriver. Device: '{:?}'", device.name()); + error!("PlatformBus::probe() failed: device.driver() is not a PlatformDriver. Device: '{:?}'", device.name()); SystemError::EINVAL })?; let pdev = device.clone().cast::().map_err(|_| { - kerror!( + error!( "PlatformBus::probe() failed: device is not a PlatformDevice. Device: '{:?}'", device.name() ); diff --git a/kernel/src/driver/block/cache/cached_block_device.rs b/kernel/src/driver/block/cache/cached_block_device.rs index 29443042..d7f19497 100644 --- a/kernel/src/driver/block/cache/cached_block_device.rs +++ b/kernel/src/driver/block/cache/cached_block_device.rs @@ -1,5 +1,6 @@ use alloc::{boxed::Box, vec::Vec}; use hashbrown::HashMap; +use log::debug; use crate::{driver::base::block::block_device::BlockId, libs::rwlock::RwLock}; @@ -41,7 +42,7 @@ impl BlockCache { CSPACE = Some(LockedCacheSpace::new(CacheSpace::new())); CMAPPER = Some(LockedCacheMapper::new(CacheMapper::new())); } - kdebug!("BlockCache Initialized!"); + debug!("BlockCache Initialized!"); } /// # 函数的功能 /// 使用blockcache进行对块设备进行连续块的读操作 diff --git a/kernel/src/driver/block/virtio_blk.rs b/kernel/src/driver/block/virtio_blk.rs index 75fe897e..2475e9f9 100644 --- a/kernel/src/driver/block/virtio_blk.rs +++ b/kernel/src/driver/block/virtio_blk.rs @@ -5,6 +5,7 @@ use alloc::{ sync::{Arc, Weak}, vec::Vec, }; +use log::{debug, error}; use system_error::SystemError; use unified_init::macros::unified_init; use virtio_drivers::device::blk::VirtIOBlk; @@ -63,7 +64,7 @@ pub fn virtio_blk_0() -> Option> { pub fn virtio_blk(transport: VirtIOTransport, dev_id: Arc) { let device = VirtIOBlkDevice::new(transport, dev_id); if let Some(device) = device { - kdebug!("VirtIOBlkDevice '{:?}' created", device.dev_id); + debug!("VirtIOBlkDevice '{:?}' created", device.dev_id); virtio_device_manager() .device_add(device.clone() as Arc) .expect("Add virtio blk failed"); @@ -89,7 +90,7 @@ impl VirtIOBlkDevice { let irq = transport.irq().map(|irq| IrqNumber::new(irq.data())); let device_inner = VirtIOBlk::::new(transport); if let Err(e) = device_inner { - kerror!("VirtIOBlkDevice '{dev_id:?}' create failed: {:?}", e); + error!("VirtIOBlkDevice '{dev_id:?}' create failed: {:?}", e); return None; } @@ -134,10 +135,9 @@ impl BlockDevice for VirtIOBlkDevice { .device_inner .read_blocks(lba_id_start, &mut buf[..count * LBA_SIZE]) .map_err(|e| { - kerror!( + error!( "VirtIOBlkDevice '{:?}' read_at_sync failed: {:?}", - self.dev_id, - e + self.dev_id, e ); SystemError::EIO })?; @@ -416,7 +416,7 @@ impl VirtIODriver for VirtIOBlkDriver { .arc_any() .downcast::() .map_err(|_| { - kerror!( + error!( "VirtIOBlkDriver::probe() failed: device is not a VirtIO block device. Device: '{:?}'", device.name() ); diff --git a/kernel/src/driver/clocksource/acpi_pm.rs b/kernel/src/driver/clocksource/acpi_pm.rs index d372ec4a..09382a9a 100644 --- a/kernel/src/driver/clocksource/acpi_pm.rs +++ b/kernel/src/driver/clocksource/acpi_pm.rs @@ -15,6 +15,7 @@ use acpi::fadt::Fadt; use alloc::sync::{Arc, Weak}; use core::intrinsics::unlikely; use core::sync::atomic::{AtomicU32, Ordering}; +use log::info; use system_error::SystemError; // 参考:https://code.dragonos.org.cn/xref/linux-6.6.21/drivers/clocksource/acpi_pm.c @@ -170,6 +171,8 @@ const PMTMR_EXPECTED_RATE: u64 = #[cfg(not(target_arch = "x86_64"))] #[allow(dead_code)] fn verify_pmtmr_rate() -> bool { + use log::info; + let mut count: u32 = 0; mach_prepare_counter(); @@ -179,7 +182,7 @@ fn verify_pmtmr_rate() -> bool { let delta = (value2 - value1) & ACPI_PM_MASK; if (delta < (PMTMR_EXPECTED_RATE * 19) / 20) || (delta > (PMTMR_EXPECTED_RATE * 21) / 20) { - kinfo!( + info!( "PM Timer running at invalid rate: {}", 100 * delta / PMTMR_EXPECTED_RATE ); @@ -209,7 +212,7 @@ fn find_acpi_pm_clock() -> Result<(), SystemError> { PMTMR_IO_PORT.store(pmtmr_addr as u32, Ordering::SeqCst); - kinfo!( + info!( "apic_pmtmr I/O port: {}", PMTMR_IO_PORT.load(Ordering::SeqCst) ); @@ -257,14 +260,14 @@ pub fn init_acpi_pm_clocksource() -> Result<(), SystemError> { if (value2 < value1) && (value2 < 0xfff) { break; } - kinfo!("PM Timer had inconsistens results: {} {}", value1, value2); + info!("PM Timer had inconsistens results: {} {}", value1, value2); PMTMR_IO_PORT.store(0, Ordering::SeqCst); return Err(SystemError::EINVAL); } if i == ACPI_PM_READ_CHECKS { - kinfo!("PM Timer failed consistency check: {}", value1); + info!("PM Timer failed consistency check: {}", value1); PMTMR_IO_PORT.store(0, Ordering::SeqCst); @@ -289,11 +292,11 @@ pub fn init_acpi_pm_clocksource() -> Result<(), SystemError> { let acpi_pmtmr = clocksource_acpi_pm() as Arc; match acpi_pmtmr.register(100, PMTMR_TICKS_PER_SEC as u32) { Ok(_) => { - kinfo!("ACPI PM Timer registered as clocksource sccessfully"); + info!("ACPI PM Timer registered as clocksource sccessfully"); return Ok(()); } Err(_) => { - kinfo!("ACPI PM Timer init registered failed"); + info!("ACPI PM Timer init registered failed"); return Err(SystemError::ENOSYS); } }; diff --git a/kernel/src/driver/clocksource/timer_riscv.rs b/kernel/src/driver/clocksource/timer_riscv.rs index e5481f4e..48cd31e4 100644 --- a/kernel/src/driver/clocksource/timer_riscv.rs +++ b/kernel/src/driver/clocksource/timer_riscv.rs @@ -49,7 +49,7 @@ impl RiscVSbiTimer { fn handle_irq(trap_frame: &mut TrapFrame) -> Result<(), SystemError> { // 更新下一次中断时间 - // kdebug!( + // debug!( // "riscv_sbi_timer: handle_irq: cpu_id: {}, time: {}", // smp_get_processor_id().data(), // CurrentTimeArch::get_cycles() as u64 diff --git a/kernel/src/driver/disk/ahci/ahcidisk.rs b/kernel/src/driver/disk/ahci/ahcidisk.rs index 4aaaa799..a57b2bb2 100644 --- a/kernel/src/driver/disk/ahci/ahcidisk.rs +++ b/kernel/src/driver/disk/ahci/ahcidisk.rs @@ -13,16 +13,14 @@ use crate::driver::disk::ahci::HBA_PxIS_TFES; use crate::filesystem::kernfs::KernFSInode; use crate::filesystem::mbr::MbrDiskPartionTable; +use crate::driver::disk::ahci::hba::{ + FisRegH2D, FisType, HbaCmdHeader, ATA_CMD_READ_DMA_EXT, ATA_CMD_WRITE_DMA_EXT, ATA_DEV_BUSY, + ATA_DEV_DRQ, +}; use crate::libs::rwlock::{RwLockReadGuard, RwLockWriteGuard}; use crate::libs::spinlock::SpinLock; use crate::mm::{phys_2_virt, verify_area, VirtAddr}; -use crate::{ - driver::disk::ahci::hba::{ - FisRegH2D, FisType, HbaCmdHeader, ATA_CMD_READ_DMA_EXT, ATA_CMD_WRITE_DMA_EXT, - ATA_DEV_BUSY, ATA_DEV_DRQ, - }, - kerror, -}; +use log::error; use system_error::SystemError; use alloc::sync::Weak; @@ -70,7 +68,7 @@ impl AhciDisk { compiler_fence(Ordering::SeqCst); let check_length = ((count - 1) >> 4) + 1; // prdt length if count * 512 > buf.len() || check_length > 8_usize { - kerror!("ahci read: e2big"); + error!("ahci read: e2big"); // 不可能的操作 return Err(SystemError::E2BIG); } else if count == 0 { @@ -130,7 +128,7 @@ impl AhciDisk { // 清空整个table的旧数据 write_bytes(cmdtbl, 0, 1); } - // kdebug!("cmdheader.prdtl={}", volatile_read!(cmdheader.prdtl)); + // debug!("cmdheader.prdtl={}", volatile_read!(cmdheader.prdtl)); // 8K bytes (16 sectors) per PRDT for i in 0..((volatile_read!(cmdheader.prdtl) - 1) as usize) { @@ -181,19 +179,19 @@ impl AhciDisk { } if spin_count == SPIN_LIMIT { - kerror!("Port is hung"); + error!("Port is hung"); return Err(SystemError::EIO); } volatile_set_bit!(port.ci, 1 << slot, true); // Issue command - // kdebug!("To wait ahci read complete."); + // debug!("To wait ahci read complete."); // 等待操作完成 loop { if (volatile_read!(port.ci) & (1 << slot)) == 0 { break; } if (volatile_read!(port.is) & HBA_PxIS_TFES) > 0 { - kerror!("Read disk error"); + error!("Read disk error"); return Err(SystemError::EIO); } } @@ -336,7 +334,7 @@ impl AhciDisk { break; } if (volatile_read!(port.is) & HBA_PxIS_TFES) > 0 { - kerror!("Write disk error"); + error!("Write disk error"); return Err(SystemError::EIO); } } diff --git a/kernel/src/driver/disk/ahci/mod.rs b/kernel/src/driver/disk/ahci/mod.rs index 778fc9a4..514b7b0f 100644 --- a/kernel/src/driver/disk/ahci/mod.rs +++ b/kernel/src/driver/disk/ahci/mod.rs @@ -10,21 +10,19 @@ use crate::driver::pci::pci::{ get_pci_device_structure_mut, PciDeviceStructure, PCI_DEVICE_LINKEDLIST, }; use crate::filesystem::devfs::devfs_register; -use crate::kerror; + +use crate::driver::disk::ahci::{ + ahcidisk::LockedAhciDisk, + hba::HbaMem, + hba::{HbaPort, HbaPortType}, +}; use crate::libs::rwlock::RwLockWriteGuard; use crate::libs::spinlock::{SpinLock, SpinLockGuard}; use crate::mm::virt_2_phys; -use crate::{ - driver::disk::ahci::{ - ahcidisk::LockedAhciDisk, - hba::HbaMem, - hba::{HbaPort, HbaPortType}, - }, - kdebug, -}; use ahci_inode::LockedAhciInode; use alloc::{boxed::Box, collections::LinkedList, format, string::String, sync::Arc, vec::Vec}; use core::sync::atomic::compiler_fence; +use log::{debug, error}; use system_error::SystemError; // 仅module内可见 全局数据区 hbr_port, disks @@ -90,13 +88,13 @@ pub fn ahci_init() -> Result<(), SystemError> { let tp = hba_mem_port.check_type(); match tp { HbaPortType::None => { - kdebug!(" Find a None type Disk."); + debug!(" Find a None type Disk."); } HbaPortType::Unknown(err) => { - kdebug!(" Find a Unknown({:?}) type Disk.", err); + debug!(" Find a Unknown({:?}) type Disk.", err); } _ => { - kdebug!(" Find a {:?} type Disk.", tp); + debug!(" Find a {:?} type Disk.", tp); // 计算地址 let fb = virt_2_phys(ahci_port_base_vaddr + (32 << 10) + (j << 8)); @@ -122,7 +120,7 @@ pub fn ahci_init() -> Result<(), SystemError> { )?); id += 1; // ID 从0开始 - kdebug!("start register ahci device"); + debug!("start register ahci device"); // 挂载到devfs上面去 let ret = devfs_register( @@ -130,7 +128,7 @@ pub fn ahci_init() -> Result<(), SystemError> { LockedAhciInode::new(disks_list.last().unwrap().clone()), ); if let Err(err) = ret { - kerror!( + error!( "Ahci_{} ctrl = {}, port = {} failed to register, error code = {:?}", id, hba_mem_index as u8, diff --git a/kernel/src/driver/firmware/efi/fdt.rs b/kernel/src/driver/firmware/efi/fdt.rs index 52ad8bb7..4276dfce 100644 --- a/kernel/src/driver/firmware/efi/fdt.rs +++ b/kernel/src/driver/firmware/efi/fdt.rs @@ -3,6 +3,7 @@ use core::fmt::Debug; use fdt::Fdt; +use log::error; use system_error::SystemError; use crate::init::boot_params; @@ -117,7 +118,7 @@ impl EFIManager { ) } .map_err(|e| { - kerror!("failed to parse fdt, err={:?}", e); + error!("failed to parse fdt, err={:?}", e); SystemError::EINVAL })?; @@ -145,7 +146,7 @@ impl EFIManager { self.do_get_fdt_prop(prop_type, &prop, &mut ret) .unwrap_or_else(|e| { - kerror!("Failed to get fdt prop: {prop_type:?}, error: {e:?}"); + error!("Failed to get fdt prop: {prop_type:?}, error: {e:?}"); }) } } diff --git a/kernel/src/driver/firmware/efi/init.rs b/kernel/src/driver/firmware/efi/init.rs index c425a887..0f25a002 100644 --- a/kernel/src/driver/firmware/efi/init.rs +++ b/kernel/src/driver/firmware/efi/init.rs @@ -1,5 +1,6 @@ use core::{hint::spin_loop, intrinsics::unlikely, mem::size_of}; +use log::{error, info, warn}; use system_error::SystemError; use uefi_raw::table::boot::{MemoryAttribute, MemoryType}; @@ -21,17 +22,17 @@ use super::efi_manager; #[allow(dead_code)] #[inline(never)] pub fn efi_init() { - kinfo!("Initializing efi..."); + info!("Initializing efi..."); let data_from_fdt = efi_manager() .get_fdt_params() .expect("Failed to get fdt params"); if data_from_fdt.systable.is_none() { - kerror!("Failed to get systable from fdt"); + error!("Failed to get systable from fdt"); return; } - // kdebug!("to map memory table"); + // debug!("to map memory table"); // 映射mmap table if efi_manager().memmap_init_early(&data_from_fdt).is_err() { @@ -39,23 +40,23 @@ pub fn efi_init() { // 那么 UEFI memory map 就是我们拥有的关于内存的唯一描述, // 所以如果我们无法访问它,那么继续进行下去就没有什么意义了 - kerror!("Failed to initialize early memory map"); + error!("Failed to initialize early memory map"); loop { spin_loop(); } } - // kdebug!("NNNN"); - // kwarn!("BBBB, e:{:?}", SystemError::EINVAL); + // debug!("NNNN"); + // warn!("BBBB, e:{:?}", SystemError::EINVAL); let desc_version = efi_manager().desc_version(); if unlikely(desc_version != 1) { - kwarn!("Unexpected EFI memory map version: {}", desc_version); + warn!("Unexpected EFI memory map version: {}", desc_version); } let r = uefi_init(PhysAddr::new(data_from_fdt.systable.unwrap() as usize)); if let Err(e) = r { - kerror!("Failed to initialize UEFI: {:?}", e); + error!("Failed to initialize UEFI: {:?}", e); efi_manager().efi_memmap_unmap(); return; } @@ -97,7 +98,7 @@ pub fn efi_init() { // todo: Initialize screen info - kinfo!("UEFI init done!"); + info!("UEFI init done!"); } fn efi_find_mirror() { @@ -117,7 +118,7 @@ fn efi_find_mirror() { } if mirror_size > 0 { - kinfo!( + info!( "Memory: {}M/{}M mirrored memory", mirror_size >> 20, total_size >> 20 @@ -133,7 +134,7 @@ fn uefi_init(system_table: PhysAddr) -> Result<(), SystemError> { let err_unmap_systable = |st_vaddr: VirtAddr| { EarlyIoRemap::unmap(st_vaddr) .map_err(|e| { - kerror!("Failed to unmap system table: {e:?}"); + error!("Failed to unmap system table: {e:?}"); }) .ok(); }; @@ -143,7 +144,7 @@ fn uefi_init(system_table: PhysAddr) -> Result<(), SystemError> { let st_size = size_of::(); let st_vaddr = EarlyIoRemap::map_not_aligned(system_table, st_size, true).map_err(|e| { - kwarn!("Unable to map EFI system table, e:{e:?}"); + warn!("Unable to map EFI system table, e:{e:?}"); e })?; @@ -195,7 +196,7 @@ fn uefi_init(system_table: PhysAddr) -> Result<(), SystemError> { true, ) .map_err(|e| { - kwarn!("Unable to map EFI configuration table, e:{e:?}"); + warn!("Unable to map EFI configuration table, e:{e:?}"); err_unmap_systable(st_vaddr); e })?; @@ -265,11 +266,11 @@ fn reserve_memory_regions() { let phys_start = page_align_down(md.phys_start as usize); let size = (page_count << (MMArch::PAGE_SHIFT as u64)) as usize; - // kdebug!("Reserve memory region: {:#x}-{:#x}({:#x}), is_memory: {}, is_usable_memory:{}, type: {:?}, att: {:?}", phys_start, phys_start + size, page_count, md.is_memory(), md.is_usable_memory(), md.ty, md.att); + // debug!("Reserve memory region: {:#x}-{:#x}({:#x}), is_memory: {}, is_usable_memory:{}, type: {:?}, att: {:?}", phys_start, phys_start + size, page_count, md.is_memory(), md.is_usable_memory(), md.ty, md.att); if md.is_memory() { open_firmware_fdt_driver().early_init_dt_add_memory(phys_start as u64, size as u64); if !md.is_usable_memory() { - // kdebug!( + // debug!( // "Marking non-usable memory as nomap: {:#x}-{:#x}", // phys_start, // phys_start + size diff --git a/kernel/src/driver/firmware/efi/memmap.rs b/kernel/src/driver/firmware/efi/memmap.rs index 1bfea15f..c213d853 100644 --- a/kernel/src/driver/firmware/efi/memmap.rs +++ b/kernel/src/driver/firmware/efi/memmap.rs @@ -1,5 +1,6 @@ use core::{intrinsics::unlikely, mem::size_of}; +use log::error; use system_error::SystemError; use crate::{ @@ -110,7 +111,7 @@ impl EFIManager { let offset = paddr.data() - page_align_down(paddr.data()); let map_size = data.mmap_size.unwrap() as usize + offset; - // kdebug!("do_efi_memmap_init: map_size={map_size:#x}"); + // debug!("do_efi_memmap_init: map_size={map_size:#x}"); // 映射内存 let mut vaddr = EarlyIoRemap::map( @@ -130,7 +131,7 @@ impl EFIManager { } if inner_guard.mmap.vaddr.is_none() { - kerror!("Cannot map the EFI memory map!"); + error!("Cannot map the EFI memory map!"); return Err(SystemError::ENOMEM); } diff --git a/kernel/src/driver/firmware/efi/mod.rs b/kernel/src/driver/firmware/efi/mod.rs index a07d4df2..4d0f9e3b 100644 --- a/kernel/src/driver/firmware/efi/mod.rs +++ b/kernel/src/driver/firmware/efi/mod.rs @@ -1,3 +1,4 @@ +use log::{error, warn}; use system_error::SystemError; use crate::{ @@ -90,15 +91,14 @@ impl EFIManager { min_major: u16, ) -> Result<(), SystemError> { if header.signature != uefi_raw::table::system::SystemTable::SIGNATURE { - kerror!("System table signature mismatch!"); + error!("System table signature mismatch!"); return Err(SystemError::EINVAL); } if header.revision.major() < min_major { - kwarn!( + warn!( "System table version: {:?}, expected {}.00 or greater!", - header.revision, - min_major + header.revision, min_major ); } diff --git a/kernel/src/driver/firmware/efi/tables.rs b/kernel/src/driver/firmware/efi/tables.rs index bab60500..a6e9c344 100644 --- a/kernel/src/driver/firmware/efi/tables.rs +++ b/kernel/src/driver/firmware/efi/tables.rs @@ -1,6 +1,7 @@ use core::{ffi::CStr, mem::size_of}; use hashbrown::Equivalent; +use log::{debug, error, info, warn}; use system_error::SystemError; use uefi_raw::table::{ boot::{MemoryAttribute, MemoryType}, @@ -66,16 +67,16 @@ impl EFIManager { } EarlyIoRemap::unmap(fw_ptr).map_err(|e|{ - kerror!("report systable header: failed to unmap systable header, fw_ptr: {fw_ptr:?}, err: {e:?}"); + error!("report systable header: failed to unmap systable header, fw_ptr: {fw_ptr:?}, err: {e:?}"); e }).ok(); } else { - kwarn!("report systable header: failed to map systable header, err: {fw_ptr:?}"); + warn!("report systable header: failed to map systable header, err: {fw_ptr:?}"); } let s = CStr::from_bytes_with_nul(&tmp_buf) .unwrap_or_else(|_| CStr::from_bytes_with_nul(b"Unknown\0").unwrap()); - kinfo!("EFI version: {:?}, vendor: {:?}", header.revision, s); + info!("EFI version: {:?}, vendor: {:?}", header.revision, s); } /// 解析EFI config table @@ -86,7 +87,7 @@ impl EFIManager { if let Some(r) = parser.match_table(table) { // 有匹配结果 if let Err(e) = r { - kwarn!( + warn!( "Failed to parse cfg table: '{}', err: {e:?}", parser.table.name() ); @@ -97,7 +98,7 @@ impl EFIManager { } if !flag { - kwarn!("Cannot find parser for guid: {:?}", table.vendor_guid); + warn!("Cannot find parser for guid: {:?}", table.vendor_guid); } } @@ -107,7 +108,7 @@ impl EFIManager { while !prev_paddr.is_null() { let vaddr = EarlyIoRemap::map_not_aligned(prev_paddr, MMArch::PAGE_SIZE, true) .map_err(|e| { - kerror!( + error!( "Failed to map UEFI memreserve table, paddr: {prev_paddr:?}, err: {e:?}" ); @@ -129,7 +130,7 @@ impl EFIManager { + size_of::() * psize, ) .map_err(|e| { - kerror!("Failed to reserve block, paddr: {prev_paddr:?}, err: {e:?}"); + error!("Failed to reserve block, paddr: {prev_paddr:?}, err: {e:?}"); EarlyIoRemap::unmap(vaddr).unwrap(); e })?; @@ -146,7 +147,7 @@ impl EFIManager { mem_block_manager() .reserve_block(PhysAddr::new(entry.base), entry.size) .map_err(|e| { - kerror!("Failed to reserve block, paddr: {prev_paddr:?}, err: {e:?}"); + error!("Failed to reserve block, paddr: {prev_paddr:?}, err: {e:?}"); EarlyIoRemap::unmap(vaddr).unwrap(); e })?; @@ -344,7 +345,7 @@ impl MatchTable for MatchTableMemReserve { ) -> Result<(), SystemError> { efi_manager().inner.write_irqsave().memreserve_table_paddr = Some(PhysAddr::new(table_raw.vendor_table as usize)); - kdebug!( + debug!( "memreserve_table_paddr: {:#x}", table_raw.vendor_table as usize ); @@ -374,7 +375,7 @@ impl MatchTable for MatchTableEsrt { ) -> Result<(), SystemError> { efi_manager().inner.write_irqsave().esrt_table_paddr = Some(PhysAddr::new(table_raw.vendor_table as usize)); - kdebug!("esrt_table_paddr: {:#x}", table_raw.vendor_table as usize); + debug!("esrt_table_paddr: {:#x}", table_raw.vendor_table as usize); return Ok(()); } } diff --git a/kernel/src/driver/input/ps2_mouse/ps_mouse_device.rs b/kernel/src/driver/input/ps2_mouse/ps_mouse_device.rs index e99f683d..d78c70b1 100644 --- a/kernel/src/driver/input/ps2_mouse/ps_mouse_device.rs +++ b/kernel/src/driver/input/ps2_mouse/ps_mouse_device.rs @@ -6,6 +6,7 @@ use alloc::{ vec::Vec, }; use kdepends::ringbuffer::{AllocRingBuffer, RingBuffer}; +use log::{debug, error}; use system_error::SystemError; use crate::{ @@ -229,7 +230,7 @@ impl Ps2MouseDevice { self.send_command_to_ps2mouse(PsMouseCommand::EnablePacketStreaming) .map_err(|e| { - kerror!("ps2 mouse init error: {:?}", e); + error!("ps2 mouse init error: {:?}", e); e })?; self.read_data_port().ok(); @@ -313,7 +314,7 @@ impl Ps2MouseDevice { guard.current_state.y = self.get_y_movement(packet, flags); } - // kdebug!( + // debug!( // "Ps2MouseDevice packet : flags:{}, x:{}, y:{}\n", // guard.current_state.flags.bits, // guard.current_state.x, @@ -664,7 +665,7 @@ impl IndexNode for Ps2MouseDevice { impl Ps2Device for Ps2MouseDevice {} pub fn rs_ps2_mouse_device_init(parent: Arc) -> Result<(), SystemError> { - kdebug!("ps2_mouse_device initializing..."); + debug!("ps2_mouse_device initializing..."); let psmouse = Arc::new(Ps2MouseDevice::new()); device_manager().device_default_initialize(&(psmouse.clone() as Arc)); @@ -672,7 +673,7 @@ pub fn rs_ps2_mouse_device_init(parent: Arc) -> Result<(), SystemEr serio_device_manager().register_port(psmouse.clone() as Arc)?; devfs_register(&psmouse.name(), psmouse.clone()).map_err(|e| { - kerror!( + error!( "register psmouse device '{}' to devfs failed: {:?}", psmouse.name(), e diff --git a/kernel/src/driver/input/ps2_mouse/ps_mouse_driver.rs b/kernel/src/driver/input/ps2_mouse/ps_mouse_driver.rs index a9b76c33..baedcd4e 100644 --- a/kernel/src/driver/input/ps2_mouse/ps_mouse_driver.rs +++ b/kernel/src/driver/input/ps2_mouse/ps_mouse_driver.rs @@ -3,6 +3,7 @@ use alloc::{ sync::{Arc, Weak}, vec::Vec, }; +use log::debug; use system_error::SystemError; use unified_init::macros::unified_init; @@ -276,10 +277,10 @@ impl SerioDriver for Ps2MouseDriver { #[unified_init(INITCALL_DEVICE)] fn ps2_mouse_driver_init() -> Result<(), SystemError> { - kdebug!("Ps2_mouse_drive initializing..."); + debug!("Ps2_mouse_drive initializing..."); let driver = Ps2MouseDriver::new(); serio_driver_manager().register(driver.clone())?; unsafe { PS2_MOUSE_DRIVER = Some(driver) }; - kdebug!("Ps2_mouse_drive initialized!"); + debug!("Ps2_mouse_drive initialized!"); return Ok(()); } diff --git a/kernel/src/driver/input/serio/i8042/mod.rs b/kernel/src/driver/input/serio/i8042/mod.rs index 31a2b1de..8c612d74 100644 --- a/kernel/src/driver/input/serio/i8042/mod.rs +++ b/kernel/src/driver/input/serio/i8042/mod.rs @@ -1,4 +1,5 @@ use alloc::sync::Arc; +use log::debug; use system_error::SystemError; use unified_init::macros::unified_init; @@ -33,7 +34,7 @@ pub fn i8042_platform_device() -> Arc { // TODO: https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/input/serio/i8042.c#1612 #[unified_init(INITCALL_DEVICE)] pub fn i8042_init() -> Result<(), SystemError> { - kdebug!("i8042 initializing..."); + debug!("i8042 initializing..."); let i8042_device = Arc::new(I8042PlatformDevice::new()); device_manager().device_default_initialize(&(i8042_device.clone() as Arc)); platform_device_manager().device_add(i8042_device.clone() as Arc)?; diff --git a/kernel/src/driver/input/serio/subsys.rs b/kernel/src/driver/input/serio/subsys.rs index d3291a85..afdd9349 100644 --- a/kernel/src/driver/input/serio/subsys.rs +++ b/kernel/src/driver/input/serio/subsys.rs @@ -3,6 +3,7 @@ use alloc::{ sync::{Arc, Weak}, }; use intertrait::cast::CastArc; +use log::error; use system_error::SystemError; use crate::{ @@ -59,7 +60,7 @@ impl Bus for SerioBus { fn probe(&self, device: &Arc) -> Result<(), SystemError> { let drv = device.driver().ok_or(SystemError::EINVAL)?; let pdrv = drv.cast::().map_err(|_| { - kerror!( + error!( "SerioBus::probe() failed: device.driver() is not a SerioDriver. Device: '{:?}'", device.name() ); @@ -67,7 +68,7 @@ impl Bus for SerioBus { })?; let pdev = device.clone().cast::().map_err(|_| { - kerror!( + error!( "SerioBus::probe() failed: device is not a SerioDevice. Device: '{:?}'", device.name() ); diff --git a/kernel/src/driver/irqchip/riscv_intc.rs b/kernel/src/driver/irqchip/riscv_intc.rs index 2e83dbb3..e14d25ad 100644 --- a/kernel/src/driver/irqchip/riscv_intc.rs +++ b/kernel/src/driver/irqchip/riscv_intc.rs @@ -1,4 +1,5 @@ use alloc::{string::ToString, sync::Arc}; +use log::error; use system_error::SystemError; use crate::{ @@ -155,7 +156,7 @@ pub unsafe fn riscv_intc_init() -> Result<(), SystemError> { RiscvIntcChip::IRQ_SIZE, ) .ok_or_else(|| { - kerror!("Failed to create riscv-intc domain"); + error!("Failed to create riscv-intc domain"); SystemError::ENXIO })?; @@ -197,7 +198,7 @@ pub fn riscv_intc_assicate_irq(hwirq: HardwareIrqNumber) -> Option { irq_domain_manager() .domain_associate( riscv_intc_domain().as_ref().or_else(|| { - kerror!("riscv_intc_domain is None"); + error!("riscv_intc_domain is None"); None })?, virq, diff --git a/kernel/src/driver/irqchip/riscv_sifive_plic.rs b/kernel/src/driver/irqchip/riscv_sifive_plic.rs index 83e26916..05bc52f0 100644 --- a/kernel/src/driver/irqchip/riscv_sifive_plic.rs +++ b/kernel/src/driver/irqchip/riscv_sifive_plic.rs @@ -25,6 +25,7 @@ use alloc::{ }; use bitmap::AllocBitmap; use fdt::node::FdtNode; +use log::{debug, warn}; use system_error::SystemError; use crate::{ @@ -187,7 +188,7 @@ impl PlicHandler { fn plic_irq_toggle(cpumask: &CpuMask, irq_data: &Arc, enable: bool) { cpumask.iter_cpu().for_each(|cpu| { - kdebug!("plic: irq_toggle: cpu: {cpu:?}"); + debug!("plic: irq_toggle: cpu: {cpu:?}"); let handler = unsafe { plic_handlers().force_get(cpu) }; handler.toggle(irq_data.hardware_irq(), enable); }); @@ -240,7 +241,7 @@ impl IrqChip for PlicIrqChip { "SiFive PLIC" } fn irq_enable(&self, irq_data: &Arc) -> Result<(), SystemError> { - // kwarn!("plic: irq_enable"); + // warn!("plic: irq_enable"); let common_data = irq_data.common_data(); let inner_guard = common_data.inner(); let mask = inner_guard.effective_affinity(); @@ -252,7 +253,7 @@ impl IrqChip for PlicIrqChip { } fn irq_unmask(&self, irq_data: &Arc) -> Result<(), SystemError> { - // kwarn!("plic: irq_unmask"); + // warn!("plic: irq_unmask"); let chip_data = irq_data .chip_info_read_irqsave() @@ -300,7 +301,7 @@ impl IrqChip for PlicIrqChip { } fn irq_disable(&self, irq_data: &Arc) { - kdebug!("plic: irq_disable"); + debug!("plic: irq_disable"); let common_data = irq_data.common_data(); let inner_guard = common_data.inner(); let mask = inner_guard.effective_affinity(); @@ -321,7 +322,7 @@ impl IrqChip for PlicIrqChip { handler.toggle(irq_data.hardware_irq(), false); } else { - // kdebug!("plic: irq_eoi: hwirq: {:?}", irq_data.hardware_irq()); + // debug!("plic: irq_eoi: hwirq: {:?}", irq_data.hardware_irq()); unsafe { write_volatile( (handler.inner().hart_base + PlicIrqChip::CONTEXT_CLAIM).data() as *mut u32, @@ -423,7 +424,7 @@ pub fn riscv_sifive_plic_init() -> Result<(), SystemError> { }); for node in all_plics { if let Err(e) = do_riscv_sifive_plic_init(&node) { - kwarn!("Failed to init SiFive PLIC: node: {node:?} {e:?}"); + warn!("Failed to init SiFive PLIC: node: {node:?} {e:?}"); } } @@ -457,7 +458,7 @@ fn do_riscv_sifive_plic_init(fdt_node: &FdtNode) -> Result<(), SystemError> { .ok_or(SystemError::EINVAL)? .as_usize() .ok_or(SystemError::EINVAL)?; - kdebug!( + debug!( "plic: node: {}, irq_num: {irq_num}, paddr: {paddr:?}, size: {size}", fdt_node.name ); @@ -465,7 +466,7 @@ fn do_riscv_sifive_plic_init(fdt_node: &FdtNode) -> Result<(), SystemError> { .interrupts_extended() .ok_or(SystemError::EINVAL)? .count(); - kdebug!("plic: nr_contexts: {nr_contexts}"); + debug!("plic: nr_contexts: {nr_contexts}"); let irq_domain = irq_domain_manager() .create_and_add_linear( @@ -474,7 +475,7 @@ fn do_riscv_sifive_plic_init(fdt_node: &FdtNode) -> Result<(), SystemError> { (irq_num + 1) as u32, ) .ok_or(SystemError::EINVAL)?; - // kdebug!("plic: irq_domain: {irq_domain:?}"); + // debug!("plic: irq_domain: {irq_domain:?}"); let priv_data = PlicChipData::new( Arc::downgrade(&irq_domain), @@ -506,13 +507,13 @@ fn do_riscv_sifive_plic_init(fdt_node: &FdtNode) -> Result<(), SystemError> { let cpu = ProcessorId::new(i as u32); let handler = unsafe { plic_handlers().force_get(cpu) }; if handler.present() { - kwarn!("plic: handler {i} already present."); + warn!("plic: handler {i} already present."); handler.set_threshold(PlicIrqChip::PLIC_ENABLE_THRESHOLD); loop_done_setup(handler); continue; } - kdebug!("plic: setup lmask {cpu:?}."); + debug!("plic: setup lmask {cpu:?}."); priv_data.lmask().set(cpu, true); let mut handler_inner = handler.inner(); handler_inner.hart_base = @@ -560,7 +561,7 @@ fn associate_irq_with_plic_domain( let irq = irq as u32; let virq = IrqNumber::new(irq); let hwirq = HardwareIrqNumber::new(irq); - kdebug!("plic: associate irq: {irq}, virq: {virq:?}, hwirq: {hwirq:?}"); + debug!("plic: associate irq: {irq}, virq: {virq:?}, hwirq: {hwirq:?}"); irq_domain_manager() .domain_associate(irq_domain, virq, hwirq) .ok(); @@ -583,7 +584,7 @@ impl IrqDomainOps for PlicIrqDomainOps { hwirq: HardwareIrqNumber, virq: IrqNumber, ) -> Result<(), SystemError> { - // kdebug!("plic: map: virq: {virq:?}, hwirq: {hwirq:?}"); + // debug!("plic: map: virq: {virq:?}, hwirq: {hwirq:?}"); let chip_data = irq_domain.host_data().ok_or(SystemError::EINVAL)?; let plic_chip_data = chip_data @@ -613,7 +614,7 @@ impl IrqDomainOps for PlicIrqDomainOps { _irq_data: &Arc, _reserve: bool, ) -> Result<(), SystemError> { - kwarn!("plic: activate"); + warn!("plic: activate"); loop {} } @@ -622,7 +623,7 @@ impl IrqDomainOps for PlicIrqDomainOps { /// 处理PLIC中断 pub(super) fn do_plic_irq(trap_frame: &mut TrapFrame) { - // kdebug!("plic: do_plic_irq"); + // debug!("plic: do_plic_irq"); let handler = plic_handlers().get(); let priv_data = handler.priv_data(); @@ -648,11 +649,11 @@ pub(super) fn do_plic_irq(trap_frame: &mut TrapFrame) { if claim == 0 { break; } - kdebug!("plic: claim: {claim:?}"); + debug!("plic: claim: {claim:?}"); let hwirq = HardwareIrqNumber::new(claim); if let Err(e) = GenericIrqHandler::handle_domain_irq(domain.clone(), hwirq, trap_frame) { - kwarn!("plic: can't find mapping for hwirq {hwirq:?}, {e:?}"); + warn!("plic: can't find mapping for hwirq {hwirq:?}, {e:?}"); } } } diff --git a/kernel/src/driver/net/e1000e/e1000e.rs b/kernel/src/driver/net/e1000e/e1000e.rs index c2a27806..475823bd 100644 --- a/kernel/src/driver/net/e1000e/e1000e.rs +++ b/kernel/src/driver/net/e1000e/e1000e.rs @@ -9,6 +9,7 @@ use core::mem::size_of; use core::ptr::NonNull; use core::slice::{from_raw_parts, from_raw_parts_mut}; use core::sync::atomic::{compiler_fence, Ordering}; +use log::{debug, info}; use super::e1000e_driver::e1000e_driver_init; use crate::driver::base::device::DeviceId; @@ -23,8 +24,6 @@ use crate::exception::IrqNumber; use crate::libs::volatile::{ReadOnly, Volatile, WriteOnly}; -use crate::{kdebug, kinfo}; - const PAGE_SIZE: usize = 4096; const NETWORK_CLASS: u8 = 0x2; const ETHERNET_SUBCLASS: u8 = 0x0; @@ -284,7 +283,7 @@ impl E1000EDevice { volwrite!(general_regs, ctrl, ctrl | E1000E_CTRL_SLU); } let status = unsafe { volread!(general_regs, status) }; - kdebug!("Status: {status:#X}"); + debug!("Status: {status:#X}"); // 读取设备的mac地址 // Read mac address @@ -442,7 +441,7 @@ impl E1000EDevice { buffer.set_length(desc.len as usize); rdt = index; unsafe { volwrite!(self.receive_regs, rdt0, rdt as u32) }; - // kdebug!("e1000e: receive packet"); + // debug!("e1000e: receive packet"); return Some(buffer); } @@ -559,7 +558,7 @@ impl Drop for E1000EDevice { fn drop(&mut self) { // 释放已分配的所有dma页 // free all dma pages we have allocated - kdebug!("droping..."); + debug!("droping..."); let recv_ring_length = PAGE_SIZE / size_of::(); let trans_ring_length = PAGE_SIZE / size_of::(); unsafe { @@ -590,10 +589,10 @@ impl Drop for E1000EDevice { pub fn e1000e_init() { match e1000e_probe() { Ok(_code) => { - kinfo!("Successfully init e1000e device!"); + info!("Successfully init e1000e device!"); } Err(_error) => { - kinfo!("Error occurred!"); + info!("Error occurred!"); } } } @@ -610,7 +609,7 @@ pub fn e1000e_probe() -> Result { if header.vendor_id == 0x8086 { // intel if E1000E_DEVICE_ID.contains(&header.device_id) { - kdebug!( + debug!( "Detected e1000e PCI device with device id {:#x}", header.device_id ); diff --git a/kernel/src/driver/net/e1000e/e1000e_driver.rs b/kernel/src/driver/net/e1000e/e1000e_driver.rs index 92ff60c4..fbac2f83 100644 --- a/kernel/src/driver/net/e1000e/e1000e_driver.rs +++ b/kernel/src/driver/net/e1000e/e1000e_driver.rs @@ -10,7 +10,6 @@ use crate::{ }, net::NetDevice, }, - kinfo, libs::spinlock::SpinLock, net::{generate_iface_id, NET_DEVICES}, time::Instant, @@ -24,6 +23,7 @@ use core::{ fmt::Debug, ops::{Deref, DerefMut}, }; +use log::info; use smoltcp::{ phy, wire::{self, HardwareAddress}, @@ -367,5 +367,5 @@ pub fn e1000e_driver_init(device: E1000EDevice) { NET_DEVICES .write_irqsave() .insert(iface.nic_id(), iface.clone()); - kinfo!("e1000e driver init successfully!\tMAC: [{}]", mac); + info!("e1000e driver init successfully!\tMAC: [{}]", mac); } diff --git a/kernel/src/driver/net/virtio_net.rs b/kernel/src/driver/net/virtio_net.rs index 1bc1f6a6..58551e4a 100644 --- a/kernel/src/driver/net/virtio_net.rs +++ b/kernel/src/driver/net/virtio_net.rs @@ -10,6 +10,7 @@ use alloc::{ sync::{Arc, Weak}, vec::Vec, }; +use log::{debug, error}; use smoltcp::{iface, phy, wire}; use unified_init::macros::unified_init; use virtio_drivers::device::net::VirtIONet; @@ -39,7 +40,6 @@ use crate::{ exception::{irqdesc::IrqReturn, IrqNumber}, filesystem::kernfs::KernFSInode, init::initcall::INITCALL_POSTCORE, - kerror, libs::{ rwlock::{RwLockReadGuard, RwLockWriteGuard}, spinlock::{SpinLock, SpinLockGuard}, @@ -357,12 +357,12 @@ impl phy::Device for VirtIONicDeviceInner { } fn transmit(&mut self, _timestamp: smoltcp::time::Instant) -> Option> { - // kdebug!("VirtioNet: transmit"); + // debug!("VirtioNet: transmit"); if self.inner.lock_irqsave().can_send() { - // kdebug!("VirtioNet: can send"); + // debug!("VirtioNet: can send"); return Some(VirtioNetToken::new(self.clone(), None)); } else { - // kdebug!("VirtioNet: can not send"); + // debug!("VirtioNet: can not send"); return None; } } @@ -418,14 +418,14 @@ pub fn virtio_net(transport: VirtIOTransport, dev_id: Arc) { match VirtIONet::::new(transport, 4096) { Ok(net) => net, Err(_) => { - kerror!("VirtIONet init failed"); + error!("VirtIONet init failed"); return; } }; let mac = wire::EthernetAddress::from_bytes(&driver_net.mac_address()); let dev_inner = VirtIONicDeviceInner::new(driver_net); let iface = VirtioInterface::new(dev_inner, dev_id); - kdebug!("To add virtio net: {}, mac: {}", iface.device_name(), mac); + debug!("To add virtio net: {}, mac: {}", iface.device_name(), mac); virtio_device_manager() .device_add(iface.clone() as Arc) .expect("Add virtio net failed"); @@ -471,7 +471,7 @@ impl NetDevice for VirtioInterface { let mut guard = self.iface.lock(); let poll_res = guard.poll(timestamp, self.device_inner.force_get_mut(), sockets); // todo: notify!!! - // kdebug!("Virtio Interface poll:{poll_res}"); + // debug!("Virtio Interface poll:{poll_res}"); if poll_res { return Ok(()); } @@ -596,7 +596,7 @@ impl VirtIODriver for VirtIONetDriver { .arc_any() .downcast::() .map_err(|_| { - kerror!( + error!( "VirtIONetDriver::probe() failed: device is not a VirtioInterface. Device: '{:?}'", device.name() ); diff --git a/kernel/src/driver/open_firmware/fdt.rs b/kernel/src/driver/open_firmware/fdt.rs index 2189ef5a..4b68e78e 100644 --- a/kernel/src/driver/open_firmware/fdt.rs +++ b/kernel/src/driver/open_firmware/fdt.rs @@ -4,6 +4,7 @@ use fdt::{ node::{FdtNode, NodeProperty}, Fdt, }; +use log::{debug, error, warn}; use system_error::SystemError; use crate::{ @@ -79,7 +80,7 @@ impl OpenFirmwareFdtDriver { let fdt_vaddr = boot_params().read().fdt().ok_or(SystemError::ENODEV)?; let fdt: Fdt<'_> = unsafe { fdt::Fdt::from_ptr(fdt_vaddr.as_ptr()).map_err(|e| { - kerror!("failed to parse fdt, err={:?}", e); + error!("failed to parse fdt, err={:?}", e); SystemError::EINVAL }) }?; @@ -91,7 +92,7 @@ impl OpenFirmwareFdtDriver { .expect("Failed to scan fdt root node."); self.early_init_scan_chosen(fdt).unwrap_or_else(|_| { - kwarn!("No `chosen` node found"); + warn!("No `chosen` node found"); }); self.early_init_scan_memory(fdt); @@ -106,13 +107,13 @@ impl OpenFirmwareFdtDriver { if let Some(prop) = node.property("#size-cells") { guard.root_size_cells = prop.as_usize().unwrap() as u32; - // kdebug!("fdt_root_size_cells={}", guard.root_size_cells); + // debug!("fdt_root_size_cells={}", guard.root_size_cells); } if let Some(prop) = node.property("#address-cells") { guard.root_addr_cells = prop.as_usize().unwrap() as u32; - // kdebug!("fdt_root_addr_cells={}", guard.root_addr_cells); + // debug!("fdt_root_addr_cells={}", guard.root_addr_cells); } return Ok(()); @@ -144,7 +145,7 @@ impl OpenFirmwareFdtDriver { // TODO: 拼接内核自定义的command line参数 - kdebug!("Command line: {}", boot_params().read().boot_cmdline_str()); + debug!("Command line: {}", boot_params().read().boot_cmdline_str()); return Ok(()); } @@ -194,7 +195,7 @@ impl OpenFirmwareFdtDriver { continue; } - kdebug!("Found memory: base={:#x}, size={:#x}", base, size); + debug!("Found memory: base={:#x}, size={:#x}", base, size); self.early_init_dt_add_memory(base, size); found_memory = true; } @@ -205,7 +206,7 @@ impl OpenFirmwareFdtDriver { #[cfg(target_arch = "x86_64")] pub fn early_init_dt_add_memory(&self, _base: u64, _size: u64) { - kBUG!("x86_64 should not call early_init_dt_add_memory"); + panic!("x86_64 should not call early_init_dt_add_memory"); } #[cfg(not(target_arch = "x86_64"))] @@ -220,7 +221,7 @@ impl OpenFirmwareFdtDriver { let mut size = size as usize; if size < (MMArch::PAGE_SIZE - (base & (!MMArch::PAGE_MASK))) { - kwarn!("Ignoring memory block {:#x}-{:#x}", base, base + size); + warn!("Ignoring memory block {:#x}-{:#x}", base, base + size); } if PhysAddr::new(base).check_aligned(MMArch::PAGE_SIZE) == false { @@ -231,11 +232,11 @@ impl OpenFirmwareFdtDriver { size = page_align_down(size); if base > MemBlockManager::MAX_MEMBLOCK_ADDR.data() { - kwarn!("Ignoring memory block {:#x}-{:#x}", base, base + size); + warn!("Ignoring memory block {:#x}-{:#x}", base, base + size); } if base + size - 1 > MemBlockManager::MAX_MEMBLOCK_ADDR.data() { - kwarn!( + warn!( "Ignoring memory range {:#x}-{:#x}", MemBlockManager::MAX_MEMBLOCK_ADDR.data() + 1, base + size @@ -244,13 +245,13 @@ impl OpenFirmwareFdtDriver { } if base + size < MemBlockManager::MIN_MEMBLOCK_ADDR.data() { - kwarn!("Ignoring memory range {:#x}-{:#x}", base, base + size); + warn!("Ignoring memory range {:#x}-{:#x}", base, base + size); return; } if base < MemBlockManager::MIN_MEMBLOCK_ADDR.data() { { - kwarn!( + warn!( "Ignoring memory range {:#x}-{:#x}", base, MemBlockManager::MIN_MEMBLOCK_ADDR.data() @@ -312,7 +313,7 @@ impl OpenFirmwareFdtDriver { if node.size() != 0 { let address = PhysAddr::new(node.address() as usize); let size = node.size(); - kdebug!("Reserve memory: {:?}-{:?}", address, address + size); + debug!("Reserve memory: {:?}-{:?}", address, address + size); mem_block_manager().reserve_block(address, size).unwrap(); } } @@ -406,7 +407,7 @@ fn reserved_mem_reserve_reg(node: &FdtNode<'_, '_>) -> Result<(), SystemError> { let mut reg_size = reg.value.len(); if reg_size > 0 && reg_size % t_len != 0 { - kerror!( + error!( "Reserved memory: invalid reg property in '{}', skipping node.", node.name ); @@ -431,18 +432,14 @@ fn reserved_mem_reserve_reg(node: &FdtNode<'_, '_>) -> Result<(), SystemError> { .early_init_dt_reserve_memory(PhysAddr::new(base as usize), size as usize, nomap) .is_ok() { - kdebug!( + debug!( "Reserved memory: base={:#x}, size={:#x}, nomap={}", - base, - size, - nomap + base, size, nomap ); } else { - kerror!( + error!( "Failed to reserve memory: base={:#x}, size={:#x}, nomap={}", - base, - size, - nomap + base, size, nomap ); } diff --git a/kernel/src/driver/pci/attr.rs b/kernel/src/driver/pci/attr.rs index ae22e374..6d59122b 100644 --- a/kernel/src/driver/pci/attr.rs +++ b/kernel/src/driver/pci/attr.rs @@ -1,5 +1,6 @@ use alloc::sync::Arc; use intertrait::cast::CastArc; +use log::warn; use system_error::SystemError; use crate::{ @@ -50,7 +51,7 @@ impl Attribute for Vendor { let dev = _kobj .cast::() .map_err(|e: Arc| { - kwarn!("device:{:?} is not a pci device!", e); + warn!("device:{:?} is not a pci device!", e); SystemError::EINVAL })?; return sysfs_emit_str(_buf, &format!("0x{:04x}", dev.vendor())); @@ -81,7 +82,7 @@ impl Attribute for DeviceID { let dev = _kobj .cast::() .map_err(|e: Arc| { - kwarn!("device:{:?} is not a pci device!", e); + warn!("device:{:?} is not a pci device!", e); SystemError::EINVAL })?; return sysfs_emit_str(_buf, &format!("0x{:04x}", dev.device_id())); @@ -112,7 +113,7 @@ impl Attribute for SubsystemVendor { let dev = _kobj .cast::() .map_err(|e: Arc| { - kwarn!("device:{:?} is not a pci device!", e); + warn!("device:{:?} is not a pci device!", e); SystemError::EINVAL })?; return sysfs_emit_str(_buf, &format!("0x{:04x}", dev.subsystem_vendor())); @@ -143,7 +144,7 @@ impl Attribute for SubsystemDevice { let dev = _kobj .cast::() .map_err(|e: Arc| { - kwarn!("device:{:?} is not a pci device!", e); + warn!("device:{:?} is not a pci device!", e); SystemError::EINVAL })?; return sysfs_emit_str(_buf, &format!("0x{:04x}", dev.subsystem_device())); diff --git a/kernel/src/driver/pci/ecam.rs b/kernel/src/driver/pci/ecam.rs index de1529c9..e3403416 100644 --- a/kernel/src/driver/pci/ecam.rs +++ b/kernel/src/driver/pci/ecam.rs @@ -1,3 +1,5 @@ +use log::{error, warn}; + use crate::mm::PhysAddr; use super::{ @@ -56,13 +58,13 @@ impl EcamRootInfoManager { ); if let Err(err) = root { - kerror!("add_ecam_root_info(): failed to create PciRoot: {:?}", err); + error!("add_ecam_root_info(): failed to create PciRoot: {:?}", err); return; } pci_root_manager().add_pci_root(root.unwrap()); } else { - kwarn!( + warn!( "add_ecam_root_info(): root {} already exists", ecam_root_info.segement_group_number ); diff --git a/kernel/src/driver/pci/pci.rs b/kernel/src/driver/pci/pci.rs index 12168e20..3b5c97e8 100644 --- a/kernel/src/driver/pci/pci.rs +++ b/kernel/src/driver/pci/pci.rs @@ -14,12 +14,13 @@ use crate::libs::rwlock::{RwLock, RwLockReadGuard, RwLockWriteGuard}; use crate::mm::mmio_buddy::{mmio_pool, MMIOSpaceGuard}; use crate::mm::VirtAddr; -use crate::{kdebug, kerror, kinfo, kwarn}; + use alloc::string::String; use alloc::sync::Arc; use alloc::vec::Vec; use alloc::{boxed::Box, collections::LinkedList}; use bitflags::bitflags; +use log::{debug, error, info, warn}; use core::{ convert::TryFrom, @@ -962,7 +963,7 @@ fn pci_read_pci_to_cardbus_bridge_header( /// @brief 检查所有bus上的设备并将其加入链表 /// @return 成功返回ok(),失败返回失败原因 fn pci_check_all_buses() -> Result { - kinfo!("Checking all devices in PCI bus..."); + info!("Checking all devices in PCI bus..."); let busdevicefunction = BusDeviceFunction { bus: 0, device: 0, @@ -981,7 +982,7 @@ fn pci_check_all_buses() -> Result { /// @brief 检查特定设备并将其加入链表 /// @return 成功返回ok(),失败返回失败原因 fn pci_check_function(busdevicefunction: BusDeviceFunction) -> Result { - //kdebug!("PCI check function {}", busdevicefunction.function); + //debug!("PCI check function {}", busdevicefunction.function); let header = match pci_read_header(busdevicefunction, true) { Ok(header) => header, Err(PciError::GetWrongHeader) => { @@ -1007,7 +1008,7 @@ fn pci_check_function(busdevicefunction: BusDeviceFunction) -> Result Result { - //kdebug!("PCI check device {}", device); + //debug!("PCI check device {}", device); let busdevicefunction = BusDeviceFunction { bus, device, @@ -1026,10 +1027,9 @@ fn pci_check_device(bus: u8, device: u8) -> Result { pci_check_function(busdevicefunction)?; let common_header = header.common_header(); if common_header.header_type & 0x80 != 0 { - kdebug!( + debug!( "Detected multi func device in bus{},device{}", - busdevicefunction.bus, - busdevicefunction.device + busdevicefunction.bus, busdevicefunction.device ); // 这是一个多function的设备,因此查询剩余的function for function in 1..8 { @@ -1046,7 +1046,7 @@ fn pci_check_device(bus: u8, device: u8) -> Result { /// @brief 检查该bus上的设备并将其加入链表 /// @return 成功返回ok(),失败返回失败原因 fn pci_check_bus(bus: u8) -> Result { - //kdebug!("PCI check bus {}", bus); + //debug!("PCI check bus {}", bus); for device in 0..32 { pci_check_device(bus, device)?; } @@ -1056,13 +1056,13 @@ fn pci_check_bus(bus: u8) -> Result { /// pci初始化函数 #[inline(never)] pub fn pci_init() { - kinfo!("Initializing PCI bus..."); + info!("Initializing PCI bus..."); pci_bus_subsys_init().expect("Failed to init pci bus subsystem"); if let Err(e) = pci_check_all_buses() { - kerror!("pci init failed when checking bus because of error: {}", e); + error!("pci init failed when checking bus because of error: {}", e); return; } - kinfo!( + info!( "Total pci device and function num = {}", PCI_DEVICE_LINKEDLIST.num() ); @@ -1071,40 +1071,34 @@ pub fn pci_init() { let common_header = box_pci_device.common_header(); match box_pci_device.header_type() { HeaderType::Standard if common_header.status & 0x10 != 0 => { - kinfo!("Found pci standard device with class code ={} subclass={} status={:#x} cap_pointer={:#x} vendor={:#x}, device id={:#x},bdf={}", common_header.class_code, common_header.subclass, common_header.status, box_pci_device.as_standard_device().unwrap().capabilities_pointer,common_header.vendor_id, common_header.device_id,common_header.bus_device_function); + info!("Found pci standard device with class code ={} subclass={} status={:#x} cap_pointer={:#x} vendor={:#x}, device id={:#x},bdf={}", common_header.class_code, common_header.subclass, common_header.status, box_pci_device.as_standard_device().unwrap().capabilities_pointer,common_header.vendor_id, common_header.device_id,common_header.bus_device_function); } HeaderType::Standard => { - kinfo!( + info!( "Found pci standard device with class code ={} subclass={} status={:#x} ", - common_header.class_code, - common_header.subclass, - common_header.status + common_header.class_code, common_header.subclass, common_header.status ); } HeaderType::PciPciBridge if common_header.status & 0x10 != 0 => { - kinfo!("Found pci-to-pci bridge device with class code ={} subclass={} status={:#x} cap_pointer={:#x}", common_header.class_code, common_header.subclass, common_header.status, box_pci_device.as_pci_to_pci_bridge_device().unwrap().capability_pointer); + info!("Found pci-to-pci bridge device with class code ={} subclass={} status={:#x} cap_pointer={:#x}", common_header.class_code, common_header.subclass, common_header.status, box_pci_device.as_pci_to_pci_bridge_device().unwrap().capability_pointer); } HeaderType::PciPciBridge => { - kinfo!( + info!( "Found pci-to-pci bridge device with class code ={} subclass={} status={:#x} ", - common_header.class_code, - common_header.subclass, - common_header.status + common_header.class_code, common_header.subclass, common_header.status ); } HeaderType::PciCardbusBridge => { - kinfo!( + info!( "Found pcicardbus bridge device with class code ={} subclass={} status={:#x} ", - common_header.class_code, - common_header.subclass, - common_header.status + common_header.class_code, common_header.subclass, common_header.status ); } HeaderType::Unrecognised(_) => {} } } - kinfo!("PCI bus initialized."); + info!("PCI bus initialized."); } /// An identifier for a PCI bus, device and function. @@ -1340,7 +1334,7 @@ pub fn pci_bar_init( // A wrapping add is necessary to correctly handle the case of unused BARs, which read back // as 0, and should be treated as size 0. let size = (!(size_mask & 0xfffffff0)).wrapping_add(1); - //kdebug!("bar_orig:{:#x},size: {:#x}", bar_orig,size); + //debug!("bar_orig:{:#x},size: {:#x}", bar_orig,size); // Restore the original value. pci_root_0().write_config( bus_device_function, @@ -1380,7 +1374,7 @@ pub fn pci_bar_init( .create_mmio(size_want) .map_err(|_| PciError::CreateMmioError)?; space_guard = Arc::new(tmp); - //kdebug!("Pci bar init: mmio space: {space_guard:?}, paddr={paddr:?}, size_want={size_want}"); + //debug!("Pci bar init: mmio space: {space_guard:?}, paddr={paddr:?}, size_want={size_want}"); assert!( space_guard.map_phys(paddr, size_want).is_ok(), "pci_bar_init: map_phys failed" @@ -1416,7 +1410,7 @@ pub fn pci_bar_init( _ => {} } } - //kdebug!("pci_device_bar:{}", device_bar); + //debug!("pci_device_bar:{}", device_bar); return Ok(device_bar); } @@ -1454,7 +1448,7 @@ impl Iterator for CapabilityIterator { self.next_capability_offset = if next_offset == 0 { None } else if next_offset < 64 || next_offset & 0x3 != 0 { - kwarn!("Invalid next capability offset {:#04x}", next_offset); + warn!("Invalid next capability offset {:#04x}", next_offset); None } else { Some(next_offset) @@ -1502,7 +1496,7 @@ impl<'a> Iterator for ExternalCapabilityIterator<'a> { self.next_capability_offset = if next_offset == 0 { None } else if next_offset < 0x100 || next_offset & 0x3 != 0 { - kwarn!("Invalid next capability offset {:#04x}", next_offset); + warn!("Invalid next capability offset {:#04x}", next_offset); None } else { Some(next_offset) diff --git a/kernel/src/driver/pci/pci_irq.rs b/kernel/src/driver/pci/pci_irq.rs index 2246f0c9..e31082dd 100644 --- a/kernel/src/driver/pci/pci_irq.rs +++ b/kernel/src/driver/pci/pci_irq.rs @@ -6,6 +6,7 @@ use core::ptr::NonNull; use alloc::string::String; use alloc::sync::Arc; use alloc::vec::Vec; +use log::error; use system_error::SystemError; use super::pci::{PciDeviceStructure, PciDeviceStructureGeneralDevice, PciError}; @@ -385,7 +386,7 @@ pub trait PciInterrupt: PciDeviceStructure { } Err(_) => { - kerror!( + error!( "Failed to request pci irq {} for device {}", irq_num.data(), &common_msg.irq_name @@ -548,7 +549,7 @@ pub trait PciInterrupt: PciDeviceStructure { } Err(_) => { - kerror!( + error!( "Failed to request pci irq {} for device {}", irq_num.data(), &common_msg.irq_name diff --git a/kernel/src/driver/pci/root.rs b/kernel/src/driver/pci/root.rs index 2d792884..2deb1cb6 100644 --- a/kernel/src/driver/pci/root.rs +++ b/kernel/src/driver/pci/root.rs @@ -91,7 +91,7 @@ impl PciRoot { /// @brief 完成物理地址到虚拟地址的映射,并将虚拟地址加入mmio_base变量 /// @return 返回错误或Ok(0) fn map(&mut self) -> Result { - //kdebug!("bus_begin={},bus_end={}", self.bus_begin,self.bus_end); + //debug!("bus_begin={},bus_end={}", self.bus_begin,self.bus_end); let bus_number = (self.bus_end - self.bus_begin) as u32 + 1; let bus_number_double = (bus_number - 1) / 2 + 1; //一个bus占据1MB空间,计算全部bus占据空间相对于2MB空间的个数 diff --git a/kernel/src/driver/pci/subsys.rs b/kernel/src/driver/pci/subsys.rs index 4b9aa9a9..c2e5ee39 100644 --- a/kernel/src/driver/pci/subsys.rs +++ b/kernel/src/driver/pci/subsys.rs @@ -3,6 +3,7 @@ use alloc::{ sync::{Arc, Weak}, }; use intertrait::cast::CastArc; +use log::error; use system_error::SystemError; use crate::{ @@ -89,14 +90,14 @@ impl Bus for PciBus { fn probe(&self, device: &Arc) -> Result<(), SystemError> { let drv = device.driver().ok_or(SystemError::EINVAL)?; let pci_drv = drv.cast::().map_err(|_| { - kerror!( + error!( "PciBus::probe() failed: device.driver() is not a PciDriver. Device: '{:?}'", device.name() ); SystemError::EINVAL })?; let pci_dev = device.clone().cast::().map_err(|_| { - kerror!( + error!( "PciBus::probe() failed: device is not a PciDevice. Device: '{:?}'", device.name() ); diff --git a/kernel/src/driver/rtc/class.rs b/kernel/src/driver/rtc/class.rs index 12184e56..d10f11cf 100644 --- a/kernel/src/driver/rtc/class.rs +++ b/kernel/src/driver/rtc/class.rs @@ -2,6 +2,7 @@ use alloc::{ string::ToString, sync::{Arc, Weak}, }; +use log::info; use system_error::SystemError; use unified_init::macros::unified_init; @@ -100,7 +101,7 @@ fn rtc_hctosys(dev: &Arc) { let r = do_settimeofday64(timespec64); dev.set_hc2sys_result(r); - kinfo!( + info!( "Setting system clock to {} {} UTC ({})", time.date_string(), time.time_string(), diff --git a/kernel/src/driver/serial/serial8250/mod.rs b/kernel/src/driver/serial/serial8250/mod.rs index 48c82c07..519ff21c 100644 --- a/kernel/src/driver/serial/serial8250/mod.rs +++ b/kernel/src/driver/serial/serial8250/mod.rs @@ -8,6 +8,7 @@ use alloc::{ sync::{Arc, Weak}, vec::Vec, }; +use log::error; use system_error::SystemError; use crate::{ @@ -410,7 +411,7 @@ impl PlatformDriver for Serial8250ISADriver { .arc_any() .downcast::() .map_err(|_| { - kerror!("Serial8250ISADriver::probe: device is not a Serial8250ISADevices"); + error!("Serial8250ISADriver::probe: device is not a Serial8250ISADevices"); SystemError::EINVAL })?; isa_dev.set_driver(Some(self.self_ref.clone())); diff --git a/kernel/src/driver/tty/tty_driver.rs b/kernel/src/driver/tty/tty_driver.rs index 53225067..6acb4cbd 100644 --- a/kernel/src/driver/tty/tty_driver.rs +++ b/kernel/src/driver/tty/tty_driver.rs @@ -6,6 +6,7 @@ use alloc::{ vec::Vec, }; use hashbrown::HashMap; +use log::warn; use system_error::SystemError; use crate::{ @@ -284,7 +285,7 @@ impl TtyDriver { Some(tty) => { // TODO: 暂时这么写,因为还没写TtyPort if tty.core().port().is_none() { - kwarn!("{} port is None", tty.core().name()); + warn!("{} port is None", tty.core().name()); } else if tty.core().port().unwrap().state() == TtyPortState::KOPENED { return Err(SystemError::EBUSY); } diff --git a/kernel/src/driver/tty/virtual_terminal/virtual_console.rs b/kernel/src/driver/tty/virtual_terminal/virtual_console.rs index 3fc94b32..c0ee17c4 100644 --- a/kernel/src/driver/tty/virtual_terminal/virtual_console.rs +++ b/kernel/src/driver/tty/virtual_terminal/virtual_console.rs @@ -5,6 +5,7 @@ use alloc::{ vec::Vec, }; use bitmap::{traits::BitMapOps, StaticBitmap}; +use log::warn; use crate::{ driver::{ @@ -936,7 +937,7 @@ impl VirtualConsoleData { 'c' => { if self.par[0] == 0 { - kwarn!("respone ID todo"); + warn!("respone ID todo"); } return; } @@ -1612,7 +1613,7 @@ impl VirtualConsoleData { tc |= ((attr as u32) << 8) & (!himask as u32); - // kwarn!( + // warn!( // "ch {} pos {} x {} y {} cols {}", // c as u8 as char, // self.pos, diff --git a/kernel/src/driver/video/fbdev/base/fbcon/framebuffer_console.rs b/kernel/src/driver/video/fbdev/base/fbcon/framebuffer_console.rs index d0a3040e..4a193f28 100644 --- a/kernel/src/driver/video/fbdev/base/fbcon/framebuffer_console.rs +++ b/kernel/src/driver/video/fbdev/base/fbcon/framebuffer_console.rs @@ -1,4 +1,5 @@ use alloc::{sync::Arc, vec::Vec}; +use log::warn; use system_error::SystemError; use crate::{ @@ -200,7 +201,7 @@ impl ConsoleSwitch for BlittingFbConsole { vc_data.font.height = font.height; vc_data.font.count = font.char_count; } else { - kwarn!("The frontend Framebuffer is not implemented"); + warn!("The frontend Framebuffer is not implemented"); } vc_data.color_mode = fb.color_depth() != 1; diff --git a/kernel/src/driver/video/fbdev/base/fbcon/mod.rs b/kernel/src/driver/video/fbdev/base/fbcon/mod.rs index 3d95e85a..2c1fbccb 100644 --- a/kernel/src/driver/video/fbdev/base/fbcon/mod.rs +++ b/kernel/src/driver/video/fbdev/base/fbcon/mod.rs @@ -3,6 +3,7 @@ use alloc::{ sync::{Arc, Weak}, vec::Vec, }; +use log::warn; use system_error::SystemError; use crate::{ @@ -165,7 +166,7 @@ impl KObject for FbConsoleDevice { fn set_name(&self, _name: String) { // 不允许修改 - kwarn!("fbcon name can not be changed"); + warn!("fbcon name can not be changed"); } fn kobj_state(&self) -> RwLockReadGuard { @@ -199,7 +200,7 @@ impl Device for FbConsoleDevice { fn set_class(&self, _class: Option>) { // 不允许修改 - kwarn!("fbcon's class can not be changed"); + warn!("fbcon's class can not be changed"); } fn class(&self) -> Option> { @@ -279,13 +280,13 @@ impl Attribute for AttrRotate { /// https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/video/fbdev/core/fbcon.c#3226 fn show(&self, _kobj: Arc, buf: &mut [u8]) -> Result { - kwarn!("fbcon rotate show not implemented"); + warn!("fbcon rotate show not implemented"); return sysfs_emit_str(buf, "0\n"); } /// https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/video/fbdev/core/fbcon.c#3182 fn store(&self, _kobj: Arc, _buf: &[u8]) -> Result { - kwarn!("fbcon rotate store not implemented"); + warn!("fbcon rotate store not implemented"); return Err(SystemError::ENOSYS); } } @@ -308,7 +309,7 @@ impl Attribute for AttrRotateAll { /// https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/video/fbdev/core/fbcon.c#3204 fn store(&self, _kobj: Arc, _buf: &[u8]) -> Result { - kwarn!("fbcon rotate_all store not implemented"); + warn!("fbcon rotate_all store not implemented"); return Err(SystemError::ENOSYS); } } diff --git a/kernel/src/driver/video/fbdev/base/fbmem.rs b/kernel/src/driver/video/fbdev/base/fbmem.rs index bb404ab3..8031fc6d 100644 --- a/kernel/src/driver/video/fbdev/base/fbmem.rs +++ b/kernel/src/driver/video/fbdev/base/fbmem.rs @@ -6,6 +6,7 @@ use alloc::{ vec::Vec, }; +use log::error; use system_error::SystemError; use unified_init::macros::unified_init; @@ -152,7 +153,7 @@ impl FrameBufferManager { device_manager().add_device(fb_device.clone() as Arc)?; // 添加到devfs devfs_register(&fb_device.name(), fb_device.clone()).map_err(|e| { - kerror!( + error!( "register fb device '{}' to devfs failed: {:?}", fb_device.name(), e diff --git a/kernel/src/driver/video/fbdev/base/fbsysfs.rs b/kernel/src/driver/video/fbdev/base/fbsysfs.rs index 0020ec1d..7b602570 100644 --- a/kernel/src/driver/video/fbdev/base/fbsysfs.rs +++ b/kernel/src/driver/video/fbdev/base/fbsysfs.rs @@ -1,4 +1,5 @@ use alloc::sync::Arc; +use log::warn; use system_error::SystemError; use crate::{ @@ -85,7 +86,7 @@ impl Attribute for AttrBitsPerPixel { } fn store(&self, _kobj: Arc, _buf: &[u8]) -> Result { - kwarn!("attr bits_per_pixel store not implemented"); + warn!("attr bits_per_pixel store not implemented"); return Err(SystemError::ENOSYS); } @@ -116,7 +117,7 @@ impl Attribute for AttrBlank { // todo: https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/video/fbdev/core/fbsysfs.c#309 fn store(&self, _kobj: Arc, _buf: &[u8]) -> Result { - kwarn!("attr blank store not implemented"); + warn!("attr blank store not implemented"); return Err(SystemError::ENOSYS); } } diff --git a/kernel/src/driver/video/fbdev/base/mod.rs b/kernel/src/driver/video/fbdev/base/mod.rs index e20b0871..c5a4c7a6 100644 --- a/kernel/src/driver/video/fbdev/base/mod.rs +++ b/kernel/src/driver/video/fbdev/base/mod.rs @@ -341,7 +341,7 @@ pub trait FrameBufferInfo: FrameBufferOps { // && var.green.offset == var.blue.offset // && var.green.offset == var.red.offset // { - // kerror!("return {}", var.green.length); + // error!("return {}", var.green.length); // return var.green.length; // } else { // return var.green.length + var.blue.length + var.red.length; diff --git a/kernel/src/driver/video/fbdev/vesafb.rs b/kernel/src/driver/video/fbdev/vesafb.rs index 2472973d..a5c48696 100644 --- a/kernel/src/driver/video/fbdev/vesafb.rs +++ b/kernel/src/driver/video/fbdev/vesafb.rs @@ -9,6 +9,7 @@ use alloc::{ sync::{Arc, Weak}, vec::Vec, }; +use log::{info, warn}; use system_error::SystemError; use unified_init::macros::unified_init; @@ -390,7 +391,7 @@ impl FrameBufferOps for VesaFb { /// ## 填充矩形 fn fb_fillrect(&self, rect: super::base::FillRectData) -> Result<(), SystemError> { - // kwarn!("rect {rect:?}"); + // warn!("rect {rect:?}"); let boot_param = boot_params().read(); let screen_base = boot_param @@ -1006,7 +1007,7 @@ fn vesa_fb_device_init() -> Result<(), SystemError> { static INIT: Once = Once::new(); INIT.call_once(|| { - kinfo!("vesa fb device init"); + info!("vesa fb device init"); let device = Arc::new(VesaFb::new()); let mut fb_fix = VESAFB_FIX_INFO.write_irqsave(); @@ -1068,7 +1069,7 @@ fn vesa_fb_device_init() -> Result<(), SystemError> { // 加入全局fb表 let mut guard = FRAME_BUFFER_SET.write(); if guard.get(device.fb_id().data() as usize).unwrap().is_some() { - kwarn!( + warn!( "vesa_fb_device_init: There is already an element {:?} in the FRAME_BUFFER_SET", device.fb_id() ); diff --git a/kernel/src/driver/video/mod.rs b/kernel/src/driver/video/mod.rs index 6a8c406d..282e672d 100644 --- a/kernel/src/driver/video/mod.rs +++ b/kernel/src/driver/video/mod.rs @@ -3,7 +3,6 @@ use core::sync::atomic::{AtomicBool, Ordering}; use crate::{ arch::MMArch, init::boot_params, - kinfo, libs::{ align::page_align_up, lib_ui::screen_manager::{ScmBuffer, ScmBufferFlag, ScmBufferInfo}, @@ -17,6 +16,7 @@ use crate::{ time::timer::{Timer, TimerFunction}, }; use alloc::{boxed::Box, sync::Arc}; +use log::info; use system_error::SystemError; pub mod console; @@ -78,7 +78,7 @@ impl VideoRefreshManager { * 将帧缓存区映射到地址SPECIAL_MEMOEY_MAPPING_VIRT_ADDR_BASE处 */ fn init_frame_buffer(&self) { - kinfo!("Re-mapping VBE frame buffer..."); + info!("Re-mapping VBE frame buffer..."); let buf_vaddr = boot_params() .read_irqsave() .screen_info @@ -115,7 +115,7 @@ impl VideoRefreshManager { } } - kinfo!("VBE frame buffer successfully Re-mapped!"); + info!("VBE frame buffer successfully Re-mapped!"); } /** diff --git a/kernel/src/driver/virtio/irq.rs b/kernel/src/driver/virtio/irq.rs index 70f823ab..aa727670 100644 --- a/kernel/src/driver/virtio/irq.rs +++ b/kernel/src/driver/virtio/irq.rs @@ -1,5 +1,6 @@ use alloc::sync::Arc; use hashbrown::HashMap; +use log::warn; use system_error::SystemError; use unified_init::macros::unified_init; @@ -120,7 +121,7 @@ impl IrqHandler for DefaultVirtioIrqHandler { return dev.handle_irq(irq); } else { // 未绑定具体设备,因此无法处理中断 - kwarn!("No device found for IRQ: {:?}", irq); + warn!("No device found for IRQ: {:?}", irq); return Ok(IrqReturn::NotHandled); } } diff --git a/kernel/src/driver/virtio/mmio.rs b/kernel/src/driver/virtio/mmio.rs index 027a70bd..815cce58 100644 --- a/kernel/src/driver/virtio/mmio.rs +++ b/kernel/src/driver/virtio/mmio.rs @@ -1,4 +1,5 @@ use fdt::node::FdtNode; +use log::error; use system_error::SystemError; use crate::driver::{ @@ -9,7 +10,7 @@ use super::{transport::VirtIOTransport, virtio::virtio_device_init}; pub(super) fn virtio_probe_mmio() { if let Err(e) = do_probe_virtio_mmio() { - kerror!("virtio_probe_mmio failed: {:?}", e); + error!("virtio_probe_mmio failed: {:?}", e); } } diff --git a/kernel/src/driver/virtio/sysfs.rs b/kernel/src/driver/virtio/sysfs.rs index 526a88ad..dc1d0ea1 100644 --- a/kernel/src/driver/virtio/sysfs.rs +++ b/kernel/src/driver/virtio/sysfs.rs @@ -4,6 +4,7 @@ use alloc::{ }; use ida::IdAllocator; use intertrait::cast::CastArc; +use log::error; use system_error::SystemError; use unified_init::macros::unified_init; @@ -78,7 +79,7 @@ impl Bus for VirtIOBus { fn probe(&self, device: &Arc) -> Result<(), SystemError> { let drv = device.driver().ok_or(SystemError::EINVAL)?; let virtio_drv = drv.cast::().map_err(|_| { - kerror!( + error!( "VirtIOBus::probe() failed: device.driver() is not a VirtioDriver. Device: '{:?}'", device.name() ); @@ -86,7 +87,7 @@ impl Bus for VirtIOBus { })?; let virtio_dev = device.clone().cast::().map_err(|_| { - kerror!( + error!( "VirtIOBus::probe() failed: device is not a VirtIODevice. Device: '{:?}'", device.name() ); @@ -167,7 +168,7 @@ impl VirtIODeviceManager { let drv = dev.driver().ok_or(SystemError::EINVAL)?; let virtio_drv = drv.cast::().map_err(|_| { - kerror!( + error!( "VirtIODeviceManager::device_add() failed: device.driver() is not a VirtioDriver. Device: '{:?}'", dev.name() ); @@ -199,7 +200,7 @@ impl VirtIODeviceManager { IrqHandleFlags::IRQF_SHARED, Some(dev.dev_id().clone()), ) { - kerror!( + error!( "Failed to request irq for virtio device '{}': irq: {:?}, error {:?}", dev.device_name(), irq, @@ -211,7 +212,7 @@ impl VirtIODeviceManager { virtio_irq_manager() .register_device(dev.clone()) .map_err(|e| { - kerror!( + error!( "Failed to register virtio device's irq, dev: '{}', irq: {:?}, error {:?}", dev.device_name(), irq, @@ -302,7 +303,7 @@ impl Attribute for AttrDevice { fn show(&self, kobj: Arc, buf: &mut [u8]) -> Result { let dev = kobj.cast::().map_err(|_| { - kerror!("AttrDevice::show() failed: kobj is not a VirtIODevice"); + error!("AttrDevice::show() failed: kobj is not a VirtIODevice"); SystemError::EINVAL })?; let device_type_id = dev.device_type_id(); @@ -329,7 +330,7 @@ impl Attribute for AttrVendor { fn show(&self, kobj: Arc, buf: &mut [u8]) -> Result { let dev = kobj.cast::().map_err(|_| { - kerror!("AttrVendor::show() failed: kobj is not a VirtIODevice"); + error!("AttrVendor::show() failed: kobj is not a VirtIODevice"); SystemError::EINVAL })?; let vendor = dev.vendor(); diff --git a/kernel/src/driver/virtio/transport_mmio.rs b/kernel/src/driver/virtio/transport_mmio.rs index 435f90fc..0ee3864d 100644 --- a/kernel/src/driver/virtio/transport_mmio.rs +++ b/kernel/src/driver/virtio/transport_mmio.rs @@ -2,6 +2,7 @@ use core::ptr::NonNull; use alloc::sync::Arc; use fdt::node::FdtNode; +use log::info; use system_error::SystemError; use virtio_drivers::transport::{ mmio::{MmioTransport, VirtIOHeader}, @@ -54,7 +55,7 @@ impl VirtIOMmioTransport { match unsafe { MmioTransport::new(header) } { Ok(mmio_transport) => { - kinfo!( "Detected virtio MMIO device with vendor id {:#X}, device type {:?}, version {:?}, hw irq: {}", + info!( "Detected virtio MMIO device with vendor id {:#X}, device type {:?}, version {:?}, hw irq: {}", mmio_transport.vendor_id(), mmio_transport.device_type(), mmio_transport.version(), @@ -69,7 +70,7 @@ impl VirtIOMmioTransport { }) } Err(_) => { - // kwarn!("MmioTransport::new failed: {:?}", e); + // warn!("MmioTransport::new failed: {:?}", e); Err(SystemError::EINVAL) } } diff --git a/kernel/src/driver/virtio/transport_pci.rs b/kernel/src/driver/virtio/transport_pci.rs index 071f7edd..88f4fcab 100644 --- a/kernel/src/driver/virtio/transport_pci.rs +++ b/kernel/src/driver/virtio/transport_pci.rs @@ -211,7 +211,7 @@ impl PciTransport { notify_off_multiplier, )); } - //kdebug!("notify.offset={},notify.length={}",notify_cfg.offset,notify_cfg.length); + //debug!("notify.offset={},notify.length={}",notify_cfg.offset,notify_cfg.length); let notify_region = get_bar_region_slice::<_>(&device.standard_device_bar, ¬ify_cfg)?; let isr_status = get_bar_region::<_>( &device.standard_device_bar, @@ -532,7 +532,7 @@ fn get_bar_region( { return Err(VirtioPciError::BarOffsetOutOfRange); } - //kdebug!("Chossed bar ={},used={}",struct_info.bar,struct_info.offset + struct_info.length); + //debug!("Chossed bar ={},used={}",struct_info.bar,struct_info.offset + struct_info.length); let vaddr = (bar_info .virtual_address() .ok_or(VirtioPciError::BarGetVaddrFailed)?) diff --git a/kernel/src/driver/virtio/virtio.rs b/kernel/src/driver/virtio/virtio.rs index 4314edbe..9253542e 100644 --- a/kernel/src/driver/virtio/virtio.rs +++ b/kernel/src/driver/virtio/virtio.rs @@ -10,10 +10,11 @@ use crate::driver::pci::pci::{ }; use crate::driver::virtio::transport::VirtIOTransport; use crate::libs::rwlock::RwLockWriteGuard; -use crate::{kdebug, kerror, kwarn}; + use alloc::sync::Arc; use alloc::vec::Vec; use alloc::{boxed::Box, collections::LinkedList}; +use log::{debug, error, warn}; use virtio_drivers::transport::{DeviceType, Transport}; ///@brief 寻找并加载所有virtio设备的驱动(目前只有virtio-net,但其他virtio设备也可添加) @@ -32,7 +33,7 @@ fn virtio_probe_pci() { let dev_id = DeviceId::new(None, Some(format!("{dev_id}"))).unwrap(); match PciTransport::new::(virtio_device, dev_id.clone()) { Ok(mut transport) => { - kdebug!( + debug!( "Detected virtio PCI device with device type {:?}, features {:#018x}", transport.device_type(), transport.read_device_features(), @@ -41,7 +42,7 @@ fn virtio_probe_pci() { virtio_device_init(transport, dev_id); } Err(err) => { - kerror!("Pci transport create failed because of error: {}", err); + error!("Pci transport create failed because of error: {}", err); } } } @@ -52,14 +53,14 @@ pub(super) fn virtio_device_init(transport: VirtIOTransport, dev_id: Arc virtio_blk(transport, dev_id), DeviceType::GPU => { - kwarn!("Not support virtio_gpu device for now"); + warn!("Not support virtio_gpu device for now"); } DeviceType::Input => { - kwarn!("Not support virtio_input device for now"); + warn!("Not support virtio_input device for now"); } DeviceType::Network => virtio_net(transport, dev_id), t => { - kwarn!("Unrecognized virtio device: {:?}", t); + warn!("Unrecognized virtio device: {:?}", t); } } } diff --git a/kernel/src/driver/virtio/virtio_impl.rs b/kernel/src/driver/virtio/virtio_impl.rs index 92aa07cc..256b40eb 100644 --- a/kernel/src/driver/virtio/virtio_impl.rs +++ b/kernel/src/driver/virtio/virtio_impl.rs @@ -90,7 +90,7 @@ unsafe impl Hal for HalImpl { _direction: BufferDirection, ) -> virtio_drivers::PhysAddr { let vaddr = VirtAddr::new(buffer.as_ptr() as *mut u8 as usize); - //kdebug!("virt:{:x}", vaddr); + //debug!("virt:{:x}", vaddr); // Nothing to do, as the host already has access to all memory. return MMArch::virt_2_phys(vaddr).unwrap().data(); } diff --git a/kernel/src/exception/handle.rs b/kernel/src/exception/handle.rs index fcfea1e4..e39ab02a 100644 --- a/kernel/src/exception/handle.rs +++ b/kernel/src/exception/handle.rs @@ -1,6 +1,7 @@ use core::{intrinsics::unlikely, ops::BitAnd}; use alloc::sync::Arc; +use log::{debug, error, warn}; use system_error::SystemError; use crate::{ @@ -100,7 +101,7 @@ impl IrqFlowHandler for EdgeIrqHandler { fn handle(&self, irq_desc: &Arc, _trap_frame: &mut TrapFrame) { let mut desc_inner_guard: SpinLockGuard<'_, InnerIrqDesc> = irq_desc.inner(); if !irq_may_run(&desc_inner_guard) { - // kdebug!("!irq_may_run"); + // debug!("!irq_may_run"); desc_inner_guard .internal_state_mut() .insert(IrqDescState::IRQS_PENDING); @@ -109,7 +110,7 @@ impl IrqFlowHandler for EdgeIrqHandler { } if desc_inner_guard.common_data().disabled() { - // kdebug!("desc_inner_guard.common_data().disabled()"); + // debug!("desc_inner_guard.common_data().disabled()"); desc_inner_guard .internal_state_mut() .insert(IrqDescState::IRQS_PENDING); @@ -123,7 +124,7 @@ impl IrqFlowHandler for EdgeIrqHandler { loop { if unlikely(desc_inner_guard.actions().is_empty()) { - kdebug!("no action for irq {}", irq_data.irq().data()); + debug!("no action for irq {}", irq_data.irq().data()); irq_manager().mask_irq(&irq_data); return; } @@ -136,12 +137,12 @@ impl IrqFlowHandler for EdgeIrqHandler { { let status = desc_inner_guard.common_data().status(); if !status.disabled() && status.masked() { - // kdebug!("re-enable irq"); + // debug!("re-enable irq"); irq_manager().unmask_irq(&desc_inner_guard); } } - // kdebug!("handle_irq_event"); + // debug!("handle_irq_event"); desc_inner_guard = handle_irq_event(irq_desc, desc_inner_guard); @@ -268,7 +269,7 @@ fn do_handle_irq_event(desc: &Arc) -> Result<(), SystemError> { for action in actions { let mut action_inner: SpinLockGuard<'_, InnerIrqAction> = action.inner(); - // kdebug!("do_handle_irq_event: action: {:?}", action_inner.name()); + // debug!("do_handle_irq_event: action: {:?}", action_inner.name()); let dynamic_data = action_inner .dev_id() .clone() @@ -314,17 +315,17 @@ fn cond_unmask_eoi_irq( && desc_inner_guard.common_data().masked() && desc_inner_guard.threads_oneshot() == 0 { - kdebug!( + debug!( "eoi unmask irq {}", desc_inner_guard.irq_data().irq().data() ); chip.irq_eoi(desc_inner_guard.irq_data()); unmask_irq(desc_inner_guard.irq_data()); } else if !chip.flags().contains(IrqChipFlags::IRQCHIP_EOI_THREADED) { - kdebug!("eoi irq {}", desc_inner_guard.irq_data().irq().data()); + debug!("eoi irq {}", desc_inner_guard.irq_data().irq().data()); chip.irq_eoi(desc_inner_guard.irq_data()); } else { - kwarn!( + warn!( "irq {} eoi failed", desc_inner_guard.irq_data().irq().data() ); @@ -340,7 +341,7 @@ fn warn_no_thread(irq: IrqNumber, action_inner: &mut SpinLockGuard<'_, InnerIrqA return; } - kwarn!( + warn!( "irq {}, device {} returned IRQ_WAKE_THREAD, but no threaded handler", irq.data(), action_inner.name() @@ -402,7 +403,7 @@ impl IrqFlowHandler for PerCpuDevIdIrqHandler { static ONCE: Once = Once::new(); ONCE.call_once(|| { - kerror!( + error!( "Spurious percpu irq {} on cpu {:?}, enabled: {}", irq.data(), cpu, diff --git a/kernel/src/exception/irqchip.rs b/kernel/src/exception/irqchip.rs index 93e2aa09..033f8488 100644 --- a/kernel/src/exception/irqchip.rs +++ b/kernel/src/exception/irqchip.rs @@ -5,6 +5,7 @@ use alloc::{ sync::{Arc, Weak}, vec::Vec, }; +use log::warn; use system_error::SystemError; use crate::{ @@ -433,7 +434,7 @@ impl IrqManager { * 则放弃。 */ if unlikely(is_chained) { - kwarn!( + warn!( "Chained handler for irq {} is not supported", dt.irq().data() ); @@ -453,7 +454,7 @@ impl IrqManager { &no_irq_chip(), ), ) { - kwarn!("No irq chip for irq {}", desc_inner.irq_data().irq().data()); + warn!("No irq chip for irq {}", desc_inner.irq_data().irq().data()); return; } } @@ -572,7 +573,7 @@ impl IrqHandler for ChainedActionHandler { ) -> Result { static ONCE: Once = Once::new(); ONCE.call_once(|| { - kwarn!("Chained irq {} should not call an action.", irq.data()); + warn!("Chained irq {} should not call an action.", irq.data()); }); Ok(IrqReturn::NotHandled) diff --git a/kernel/src/exception/irqdomain.rs b/kernel/src/exception/irqdomain.rs index 92267aa1..994506a2 100644 --- a/kernel/src/exception/irqdomain.rs +++ b/kernel/src/exception/irqdomain.rs @@ -6,6 +6,7 @@ use alloc::{ vec::Vec, }; use hashbrown::HashMap; +use log::{info, warn}; use system_error::SystemError; use crate::{ @@ -157,7 +158,7 @@ impl IrqDomainManager { ) { for i in 0..count { if let Err(e) = self.domain_associate(domain, first_irq + i, first_hwirq + i) { - kwarn!("domain associate failed: {:?}, domain '{:?}' didn't like hwirq {} to virq {} mapping.", e, domain.name(), (first_hwirq + i).data(), (first_irq + i).data()); + warn!("domain associate failed: {:?}, domain '{:?}' didn't like hwirq {} to virq {} mapping.", e, domain.name(), (first_hwirq + i).data(), (first_irq + i).data()); } } } @@ -172,7 +173,7 @@ impl IrqDomainManager { hwirq: HardwareIrqNumber, ) -> Result<(), SystemError> { if hwirq >= domain.revmap.read_irqsave().hwirq_max { - kwarn!( + warn!( "hwirq {} is out of range for domain {:?}", hwirq.data(), domain.name() @@ -182,12 +183,12 @@ impl IrqDomainManager { let irq_data = irq_desc_manager() .lookup(irq) .ok_or_else(|| { - kwarn!("irq_desc not found for irq {}", irq.data()); + warn!("irq_desc not found for irq {}", irq.data()); SystemError::EINVAL })? .irq_data(); if irq_data.domain().is_some() { - kwarn!( + warn!( "irq {} is already associated with domain {:?}", irq.data(), irq_data.domain().unwrap().name() @@ -203,7 +204,7 @@ impl IrqDomainManager { if let Err(e) = r { if e != SystemError::ENOSYS { if e != SystemError::EPERM { - kinfo!("domain associate failed: {:?}, domain '{:?}' didn't like hwirq {} to virq {} mapping.", e, domain.name(), hwirq.data(), irq.data()); + info!("domain associate failed: {:?}, domain '{:?}' didn't like hwirq {} to virq {} mapping.", e, domain.name(), hwirq.data(), irq.data()); } let mut irq_data_guard = irq_data.inner(); irq_data_guard.set_domain(None); @@ -246,7 +247,7 @@ impl IrqDomainManager { /// 这是调用 domain_ops->activate 以编程中断控制器的第二步,以便中断实际上可以被传递。 pub fn activate_irq(&self, irq_data: &Arc, reserve: bool) -> Result<(), SystemError> { let mut r = Ok(()); - // kdebug!( + // debug!( // "activate_irq: irq_data.common_data().status().is_activated()={}", // irq_data.common_data().status().is_activated() // ); @@ -270,9 +271,9 @@ impl IrqDomainManager { let mut r = Ok(()); if let Some(irq_data) = irq_data { - // kdebug!("do_activate_irq: irq_data={:?}", irq_data); + // debug!("do_activate_irq: irq_data={:?}", irq_data); if let Some(domain) = irq_data.domain() { - // kdebug!("do_activate_irq: domain={:?}", domain.name()); + // debug!("do_activate_irq: domain={:?}", domain.name()); let parent_data = irq_data.parent_data().and_then(|x| x.upgrade()); if let Some(parent_data) = parent_data.clone() { r = self.do_activate_irq(Some(parent_data), reserve); diff --git a/kernel/src/exception/manage.rs b/kernel/src/exception/manage.rs index 80a63249..85a47b33 100644 --- a/kernel/src/exception/manage.rs +++ b/kernel/src/exception/manage.rs @@ -2,6 +2,7 @@ use core::ops::{BitXor, Deref, DerefMut}; use alloc::{string::String, sync::Arc}; +use log::{debug, error, warn}; use system_error::SystemError; use crate::{ @@ -135,7 +136,7 @@ impl IrqManager { } let desc = irq_desc_manager().lookup(irq).ok_or(SystemError::EINVAL)?; if !desc.can_request() { - kwarn!("desc {} can not request", desc.irq().data()); + warn!("desc {} can not request", desc.irq().data()); return Err(SystemError::EINVAL); } @@ -155,7 +156,7 @@ impl IrqManager { *action_guard.flags_mut() = flags; *action_guard.dev_id_mut() = dev_id; drop(action_guard); - kdebug!("to inner_setup_irq"); + debug!("to inner_setup_irq"); return self.inner_setup_irq(irq, irqaction, desc); } @@ -215,7 +216,7 @@ impl IrqManager { .flags() .contains(IrqHandleFlags::IRQF_PROBE_SHARED) { - kerror!("Flags mismatch for irq {} (name: {}, flags: {:?}). old action name: {}, old flags: {:?}", irq.data(), action_guard.name(), action_guard.flags(), old_action_guard.name(), old_action_guard.flags()); + error!("Flags mismatch for irq {} (name: {}, flags: {:?}). old action name: {}, old flags: {:?}", irq.data(), action_guard.name(), action_guard.flags(), old_action_guard.name(), old_action_guard.flags()); } return err_out_unlock( SystemError::EBUSY, @@ -300,7 +301,7 @@ impl IrqManager { // 如果当前中断线上还没有irqaction, 则先为中断线申请资源 if desc.actions().is_empty() { if let Err(e) = self.irq_request_resources(desc.clone()) { - kerror!( + error!( "Failed to request resources for {} (irq {}) on irqchip {}, error {:?}", action_guard.name(), irq.data(), @@ -329,7 +330,7 @@ impl IrqManager { .internal_state() .contains(IrqDescState::IRQS_NMI) { - kerror!( + error!( "Invalid attempt to share NMI for {} (irq {}) on irqchip {}", action_guard.name(), irq.data(), @@ -370,7 +371,7 @@ impl IrqManager { || ((old_guard.flags().bitxor(*action_guard.flags())) .contains(IrqHandleFlags::IRQF_ONESHOT)) { - kdebug!( + debug!( "Flags mismatch for irq {} (name: {}, flags: {:?}). old action name: {}, old flags: {:?}", irq.data(), action_guard.name(), @@ -392,7 +393,7 @@ impl IrqManager { if *old_guard.flags() & IrqHandleFlags::IRQF_PERCPU != *action_guard.flags() & IrqHandleFlags::IRQF_PERCPU { - kdebug!( + debug!( "Per-cpu mismatch for irq {} (name: {}, flags: {:?})", irq.data(), action_guard.name(), @@ -429,7 +430,7 @@ impl IrqManager { // 因为我们不能确定这个中断实际上具有什么类型。 // 由于底层芯片实现可能会覆盖它们,所以类型标志并不可靠. - kerror!( + error!( "Requesting irq {} without a handler, and ONESHOT flags not set for irqaction: {}", irq.data(), action_guard.name() @@ -451,7 +452,7 @@ impl IrqManager { if let Err(e) = self.do_set_irq_trigger(desc.clone(), &mut desc_inner_guard, trigger_type) { - kdebug!( + debug!( "Failed to set trigger type for irq {} (name: {}, flags: {:?}), error {:?}", irq.data(), action_guard.name(), @@ -467,10 +468,10 @@ impl IrqManager { )); } } - kdebug!("to irq_activate"); + debug!("to irq_activate"); // 激活中断。这种激活必须独立于IRQ_NOAUTOEN进行*desc_inner_guard.internal_state_mut() |= IrqDescState::IRQS_NOREQUEST;uest. if let Err(e) = self.irq_activate(&desc, &mut desc_inner_guard) { - kdebug!( + debug!( "Failed to activate irq {} (name: {}, flags: {:?}), error {:?}", irq.data(), action_guard.name(), @@ -537,7 +538,7 @@ impl IrqManager { static mut WARNED: bool = false; if action_guard.flags().contains(IrqHandleFlags::IRQF_SHARED) && unsafe { !WARNED } { - kwarn!( + warn!( "Shared interrupt {} for {} requested but not auto enabled", irq.data(), action_guard.name() @@ -551,7 +552,7 @@ impl IrqManager { let new_trigger_type = action_guard.flags().trigger_type(); let old_trigger_type = desc_inner_guard.common_data().trigger_type(); if new_trigger_type != old_trigger_type { - kwarn!("Irq {} uses trigger type: {old_trigger_type:?}, but requested trigger type: {new_trigger_type:?}.", irq.data()); + warn!("Irq {} uses trigger type: {old_trigger_type:?}, but requested trigger type: {new_trigger_type:?}.", irq.data()); } } @@ -612,7 +613,7 @@ impl IrqManager { .thread_completion() .wait_for_completion() .map_err(|e| { - kwarn!( + warn!( "Failed to wait for irq thread ready for {} (irq {:?}), error {:?}", action.inner().name(), desc.irq_data().irq(), @@ -628,7 +629,7 @@ impl IrqManager { desc_inner_guard: &mut SpinLockGuard<'_, InnerIrqDesc>, resend: bool, ) -> Result<(), SystemError> { - kdebug!( + debug!( "irq_activate_and_startup: irq: {}, name: {:?}", desc.irq().data(), desc_inner_guard.name() @@ -659,7 +660,7 @@ impl IrqManager { resend: bool, force: bool, ) -> Result<(), SystemError> { - kdebug!( + debug!( "irq_startup: irq: {}, name: {:?}", desc_inner_guard.irq_data().irq().data(), desc_inner_guard.name() @@ -710,7 +711,7 @@ impl IrqManager { if resend { if let Err(e) = self.irq_check_and_resend(desc_inner_guard, false) { - kerror!( + error!( "Failed to check and resend irq {}, error {:?}", irq_data.irq().data(), e @@ -734,7 +735,7 @@ impl IrqManager { if e == SystemError::ENOSYS { self.unmask_irq(desc_inner_guard); } - kerror!( + error!( "Failed to enable irq {} (name: {:?}), error {:?}", desc_inner_guard.irq_data().irq().data(), desc_inner_guard.name(), @@ -930,7 +931,7 @@ impl IrqManager { let mut to_unmask = false; if !chip.can_set_flow_type() { - // kdebug!( + // debug!( // "No set_irq_type function for irq {}, chip {}", // desc_inner_guard.irq_data().irq().data(), // chip.name() @@ -979,7 +980,7 @@ impl IrqManager { ret = Ok(()); } else { - kerror!( + error!( "Failed to set irq {} trigger type to {:?} on irqchip {}, error {:?}", desc_inner_guard.irq_data().irq().data(), trigger_type, @@ -1059,7 +1060,7 @@ impl IrqManager { if let Err(e) = r { if e != SystemError::ENOSYS { - kerror!( + error!( "Failed to unmask irq {} on irqchip {}, error {:?}", desc_inner_guard.irq_data().irq().data(), desc_inner_guard @@ -1100,7 +1101,7 @@ impl IrqManager { /// /// 参考 https://code.dragonos.org.cn/xref/linux-6.6.21/kernel/irq/manage.c#2026 pub fn free_irq(&self, _irq: IrqNumber, _dev_id: Option>) { - kwarn!("Unimplemented free_irq"); + warn!("Unimplemented free_irq"); } } @@ -1138,7 +1139,7 @@ impl IrqHandler for IrqNestedPrimaryHandler { _static_data: Option<&dyn IrqHandlerData>, _dynamic_data: Option>, ) -> Result { - kwarn!("Primary handler called for nested irq {}", irq.data()); + warn!("Primary handler called for nested irq {}", irq.data()); return Ok(IrqReturn::NotHandled); } } diff --git a/kernel/src/exception/softirq.rs b/kernel/src/exception/softirq.rs index 06e882e8..f7d9513a 100644 --- a/kernel/src/exception/softirq.rs +++ b/kernel/src/exception/softirq.rs @@ -7,13 +7,13 @@ use core::{ }; use alloc::{boxed::Box, sync::Arc, vec::Vec}; +use log::{debug, info}; use num_traits::FromPrimitive; use system_error::SystemError; use crate::{ arch::CurrentIrqArch, exception::InterruptArch, - kdebug, kinfo, libs::rwlock::RwLock, mm::percpu::{PerCpu, PerCpuVar}, process::ProcessManager, @@ -35,7 +35,7 @@ pub extern "C" fn rs_softirq_init() { #[inline(never)] pub fn softirq_init() -> Result<(), SystemError> { - kinfo!("Initializing softirq..."); + info!("Initializing softirq..."); unsafe { __SORTIRQ_VECTORS = Box::leak(Box::new(Softirq::new())); __CPU_PENDING = Some(Box::new( @@ -46,7 +46,7 @@ pub fn softirq_init() -> Result<(), SystemError> { cpu_pending[i as usize] = VecStatus::default(); } } - kinfo!("Softirq initialized."); + info!("Softirq initialized."); return Ok(()); } @@ -143,20 +143,20 @@ impl Softirq { softirq_num: SoftirqNumber, handler: Arc, ) -> Result { - // kdebug!("register_softirq softirq_num = {:?}", softirq_num as u64); + // debug!("register_softirq softirq_num = {:?}", softirq_num as u64); // let self = &mut SOFTIRQ_VECTORS.lock(); // 判断该软中断向量是否已经被注册 let mut table_guard = self.table.write_irqsave(); if table_guard[softirq_num as usize].is_some() { - // kdebug!("register_softirq failed"); + // debug!("register_softirq failed"); return Err(SystemError::EINVAL); } table_guard[softirq_num as usize] = Some(handler); drop(table_guard); - // kdebug!( + // debug!( // "register_softirq successfully, softirq_num = {:?}", // softirq_num as u64 // ); @@ -169,7 +169,7 @@ impl Softirq { /// @param irq_num 中断向量号码 #[allow(dead_code)] pub fn unregister_softirq(&self, softirq_num: SoftirqNumber) { - // kdebug!("unregister_softirq softirq_num = {:?}", softirq_num as u64); + // debug!("unregister_softirq softirq_num = {:?}", softirq_num as u64); let mut table_guard = self.table.write_irqsave(); // 将软中断向量清空 table_guard[softirq_num as usize] = None; @@ -219,7 +219,7 @@ impl Softirq { softirq_func.as_ref().unwrap().run(); if unlikely(prev_count != ProcessManager::current_pcb().preempt_count()) { - kdebug!( + debug!( "entered softirq {:?} with preempt_count {:?},exited with {:?}", i, prev_count, @@ -255,7 +255,7 @@ impl Softirq { compiler_fence(Ordering::SeqCst); drop(guard); - // kdebug!("raise_softirq exited"); + // debug!("raise_softirq exited"); } #[allow(dead_code)] diff --git a/kernel/src/exception/sysfs.rs b/kernel/src/exception/sysfs.rs index 390e65a9..1e499bf5 100644 --- a/kernel/src/exception/sysfs.rs +++ b/kernel/src/exception/sysfs.rs @@ -1,4 +1,5 @@ use alloc::{string::ToString, sync::Arc}; +use log::warn; use system_error::SystemError; use unified_init::macros::unified_init; @@ -117,7 +118,7 @@ fn irq_sysfs_add(irq: &IrqNumber, desc: &Arc) { let kset = sys_kernel_irq_kset(); KObjectManager::add_kobj(desc.clone() as Arc, Some(kset)).unwrap_or_else(|e| { - kwarn!("Failed to add irq({irq:?}) kobject to sysfs: {:?}", e); + warn!("Failed to add irq({irq:?}) kobject to sysfs: {:?}", e); }); desc.mark_in_sysfs(); diff --git a/kernel/src/filesystem/devfs/mod.rs b/kernel/src/filesystem/devfs/mod.rs index 2a3ffd2e..92f602a2 100644 --- a/kernel/src/filesystem/devfs/mod.rs +++ b/kernel/src/filesystem/devfs/mod.rs @@ -11,7 +11,6 @@ use super::vfs::{ }; use crate::{ driver::base::device::device_number::DeviceNumber, - kerror, kinfo, libs::{ once::Once, spinlock::{SpinLock, SpinLockGuard}, @@ -24,6 +23,7 @@ use alloc::{ sync::{Arc, Weak}, vec::Vec, }; +use log::{error, info}; use system_error::SystemError; const DEVFS_BLOCK_SIZE: u64 = 512; @@ -97,7 +97,7 @@ impl DevFS { .expect("DevFS: Failed to create /dev/block"); devfs.register_bultinin_device(); - // kdebug!("ls /dev: {:?}", root.list()); + // debug!("ls /dev: {:?}", root.list()); return devfs; } @@ -541,7 +541,7 @@ impl IndexNode for LockedDevFSInode { _buf: &mut [u8], _data: SpinLockGuard, ) -> Result { - kerror!("DevFS: read_at is not supported!"); + error!("DevFS: read_at is not supported!"); Err(SystemError::ENOSYS) } @@ -580,7 +580,7 @@ macro_rules! devfs_exact_ref { () => {{ let devfs_inode: Result, SystemError> = ROOT_INODE().find("dev"); if let Err(e) = devfs_inode { - kerror!("failed to get DevFS ref. errcode = {:?}", e); + error!("failed to get DevFS ref. errcode = {:?}", e); return Err(SystemError::ENOENT); } @@ -611,7 +611,7 @@ pub fn devfs_init() -> Result<(), SystemError> { static INIT: Once = Once::new(); let mut result = None; INIT.call_once(|| { - kinfo!("Initializing DevFS..."); + info!("Initializing DevFS..."); // 创建 devfs 实例 let devfs: Arc = DevFS::new(); // devfs 挂载 @@ -620,7 +620,7 @@ pub fn devfs_init() -> Result<(), SystemError> { .expect("Unabled to find /dev") .mount(devfs) .expect("Failed to mount at /dev"); - kinfo!("DevFS mounted."); + info!("DevFS mounted."); result = Some(Ok(())); }); diff --git a/kernel/src/filesystem/devpts/mod.rs b/kernel/src/filesystem/devpts/mod.rs index 1fc57f5c..c019d81a 100644 --- a/kernel/src/filesystem/devpts/mod.rs +++ b/kernel/src/filesystem/devpts/mod.rs @@ -7,6 +7,7 @@ use alloc::{ vec::Vec, }; use ida::IdAllocator; +use log::info; use system_error::SystemError; use unified_init::macros::unified_init; @@ -278,7 +279,7 @@ pub fn devpts_init() -> Result<(), SystemError> { let ptsfs: Arc = DevPtsFs::new(); do_mount_mkdir(ptsfs, "/dev/pts").expect("Failed to mount DevPtsFS"); - kinfo!("DevPtsFs mounted."); + info!("DevPtsFs mounted."); Ok(()) } diff --git a/kernel/src/filesystem/fat/bpb.rs b/kernel/src/filesystem/fat/bpb.rs index 1c7b8cc7..2f8d6ec7 100644 --- a/kernel/src/filesystem/fat/bpb.rs +++ b/kernel/src/filesystem/fat/bpb.rs @@ -1,10 +1,10 @@ #![allow(dead_code)] use alloc::sync::Arc; +use log::error; use system_error::SystemError; use crate::{ driver::base::block::{block_device::LBA_SIZE, disk_info::Partition, SeekFrom}, - kerror, libs::vec_cursor::VecCursor, }; @@ -190,27 +190,27 @@ impl BiosParameterBlockFAT32 { /// @brief 验证BPB32的信息是否合法 fn validate(&self, bpb: &BiosParameterBlock) -> Result<(), SystemError> { if bpb.fat_size_16 != 0 { - kerror!("Invalid fat_size_16 value in BPB (should be zero for FAT32)"); + error!("Invalid fat_size_16 value in BPB (should be zero for FAT32)"); return Err(SystemError::EINVAL); } if bpb.root_entries_cnt != 0 { - kerror!("Invalid root_entries value in BPB (should be zero for FAT32)"); + error!("Invalid root_entries value in BPB (should be zero for FAT32)"); return Err(SystemError::EINVAL); } if bpb.total_sectors_16 != 0 { - kerror!("Invalid total_sectors_16 value in BPB (should be zero for FAT32)"); + error!("Invalid total_sectors_16 value in BPB (should be zero for FAT32)"); return Err(SystemError::EINVAL); } if self.fat_size_32 == 0 { - kerror!("Invalid fat_size_32 value in BPB (should be non-zero for FAT32)"); + error!("Invalid fat_size_32 value in BPB (should be non-zero for FAT32)"); return Err(SystemError::EINVAL); } if self.fs_version != 0 { - kerror!("Unknown FAT FS version"); + error!("Unknown FAT FS version"); return Err(SystemError::EINVAL); } @@ -315,28 +315,28 @@ impl BiosParameterBlock { pub fn validate(&self) -> Result<(), SystemError> { // 校验每扇区字节数是否合法 if self.bytes_per_sector.count_ones() != 1 { - kerror!("Invalid bytes per sector(not a power of 2)"); + error!("Invalid bytes per sector(not a power of 2)"); return Err(SystemError::EINVAL); } else if self.bytes_per_sector < 512 { - kerror!("Invalid bytes per sector (value < 512)"); + error!("Invalid bytes per sector (value < 512)"); return Err(SystemError::EINVAL); } else if self.bytes_per_sector > 4096 { - kerror!("Invalid bytes per sector (value > 4096)"); + error!("Invalid bytes per sector (value > 4096)"); return Err(SystemError::EINVAL); } if self.rsvd_sec_cnt < 1 { - kerror!("Invalid rsvd_sec_cnt value in BPB"); + error!("Invalid rsvd_sec_cnt value in BPB"); return Err(SystemError::EINVAL); } if self.num_fats == 0 { - kerror!("Invalid fats value in BPB"); + error!("Invalid fats value in BPB"); return Err(SystemError::EINVAL); } if (self.total_sectors_16 == 0) && (self.total_sectors_32 == 0) { - kerror!("Invalid BPB (total_sectors_16 or total_sectors_32 should be non-zero)"); + error!("Invalid BPB (total_sectors_16 or total_sectors_32 should be non-zero)"); return Err(SystemError::EINVAL); } @@ -367,7 +367,7 @@ impl BiosParameterBlock { // 总扇区数应当大于第一个数据扇区的扇区号 if total_sectors <= first_data_sector { - kerror!("Total sectors lesser than first data sector"); + error!("Total sectors lesser than first data sector"); return Err(SystemError::EINVAL); } diff --git a/kernel/src/filesystem/fat/entry.rs b/kernel/src/filesystem/fat/entry.rs index 322486ae..4b79ce7c 100644 --- a/kernel/src/filesystem/fat/entry.rs +++ b/kernel/src/filesystem/fat/entry.rs @@ -1,10 +1,10 @@ #![allow(dead_code)] use core::{cmp::min, intrinsics::unlikely}; +use log::{debug, warn}; use system_error::SystemError; use crate::{ driver::base::block::{block_device::LBA_SIZE, SeekFrom}, - kwarn, libs::vec_cursor::VecCursor, }; use alloc::{ @@ -265,7 +265,7 @@ impl FATFile { let last_cluster = if let Some(c) = fs.get_last_cluster(self.first_cluster) { c } else { - kwarn!("FAT: last cluster not found, File = {self:?}"); + warn!("FAT: last cluster not found, File = {self:?}"); return Err(SystemError::EINVAL); }; // 申请簇 @@ -450,7 +450,7 @@ impl FATDir { free += 1; if free == num_free { - // kdebug!("first_free = {first_free:?}, current_free = ({current_cluster:?}, {offset})"); + // debug!("first_free = {first_free:?}, current_free = ({current_cluster:?}, {offset})"); return Ok(first_free); } } @@ -472,7 +472,7 @@ impl FATDir { / fs.bytes_per_cluster(); let mut first_cluster = Cluster::default(); let mut prev_cluster = current_cluster; - // kdebug!( + // debug!( // "clusters_required={clusters_required}, prev_cluster={prev_cluster:?}, free ={free}" // ); // 申请簇 @@ -592,7 +592,7 @@ impl FATDir { pub fn create_dir(&self, name: &str, fs: &Arc) -> Result { let r: Result = self.check_existence(name, Some(true), fs.clone()); - // kdebug!("check existence ok"); + // debug!("check existence ok"); // 检查错误码,如果能够表明目录项已经存在,则返回-EEXIST if let Err(err_val) = r { if err_val == (SystemError::EISDIR) || err_val == (SystemError::ENOTDIR) { @@ -639,7 +639,7 @@ impl FATDir { dot_dot_entry.flush(fs, fs.cluster_bytes_offset(first_cluster) + offset)?; - // kdebug!("to create dentries"); + // debug!("to create dentries"); // 在当前目录下创建目标目录项 let res = self .create_dir_entries( @@ -652,7 +652,7 @@ impl FATDir { fs.clone(), ) .map(|e| e.to_dir())?; - // kdebug!("create dentries ok"); + // debug!("create dentries ok"); return res; } FATDirEntryOrShortName::DirEntry(_) => { @@ -732,7 +732,7 @@ impl FATDir { LongNameEntryGenerator::new(long_name, short_dentry.checksum()); let num_entries = long_name_gen.num_entries() as u64; - // kdebug!("to find free entries"); + // debug!("to find free entries"); let free_entries: Option<(Cluster, u64)> = self.find_free_entries(num_entries, fs.clone())?; // 目录项开始位置 @@ -1119,7 +1119,7 @@ impl LongDirEntry { | '^' | '#' | '&' => {} '+' | ',' | ';' | '=' | '[' | ']' | '.' | ' ' => {} _ => { - kdebug!("error char: {}", c); + debug!("error char: {}", c); return Err(SystemError::EILSEQ); } } @@ -1574,7 +1574,7 @@ impl FATDirIter { } } } - // kdebug!("collect dentries done. long_name_entries={long_name_entries:?}"); + // debug!("collect dentries done. long_name_entries={long_name_entries:?}"); let dir_entry: Result = FATDirEntry::new( long_name_entries, ( @@ -1582,16 +1582,16 @@ impl FATDirIter { (self.current_cluster, self.offset), ), ); - // kdebug!("dir_entry={:?}", dir_entry); + // debug!("dir_entry={:?}", dir_entry); match dir_entry { Ok(d) => { - // kdebug!("dir_entry ok"); + // debug!("dir_entry ok"); self.offset += FATRawDirEntry::DIR_ENTRY_LEN; return Ok((self.current_cluster, self.offset, Some(d))); } Err(_) => { - // kdebug!("dir_entry err, e={}", e); + // debug!("dir_entry err, e={}", e); self.offset += FATRawDirEntry::DIR_ENTRY_LEN; } } @@ -2411,7 +2411,7 @@ pub fn get_raw_dir_entry( // let step1 = fs.get_in_partition_bytes_offset(in_disk_bytes_offset); // let step2 = fs.bytes_to_sector(step1); // let lba = fs.get_lba_from_offset(step2); - // kdebug!("step1={step1}, step2={step2}, lba={lba}"); + // debug!("step1={step1}, step2={step2}, lba={lba}"); let mut v: Vec = vec![0; LBA_SIZE]; fs.partition.disk().read_at(lba, 1, &mut v)?; diff --git a/kernel/src/filesystem/fat/fs.rs b/kernel/src/filesystem/fat/fs.rs index df6af8ce..11febb29 100644 --- a/kernel/src/filesystem/fat/fs.rs +++ b/kernel/src/filesystem/fat/fs.rs @@ -2,6 +2,7 @@ use alloc::string::ToString; use core::cmp::Ordering; use core::intrinsics::unlikely; use core::{any::Any, fmt::Debug}; +use log::error; use system_error::SystemError; use alloc::{ @@ -23,7 +24,6 @@ use crate::{ syscall::ModeType, FileSystem, FileType, IndexNode, InodeId, Metadata, }, - kerror, libs::{ spinlock::{SpinLock, SpinLockGuard}, vec_cursor::VecCursor, @@ -131,7 +131,7 @@ impl FATInode { self.metadata.size = d.size(&self.fs.upgrade().unwrap().clone()) as i64; } FATDirEntry::UnInit => { - kerror!("update_metadata: Uninitialized FATDirEntry: {:?}", self); + error!("update_metadata: Uninitialized FATDirEntry: {:?}", self); return; } }; @@ -309,7 +309,7 @@ impl FATFileSystem { match bpb.fat_type { FATType::FAT32(x) => x.fat_size_32 as u64, _ => { - kerror!("FAT12 and FAT16 volumes should have non-zero BPB_FATSz16"); + error!("FAT12 and FAT16 volumes should have non-zero BPB_FATSz16"); return Err(SystemError::EINVAL); } } @@ -457,7 +457,7 @@ impl FATFileSystem { match entry { _n if (0x0ffffff7..=0x0fffffff).contains(¤t_cluster) => { // 当前簇号不是一个能被获得的簇(可能是文件系统出错了) - kerror!("FAT32 get fat entry: current cluster number [{}] is not an allocatable cluster number.", current_cluster); + error!("FAT32 get fat entry: current cluster number [{}] is not an allocatable cluster number.", current_cluster); FATEntry::Bad } 0 => FATEntry::Unused, @@ -613,7 +613,7 @@ impl FATFileSystem { // 如果这个空闲簇不是簇链的第一个簇,那么把当前簇跟前一个簇连上。 if let Some(prev_cluster) = prev_cluster { - // kdebug!("set entry, prev ={prev_cluster:?}, next = {free_cluster:?}"); + // debug!("set entry, prev ={prev_cluster:?}, next = {free_cluster:?}"); self.set_entry(prev_cluster, FATEntry::Next(free_cluster))?; } // 清空新获取的这个簇 @@ -647,7 +647,7 @@ impl FATFileSystem { return Ok(()); } else { // 不能释放坏簇 - kerror!("Bad clusters cannot be freed."); + error!("Bad clusters cannot be freed."); return Err(SystemError::EFAULT); } } @@ -1136,14 +1136,14 @@ impl FATFileSystem { } else { self.bpb.num_fats as u64 }; - // kdebug!("set entry, bound={bound}, fat_size={fat_size}"); + // debug!("set entry, bound={bound}, fat_size={fat_size}"); for i in 0..bound { // 当前操作的FAT表在磁盘上的字节偏移量 let f_offset: u64 = fat_part_bytes_offset + i * fat_size; let in_block_offset: u64 = self.get_in_block_offset(f_offset); let lba = self.get_lba_from_offset(self.bytes_to_sector(f_offset)); - // kdebug!("set entry, lba={lba}, in_block_offset={in_block_offset}"); + // debug!("set entry, lba={lba}, in_block_offset={in_block_offset}"); let mut v: Vec = vec![0; LBA_SIZE]; self.partition.disk().read_at(lba, 1, &mut v)?; @@ -1157,7 +1157,7 @@ impl FATFileSystem { && cluster.cluster_num >= 0x0ffffff7 && cluster.cluster_num <= 0x0fffffff { - kerror!( + error!( "FAT32: Reserved Cluster {:?} cannot be marked as free", cluster ); @@ -1175,7 +1175,7 @@ impl FATFileSystem { // 恢复保留位 raw_val |= old_bits; - // kdebug!("sent entry, raw_val={raw_val}"); + // debug!("sent entry, raw_val={raw_val}"); cursor.seek(SeekFrom::SeekSet(in_block_offset as i64))?; cursor.write_u32(raw_val)?; @@ -1206,7 +1206,7 @@ impl Drop for FATFileSystem { fn drop(&mut self) { let r = self.umount(); if r.is_err() { - kerror!( + error!( "Umount FAT filesystem failed: errno={:?}, FS detail:{self:?}", r.as_ref().unwrap_err() ); @@ -1257,7 +1257,7 @@ impl FATFsInfo { if fsinfo.is_valid() { return Ok(fsinfo); } else { - kerror!("Error occurred while parsing FATFsInfo."); + error!("Error occurred while parsing FATFsInfo."); return Err(SystemError::EINVAL); } } @@ -1395,7 +1395,7 @@ impl IndexNode for LockedFATInode { return Err(SystemError::EISDIR); } FATDirEntry::UnInit => { - kerror!("FATFS: param: Inode_type uninitialized."); + error!("FATFS: param: Inode_type uninitialized."); return Err(SystemError::EROFS); } } @@ -1421,7 +1421,7 @@ impl IndexNode for LockedFATInode { return Err(SystemError::EISDIR); } FATDirEntry::UnInit => { - kerror!("FATFS: param: Inode_type uninitialized."); + error!("FATFS: param: Inode_type uninitialized."); return Err(SystemError::EROFS); } } @@ -1455,7 +1455,7 @@ impl IndexNode for LockedFATInode { _ => return Err(SystemError::EINVAL), }, FATDirEntry::UnInit => { - kerror!("FATFS: param: Inode_type uninitialized."); + error!("FATFS: param: Inode_type uninitialized."); return Err(SystemError::EROFS); } } @@ -1509,7 +1509,7 @@ impl IndexNode for LockedFATInode { } FATDirEntry::Dir(_) => return Err(SystemError::ENOSYS), FATDirEntry::UnInit => { - kerror!("FATFS: param: Inode_type uninitialized."); + error!("FATFS: param: Inode_type uninitialized."); return Err(SystemError::EROFS); } } @@ -1542,7 +1542,7 @@ impl IndexNode for LockedFATInode { // ====== 生成inode缓存,存入B树 let name = DName::from(ent.name().to_uppercase()); - // kdebug!("name={name}"); + // debug!("name={name}"); if !guard.children.contains_key(&name) && name.as_ref() != "." @@ -1562,7 +1562,7 @@ impl IndexNode for LockedFATInode { return Ok(ret); } FATDirEntry::UnInit => { - kerror!("FATFS: param: Inode_type uninitialized."); + error!("FATFS: param: Inode_type uninitialized."); return Err(SystemError::EROFS); } } @@ -1608,7 +1608,7 @@ impl IndexNode for LockedFATInode { } FATDirEntry::Dir(d) => d, FATDirEntry::UnInit => { - kerror!("FATFS: param: Inode_type uninitialized."); + error!("FATFS: param: Inode_type uninitialized."); return Err(SystemError::EROFS); } }; @@ -1635,7 +1635,7 @@ impl IndexNode for LockedFATInode { } FATDirEntry::Dir(d) => d, FATDirEntry::UnInit => { - kerror!("FATFS: param: Inode_type uninitialized."); + error!("FATFS: param: Inode_type uninitialized."); return Err(SystemError::EROFS); } }; @@ -1683,7 +1683,7 @@ impl IndexNode for LockedFATInode { } FATDirEntry::Dir(d) => d, FATDirEntry::UnInit => { - kerror!("FATFS: param: Inode_type uninitialized."); + error!("FATFS: param: Inode_type uninitialized."); return Err(SystemError::EROFS); } }; @@ -1712,7 +1712,7 @@ impl IndexNode for LockedFATInode { } FATDirEntry::Dir(d) => d, FATDirEntry::UnInit => { - kerror!("FATFS: param: Inode_type uninitialized."); + error!("FATFS: param: Inode_type uninitialized."); return Err(SystemError::EROFS); } }; @@ -1722,7 +1722,7 @@ impl IndexNode for LockedFATInode { } FATDirEntry::Dir(d) => d, FATDirEntry::UnInit => { - kerror!("FATFA: param: Inode_type uninitialized."); + error!("FATFA: param: Inode_type uninitialized."); return Err(SystemError::EROFS); } }; diff --git a/kernel/src/filesystem/kernfs/mod.rs b/kernel/src/filesystem/kernfs/mod.rs index ff29cf2a..91765e57 100644 --- a/kernel/src/filesystem/kernfs/mod.rs +++ b/kernel/src/filesystem/kernfs/mod.rs @@ -6,6 +6,7 @@ use alloc::{ vec::Vec, }; use hashbrown::HashMap; +use log::warn; use system_error::SystemError; use crate::{ @@ -345,7 +346,7 @@ impl IndexNode for KernFSInode { } if self.callback.is_none() { - kwarn!("kernfs: callback is none"); + warn!("kernfs: callback is none"); return Err(SystemError::ENOSYS); } @@ -590,7 +591,7 @@ impl KernFSInode { target: &Arc, target_absolute_path: String, ) -> Result, SystemError> { - // kdebug!("kernfs add link: name:{name}, target path={target_absolute_path}"); + // debug!("kernfs add link: name:{name}, target path={target_absolute_path}"); let inode = self.inner_create( name, KernInodeType::SymLink, diff --git a/kernel/src/filesystem/mbr.rs b/kernel/src/filesystem/mbr.rs index eb3af9af..2f867536 100644 --- a/kernel/src/filesystem/mbr.rs +++ b/kernel/src/filesystem/mbr.rs @@ -4,6 +4,7 @@ use alloc::{ sync::{Arc, Weak}, vec::Vec, }; +use log::debug; use system_error::SystemError; use crate::{ @@ -105,10 +106,10 @@ impl MbrDiskPartionTable { table.dpte[i].starting_lba = cursor.read_u32()?; table.dpte[i].total_sectors = cursor.read_u32()?; - kdebug!("dpte[{i}] = {:?}", table.dpte[i]); + debug!("dpte[{i}] = {:?}", table.dpte[i]); } table.bs_trailsig = cursor.read_u16()?; - // kdebug!("bs_trailsig = {}", unsafe { + // debug!("bs_trailsig = {}", unsafe { // read_unaligned(addr_of!(table.bs_trailsig)) // }); diff --git a/kernel/src/filesystem/procfs/kmsg.rs b/kernel/src/filesystem/procfs/kmsg.rs index 79f78c0a..c2181dc8 100644 --- a/kernel/src/filesystem/procfs/kmsg.rs +++ b/kernel/src/filesystem/procfs/kmsg.rs @@ -8,6 +8,7 @@ use alloc::{borrow::ToOwned, string::ToString, vec::Vec}; use kdepends::ringbuffer::{AllocRingBuffer, RingBuffer}; +use log::info; use system_error::SystemError; /// 缓冲区容量 @@ -18,13 +19,13 @@ pub static mut KMSG: Option> = None; /// 初始化KMSG pub fn kmsg_init() { - kinfo!("kmsg_init"); + info!("kmsg_init"); let kmsg = SpinLock::new(Kmsg::new()); compiler_fence(Ordering::SeqCst); unsafe { KMSG = Some(kmsg) }; compiler_fence(Ordering::SeqCst); - kinfo!("kmsg_init done"); + info!("kmsg_init done"); } /// 日志 diff --git a/kernel/src/filesystem/procfs/mod.rs b/kernel/src/filesystem/procfs/mod.rs index 07dcd179..877cad63 100644 --- a/kernel/src/filesystem/procfs/mod.rs +++ b/kernel/src/filesystem/procfs/mod.rs @@ -1,5 +1,6 @@ use core::intrinsics::size_of; +use ::log::{error, info}; use alloc::{ borrow::ToOwned, collections::BTreeMap, @@ -17,7 +18,6 @@ use crate::{ core::{generate_inode_id, ROOT_INODE}, FileType, }, - kerror, kinfo, libs::{ once::Once, rwlock::RwLock, @@ -149,7 +149,7 @@ impl ProcFSInode { let pcb = if let Some(pcb) = pcb { pcb } else { - kerror!( + error!( "ProcFS: Cannot find pcb for pid {:?} when opening its 'status' file.", pid ); @@ -821,7 +821,7 @@ pub fn procfs_init() -> Result<(), SystemError> { static INIT: Once = Once::new(); let mut result = None; INIT.call_once(|| { - kinfo!("Initializing ProcFS..."); + info!("Initializing ProcFS..."); // 创建 procfs 实例 let procfs: Arc = ProcFS::new(); // procfs 挂载 @@ -830,7 +830,7 @@ pub fn procfs_init() -> Result<(), SystemError> { .expect("Unabled to find /proc") .mount(procfs) .expect("Failed to mount at /proc"); - kinfo!("ProcFS mounted."); + info!("ProcFS mounted."); result = Some(Ok(())); }); diff --git a/kernel/src/filesystem/sysfs/file.rs b/kernel/src/filesystem/sysfs/file.rs index 01450a8a..1d65be42 100644 --- a/kernel/src/filesystem/sysfs/file.rs +++ b/kernel/src/filesystem/sysfs/file.rs @@ -4,6 +4,7 @@ use alloc::{ string::ToString, sync::{Arc, Weak}, }; +use log::warn; use system_error::SystemError; use crate::{ @@ -16,7 +17,6 @@ use crate::{ sysfs::{SysFSOps, SysFSOpsSupport}, vfs::{syscall::ModeType, PollStatus}, }, - kwarn, }; use super::{Attribute, BinAttribute, SysFS, SysFSKernPrivateData}; @@ -130,7 +130,7 @@ impl SysFS { drop(x); let sysfs_ops: &dyn SysFSOps = kobj.kobj_type().unwrap().sysfs_ops().ok_or_else(|| { - kwarn!("missing sysfs attribute operations for kobject: {kobj:?}"); + warn!("missing sysfs attribute operations for kobject: {kobj:?}"); SystemError::EINVAL })?; @@ -184,7 +184,7 @@ impl SysFS { if let Some(parent) = parent { let r = parent.remove(attr.name()); if unlikely(r.is_err()) { - kwarn!( + warn!( "failed to remove file '{}' from '{}'", attr.name(), kobj.name() @@ -220,7 +220,7 @@ impl SysFS { if let Some(parent) = parent { let r = parent.remove(attr.name()); if unlikely(r.is_err()) { - kwarn!( + warn!( "failed to remove file '{}' from '{}'", attr.name(), kobj.name() diff --git a/kernel/src/filesystem/sysfs/group.rs b/kernel/src/filesystem/sysfs/group.rs index fb45ccb9..2fd3f397 100644 --- a/kernel/src/filesystem/sysfs/group.rs +++ b/kernel/src/filesystem/sysfs/group.rs @@ -1,6 +1,7 @@ use core::intrinsics::unlikely; use alloc::{string::ToString, sync::Arc}; +use log::{error, warn}; use system_error::SystemError; use crate::{ @@ -10,7 +11,6 @@ use crate::{ sysfs::{dir::SysKernDirPriv, sysfs_instance, SysFSKernPrivateData}, vfs::{syscall::ModeType, IndexNode}, }, - kwarn, libs::casting::DowncastArc, }; @@ -38,7 +38,7 @@ impl SysFS { continue; } if let Err(e) = self.do_create_group(kobj, group, update) { - kerror!( + error!( "Failed to create group '{}', err={e:?}", group.name().unwrap_or("") ); @@ -137,7 +137,7 @@ impl SysFS { parent_inode = inode .find(name) .map_err(|e| { - kwarn!("sysfs group '{name}' not found for kobject {kobj:?}"); + warn!("sysfs group '{name}' not found for kobject {kobj:?}"); e })? .downcast_arc() @@ -189,7 +189,7 @@ impl SysFS { } if unlikely((mode.bits() & (!0o644)) != 0) { - kwarn!( + warn!( "Attribute '{name}' has invalid mode 0{mode:o}", name = attr.name(), mode = mode @@ -204,7 +204,7 @@ impl SysFS { } if let Err(e) = e { - kerror!( + error!( "Failed to create sysfs files for group '{}', err={e:?}", group.name().unwrap_or("") ); diff --git a/kernel/src/filesystem/sysfs/mod.rs b/kernel/src/filesystem/sysfs/mod.rs index 2c2dce13..97579f00 100644 --- a/kernel/src/filesystem/sysfs/mod.rs +++ b/kernel/src/filesystem/sysfs/mod.rs @@ -9,10 +9,10 @@ use super::{ use crate::{ driver::base::kobject::KObject, filesystem::vfs::ROOT_INODE, - kinfo, kwarn, libs::{casting::DowncastArc, once::Once}, }; use alloc::sync::Arc; +use log::{info, warn}; use system_error::SystemError; pub mod dir; @@ -34,7 +34,7 @@ pub fn sysfs_init() -> Result<(), SystemError> { static INIT: Once = Once::new(); let mut result = None; INIT.call_once(|| { - kinfo!("Initializing SysFS..."); + info!("Initializing SysFS..."); // 创建 sysfs 实例 // let sysfs: Arc = OldSysFS::new(); @@ -47,9 +47,9 @@ pub fn sysfs_init() -> Result<(), SystemError> { .expect("Unabled to find /sys") .mount(sysfs_instance().fs().clone()) .expect("Failed to mount at /sys"); - kinfo!("SysFS mounted."); + info!("SysFS mounted."); - // kdebug!("sys_bus_init result: {:?}", SYS_BUS_INODE().list()); + // debug!("sys_bus_init result: {:?}", SYS_BUS_INODE().list()); result = Some(Ok(())); }); @@ -227,6 +227,6 @@ impl SysFS { /// 警告:重复的sysfs entry pub(self) fn warn_duplicate(&self, parent: &Arc, name: &str) { let path = self.kernfs_path(parent); - kwarn!("duplicate sysfs entry: {path}/{name}"); + warn!("duplicate sysfs entry: {path}/{name}"); } } diff --git a/kernel/src/filesystem/sysfs/symlink.rs b/kernel/src/filesystem/sysfs/symlink.rs index f9fb2712..66e4b33e 100644 --- a/kernel/src/filesystem/sysfs/symlink.rs +++ b/kernel/src/filesystem/sysfs/symlink.rs @@ -72,7 +72,7 @@ impl SysFS { let target_abs_path = "/sys".to_string() + &self.kernfs_path(&target_inode).to_owned(); // let current_path = self.kernfs_path(inode); - // kdebug!("sysfs: create link {} to {}", current_path, target_abs_path); + // debug!("sysfs: create link {} to {}", current_path, target_abs_path); let kn = inode.add_link(name.clone(), &target_inode, target_abs_path); if kn.is_ok() { diff --git a/kernel/src/filesystem/vfs/core.rs b/kernel/src/filesystem/vfs/core.rs index bc2d0ebb..2eb8222b 100644 --- a/kernel/src/filesystem/vfs/core.rs +++ b/kernel/src/filesystem/vfs/core.rs @@ -1,6 +1,7 @@ use core::{hint::spin_loop, sync::atomic::Ordering}; use alloc::sync::Arc; +use log::{error, info}; use system_error::SystemError; use crate::{ @@ -13,7 +14,6 @@ use crate::{ sysfs::sysfs_init, vfs::{mount::MountFS, syscall::ModeType, AtomicInodeId, FileSystem, FileType}, }, - kerror, kinfo, process::ProcessManager, }; @@ -67,7 +67,7 @@ pub fn vfs_init() -> Result<(), SystemError> { let root_entries = ROOT_INODE().list().expect("VFS init failed"); if !root_entries.is_empty() { - kinfo!("Successfully initialized VFS!"); + info!("Successfully initialized VFS!"); } return Ok(()); } @@ -75,7 +75,7 @@ pub fn vfs_init() -> Result<(), SystemError> { /// @brief 迁移伪文件系统的inode /// 请注意,为了避免删掉了伪文件系统内的信息,因此没有在原root inode那里调用unlink. fn migrate_virtual_filesystem(new_fs: Arc) -> Result<(), SystemError> { - kinfo!("VFS: Migrating filesystems..."); + info!("VFS: Migrating filesystems..."); let new_fs = MountFS::new(new_fs, None); // 获取新的根文件系统的根节点的引用 @@ -108,7 +108,7 @@ fn migrate_virtual_filesystem(new_fs: Arc) -> Result<(), SystemE drop(old_root_inode); } - kinfo!("VFS: Migrate filesystems done!"); + info!("VFS: Migrate filesystems done!"); return Ok(()); } @@ -131,7 +131,7 @@ fn root_partition() -> Arc { let virtio0 = crate::driver::block::virtio_blk::virtio_blk_0(); if virtio0.is_none() { - kerror!("Failed to get virtio_blk_0"); + error!("Failed to get virtio_blk_0"); loop { spin_loop(); } @@ -142,12 +142,12 @@ fn root_partition() -> Arc { } } pub fn mount_root_fs() -> Result<(), SystemError> { - kinfo!("Try to mount FAT32 as root fs..."); + info!("Try to mount FAT32 as root fs..."); let partiton: Arc = root_partition(); let fatfs: Result, SystemError> = FATFileSystem::new(partiton); if fatfs.is_err() { - kerror!( + error!( "Failed to initialize fatfs, code={:?}", fatfs.as_ref().err() ); @@ -158,12 +158,12 @@ pub fn mount_root_fs() -> Result<(), SystemError> { let fatfs: Arc = fatfs.unwrap(); let r = migrate_virtual_filesystem(fatfs); if r.is_err() { - kerror!("Failed to migrate virtual filesystem to FAT32!"); + error!("Failed to migrate virtual filesystem to FAT32!"); loop { spin_loop(); } } - kinfo!("Successfully migrate rootfs to FAT32!"); + info!("Successfully migrate rootfs to FAT32!"); return Ok(()); } @@ -174,14 +174,14 @@ pub fn do_mkdir_at( path: &str, mode: FileMode, ) -> Result, SystemError> { - // kdebug!("Call do mkdir at"); + // debug!("Call do mkdir at"); let (mut current_inode, path) = user_path_at(&ProcessManager::current_pcb(), dirfd, path.trim())?; let (name, parent) = rsplit_path(&path); if let Some(parent) = parent { current_inode = current_inode.lookup(parent)?; } - // kdebug!("mkdir at {:?}", current_inode.metadata()?.inode_id); + // debug!("mkdir at {:?}", current_inode.metadata()?.inode_id); return current_inode.mkdir(name, ModeType::from_bits_truncate(mode.bits())); } diff --git a/kernel/src/filesystem/vfs/file.rs b/kernel/src/filesystem/vfs/file.rs index c867d4ca..2271065d 100644 --- a/kernel/src/filesystem/vfs/file.rs +++ b/kernel/src/filesystem/vfs/file.rs @@ -5,6 +5,7 @@ use alloc::{ sync::{Arc, Weak}, vec::Vec, }; +use log::error; use system_error::SystemError; use crate::{ @@ -14,7 +15,6 @@ use crate::{ }, filesystem::procfs::ProcfsFilePrivateData, ipc::pipe::{LockedPipeInode, PipeFsPrivateData}, - kerror, libs::{rwlock::RwLock, spinlock::SpinLock}, net::{ event_poll::{EPollItem, EPollPrivateData, EventPoll}, @@ -349,7 +349,7 @@ impl File { *readdir_subdirs_name = inode.list()?; readdir_subdirs_name.sort(); } - // kdebug!("sub_entries={sub_entries:?}"); + // debug!("sub_entries={sub_entries:?}"); // 已经读到末尾 if offset == readdir_subdirs_name.len() { @@ -360,7 +360,7 @@ impl File { let sub_inode: Arc = match inode.find(name) { Ok(i) => i, Err(e) => { - kerror!( + error!( "Readdir error: Failed to find sub inode:{name:?}, file={self:?}, error={e:?}" ); return Err(e); @@ -529,7 +529,7 @@ impl Drop for File { let r: Result<(), SystemError> = self.inode.close(self.private_data.lock()); // 打印错误信息 if r.is_err() { - kerror!( + error!( "pid: {:?} failed to close file: {:?}, errno={:?}", ProcessManager::current_pcb().pid(), self, @@ -653,7 +653,7 @@ impl FileDescriptorVec { let to_drop = file.close_on_exec(); if to_drop { if let Err(r) = self.drop_fd(i as i32) { - kerror!( + error!( "Failed to close file: pid = {:?}, fd = {}, error = {:?}", ProcessManager::current_pcb().pid(), i, diff --git a/kernel/src/filesystem/vfs/mod.rs b/kernel/src/filesystem/vfs/mod.rs index 482d4a88..52af901b 100644 --- a/kernel/src/filesystem/vfs/mod.rs +++ b/kernel/src/filesystem/vfs/mod.rs @@ -871,7 +871,9 @@ macro_rules! define_filesystem_maker_slice { pub static $name: [FileSystemMaker] = [..]; }; () => { - compile_error!("define_filesystem_maker_slice! requires at least one argument: slice_name"); + compile_kerror!( + "define_filesystem_maker_slice! requires at least one argument: slice_name" + ); }; } @@ -882,7 +884,7 @@ macro_rules! producefs { match $initializer_slice.iter().find(|&m| m.name == $filesystem) { Some(maker) => maker.call(), None => { - kerror!("mismatch filesystem type : {}", $filesystem); + log::error!("mismatch filesystem type : {}", $filesystem); Err(SystemError::EINVAL) } } diff --git a/kernel/src/filesystem/vfs/mount.rs b/kernel/src/filesystem/vfs/mount.rs index 7d751583..54c07ad5 100644 --- a/kernel/src/filesystem/vfs/mount.rs +++ b/kernel/src/filesystem/vfs/mount.rs @@ -456,7 +456,7 @@ impl IndexNode for MountFSInode { if self.is_mountpoint_root()? { return Err(SystemError::EBUSY); } - // kdebug!("from {:?}, to {:?}", from, self); + // debug!("from {:?}, to {:?}", from, self); let new_mount_fs = from.umount()?; self.mount_fs .mountpoints diff --git a/kernel/src/filesystem/vfs/open.rs b/kernel/src/filesystem/vfs/open.rs index 3e2e5660..826b91be 100644 --- a/kernel/src/filesystem/vfs/open.rs +++ b/kernel/src/filesystem/vfs/open.rs @@ -1,4 +1,5 @@ use alloc::sync::Arc; +use log::warn; use system_error::SystemError; use crate::{ @@ -53,7 +54,7 @@ pub fn do_fchmodat(dirfd: i32, path: *const u8, _mode: ModeType) -> Result Result { - // kdebug!("open path: {}, how: {:?}", path, how); + // debug!("open path: {}, how: {:?}", path, how); let path = path.trim(); let (inode_begin, path) = user_path_at(&ProcessManager::current_pcb(), dirfd, path)?; diff --git a/kernel/src/filesystem/vfs/syscall.rs b/kernel/src/filesystem/vfs/syscall.rs index 7449f5ac..893de210 100644 --- a/kernel/src/filesystem/vfs/syscall.rs +++ b/kernel/src/filesystem/vfs/syscall.rs @@ -3,13 +3,13 @@ use core::mem::size_of; use alloc::string::ToString; use alloc::{string::String, sync::Arc, vec::Vec}; +use log::warn; use system_error::SystemError; use crate::producefs; use crate::{ driver::base::{block::SeekFrom, device::device_number::DeviceNumber}, filesystem::vfs::{core as Vcore, file::FileDescriptorVec}, - kerror, libs::rwlock::RwLockWriteGuard, mm::{verify_area, VirtAddr}, process::ProcessManager, @@ -29,7 +29,6 @@ use super::{ Dirent, FileType, IndexNode, SuperBlock, FSMAKER, MAX_PATHLEN, ROOT_INODE, VFS_MAX_FOLLOW_SYMLINK_TIMES, }; -// use crate::kdebug; pub const SEEK_SET: u32 = 0; pub const SEEK_CUR: u32 = 1; @@ -908,7 +907,7 @@ impl Syscall { let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?; if flags.contains(AtFlags::AT_REMOVEDIR) { - // kdebug!("rmdir"); + // debug!("rmdir"); match do_remove_dir(dirfd, &path) { Err(err) => { return Err(err); @@ -1092,7 +1091,7 @@ impl Syscall { /// - `cmd`:命令 /// - `arg`:参数 pub fn fcntl(fd: i32, cmd: FcntlCommand, arg: i32) -> Result { - // kdebug!("fcntl ({cmd:?}) fd: {fd}, arg={arg}"); + // debug!("fcntl ({cmd:?}) fd: {fd}, arg={arg}"); match cmd { FcntlCommand::DupFd | FcntlCommand::DupFdCloexec => { if arg < 0 || arg as usize >= FileDescriptorVec::PROCESS_MAX_FD { @@ -1186,7 +1185,7 @@ impl Syscall { // TODO: unimplemented // 未实现的命令,返回0,不报错。 - kwarn!("fcntl: unimplemented command: {:?}, defaults to 0.", cmd); + warn!("fcntl: unimplemented command: {:?}, defaults to 0.", cmd); return Err(SystemError::ENOSYS); } } @@ -1568,7 +1567,7 @@ impl Syscall { // fchmod没完全实现,因此不修改文件的权限 // todo: 实现fchmod - kwarn!("fchmod not fully implemented"); + warn!("fchmod not fully implemented"); return Ok(0); } /// #挂载文件系统 diff --git a/kernel/src/init/initial_kthread.rs b/kernel/src/init/initial_kthread.rs index 3ff27069..4059b59c 100644 --- a/kernel/src/init/initial_kthread.rs +++ b/kernel/src/init/initial_kthread.rs @@ -3,13 +3,13 @@ use core::sync::atomic::{compiler_fence, Ordering}; use alloc::string::{String, ToString}; +use log::{debug, error}; use system_error::SystemError; use crate::{ arch::{interrupt::TrapFrame, process::arch_switch_to_user}, driver::{net::e1000e::e1000e::e1000e_init, virtio::virtio::virtio_probe}, filesystem::vfs::core::mount_root_fs, - kdebug, kerror, net::net_core::net_init, process::{kthread::KernelThreadMechanism, stdio::stdio_init, ProcessFlags, ProcessManager}, smp::smp_init, @@ -41,10 +41,10 @@ fn kernel_init() -> Result<(), SystemError> { e1000e_init(); net_init().unwrap_or_else(|err| { - kerror!("Failed to initialize network: {:?}", err); + error!("Failed to initialize network: {:?}", err); }); - kdebug!("initial kernel thread done."); + debug!("initial kernel thread done."); return Ok(()); } @@ -90,7 +90,7 @@ fn switch_to_user() -> ! { fn try_to_run_init_process(path: &str, trap_frame: &mut TrapFrame) -> Result<(), SystemError> { if let Err(e) = run_init_process(path.to_string(), trap_frame) { if e != SystemError::ENOENT { - kerror!( + error!( "Failed to run init process: {path} exists but couldn't execute it (error {:?})", e ); diff --git a/kernel/src/ipc/shm.rs b/kernel/src/ipc/shm.rs index 6e4b7224..13c9f1b0 100644 --- a/kernel/src/ipc/shm.rs +++ b/kernel/src/ipc/shm.rs @@ -18,6 +18,7 @@ use alloc::vec::Vec; use core::sync::atomic::{compiler_fence, Ordering}; use hashbrown::{HashMap, HashSet}; use ida::IdAllocator; +use log::info; use num::ToPrimitive; use system_error::SystemError; @@ -28,14 +29,14 @@ pub const IPC_PRIVATE: ShmKey = ShmKey::new(0); /// 初始化SHM_MANAGER pub fn shm_manager_init() { - kinfo!("shm_manager_init"); + info!("shm_manager_init"); let shm_manager = SpinLock::new(ShmManager::new()); compiler_fence(Ordering::SeqCst); unsafe { SHM_MANAGER = Some(shm_manager) }; compiler_fence(Ordering::SeqCst); - kinfo!("shm_manager_init done"); + info!("shm_manager_init done"); } pub fn shm_manager_lock() -> SpinLockGuard<'static, ShmManager> { diff --git a/kernel/src/ipc/signal.rs b/kernel/src/ipc/signal.rs index df4f0f46..2cb87333 100644 --- a/kernel/src/ipc/signal.rs +++ b/kernel/src/ipc/signal.rs @@ -1,12 +1,12 @@ use core::sync::atomic::compiler_fence; use alloc::sync::Arc; +use log::warn; use system_error::SystemError; use crate::{ arch::ipc::signal::{SigCode, SigFlags, SigSet, Signal}, ipc::signal_types::SigactionType, - kwarn, libs::spinlock::SpinLockGuard, process::{pid::PidType, Pid, ProcessControlBlock, ProcessFlags, ProcessManager}, }; @@ -35,7 +35,7 @@ impl Signal { // 如果 pid 等于 -1,那么信号的发送范围是:调用进程有权将信号发往的每个目标进程,除去 init(进程 ID 为 1)和调用进程自身。如果特权级进程发起这一调用,那么会发送信号给系统中的所有进程,上述两个进程除外。显而易见,有时也将这种信号发送方式称之为广播信号 // 如果并无进程与指定的 pid 相匹配,那么 kill() 调用失败,同时将 errno 置为 ESRCH(“查无此进程”) if pid.lt(&Pid::from(0)) { - kwarn!("Kill operation not support: pid={:?}", pid); + warn!("Kill operation not support: pid={:?}", pid); return Err(SystemError::ENOSYS); } compiler_fence(core::sync::atomic::Ordering::SeqCst); @@ -47,7 +47,7 @@ impl Signal { let pcb = ProcessManager::find(pid); if pcb.is_none() { - kwarn!("No such process."); + warn!("No such process."); return retval; } @@ -85,7 +85,7 @@ impl Signal { if !self.prepare_sianal(pcb.clone(), force_send) { return Err(SystemError::EINVAL); } - // kdebug!("force send={}", force_send); + // debug!("force send={}", force_send); let pcb_info = pcb.sig_info_irqsave(); let pending = if matches!(pt, PidType::PID) { pcb_info.sig_shared_pending() @@ -141,7 +141,7 @@ impl Signal { /// @param pt siginfo结构体中,pid字段代表的含义 #[allow(clippy::if_same_then_else)] fn complete_signal(&self, pcb: Arc, pt: PidType) { - // kdebug!("complete_signal"); + // debug!("complete_signal"); compiler_fence(core::sync::atomic::Ordering::SeqCst); // ===== 寻找需要wakeup的目标进程 ===== @@ -284,14 +284,14 @@ impl Signal { fn signal_wake_up(pcb: Arc, _guard: SpinLockGuard, fatal: bool) { // 如果是 fatal 的话就唤醒 stop 和 block 的进程来响应,因为唤醒后就会终止 // 如果不是 fatal 的就只唤醒 stop 的进程来响应 - // kdebug!("signal_wake_up"); + // debug!("signal_wake_up"); // 如果目标进程已经在运行,则发起一个ipi,使得它陷入内核 let state = pcb.sched_info().inner_lock_read_irqsave().state(); let mut wakeup_ok = true; if state.is_blocked_interruptable() { ProcessManager::wakeup(&pcb).unwrap_or_else(|e| { wakeup_ok = false; - kwarn!( + warn!( "Current pid: {:?}, signal_wake_up target {:?} error: {:?}", ProcessManager::current_pcb().pid(), pcb.pid(), @@ -301,7 +301,7 @@ fn signal_wake_up(pcb: Arc, _guard: SpinLockGuard, force_default: bool) { compiler_fence(core::sync::atomic::Ordering::SeqCst); - // kdebug!("hand=0x{:018x}", hand as *const sighand_struct as usize); + // debug!("hand=0x{:018x}", hand as *const sighand_struct as usize); let actions = &mut pcb.sig_struct_irqsave().handlers; for sigaction in actions.iter_mut() { diff --git a/kernel/src/ipc/signal_types.rs b/kernel/src/ipc/signal_types.rs index 1ed08547..d5622a8f 100644 --- a/kernel/src/ipc/signal_types.rs +++ b/kernel/src/ipc/signal_types.rs @@ -430,7 +430,7 @@ impl SigPending { /// @brief 从当前进程的sigpending中取出下一个待处理的signal,并返回给调用者。(调用者应当处理这个信号) /// 请注意,进入本函数前,当前进程应当持有current_pcb().sighand.siglock pub fn dequeue_signal(&mut self, sig_mask: &SigSet) -> (Signal, Option) { - // kdebug!("dequeue signal"); + // debug!("dequeue signal"); // 获取下一个要处理的信号的编号 let sig = self.next_signal(sig_mask); diff --git a/kernel/src/ipc/syscall.rs b/kernel/src/ipc/syscall.rs index 995dcfbd..37a9cc9c 100644 --- a/kernel/src/ipc/syscall.rs +++ b/kernel/src/ipc/syscall.rs @@ -3,6 +3,7 @@ use core::{ sync::atomic::compiler_fence, }; +use log::{error, warn}; use system_error::SystemError; use crate::{ @@ -15,7 +16,6 @@ use crate::{ FilePrivateData, }, ipc::shm::{shm_manager_lock, IPC_PRIVATE}, - kerror, kwarn, libs::align::page_align_up, libs::spinlock::SpinLock, mm::{ @@ -96,7 +96,7 @@ impl Syscall { let sig = Signal::from(sig); if sig == Signal::INVALID { // 传入的signal数值不合法 - kwarn!("Not a valid signal number"); + warn!("Not a valid signal number"); return Err(SystemError::EINVAL); } @@ -173,12 +173,12 @@ impl Syscall { } // TODO 如果为空,赋默认值? - // kdebug!("new_ka={:?}", new_ka); + // debug!("new_ka={:?}", new_ka); // 如果用户手动给了sa_restorer,那么就置位SA_FLAG_RESTORER,否则报错。(用户必须手动指定restorer) if new_ka.restorer().is_some() { new_ka.flags_mut().insert(SigFlags::SA_RESTORER); } else if new_ka.action().is_customized() { - kerror!( + error!( "pid:{:?}: in sys_sigaction: User must manually sprcify a sa_restorer for signal {}.", ProcessManager::current_pcb().pid(), sig @@ -229,7 +229,7 @@ impl Syscall { } } SigactionType::SaSigaction(_) => { - kerror!("unsupported type: SaSigaction"); + error!("unsupported type: SaSigaction"); VirtAddr::new(USER_SIG_DFL as usize) } }; @@ -261,7 +261,7 @@ impl Syscall { pub fn shmget(key: ShmKey, size: usize, shmflg: ShmFlags) -> Result { // 暂不支持巨页 if shmflg.contains(ShmFlags::SHM_HUGETLB) { - kerror!("shmget: not support huge page"); + error!("shmget: not support huge page"); return Err(SystemError::ENOSYS); } diff --git a/kernel/src/lib.rs b/kernel/src/lib.rs index b26a7ca7..fce70b46 100644 --- a/kernel/src/lib.rs +++ b/kernel/src/lib.rs @@ -106,7 +106,9 @@ pub static KERNEL_ALLOCATOR: KernelAllocator = KernelAllocator; #[panic_handler] #[no_mangle] pub fn panic(info: &PanicInfo) -> ! { - kerror!("Kernel Panic Occurred."); + use log::error; + + error!("Kernel Panic Occurred."); match info.location() { Some(loc) => { diff --git a/kernel/src/libs/elf.rs b/kernel/src/libs/elf.rs index 417366b5..7cbfdb91 100644 --- a/kernel/src/libs/elf.rs +++ b/kernel/src/libs/elf.rs @@ -12,13 +12,13 @@ use elf::{ file::FileHeader, segment::ProgramHeader, }; +use log::error; use system_error::SystemError; use crate::{ arch::{CurrentElfArch, MMArch}, driver::base::block::SeekFrom, filesystem::vfs::file::File, - kerror, libs::align::page_align_up, mm::{ allocator::page_frame::{PageFrameCount, VirtPageFrame}, @@ -123,7 +123,7 @@ impl ElfLoader { ) -> Result<(), ExecError> { let start = self.elf_page_start(start); let end = self.elf_page_align_up(end); - // kdebug!("set_elf_brk: start={:?}, end={:?}", start, end); + // debug!("set_elf_brk: start={:?}, end={:?}", start, end); if end > start { let r = user_vm_guard.map_anonymous( start, @@ -133,9 +133,9 @@ impl ElfLoader { false, true, ); - // kdebug!("set_elf_brk: map_anonymous: r={:?}", r); + // debug!("set_elf_brk: map_anonymous: r={:?}", r); if r.is_err() { - kerror!("set_elf_brk: map_anonymous failed, err={:?}", r); + error!("set_elf_brk: map_anonymous failed, err={:?}", r); return Err(ExecError::OutOfMemory); } } @@ -207,7 +207,7 @@ impl ElfLoader { map_flags: &MapFlags, total_size: usize, ) -> Result<(VirtAddr, bool), SystemError> { - // kdebug!("load_elf_segment: addr_to_map={:?}", addr_to_map); + // debug!("load_elf_segment: addr_to_map={:?}", addr_to_map); // 映射位置的偏移量(页内偏移) let beginning_page_offset = self.elf_page_offset(addr_to_map); @@ -228,7 +228,7 @@ impl ElfLoader { let map_err_handler = |err: SystemError| { if err == SystemError::EEXIST { - kerror!( + error!( "Pid: {:?}, elf segment at {:p} overlaps with existing mapping", ProcessManager::current_pcb().pid(), addr_to_map.as_ptr::() @@ -283,12 +283,12 @@ impl ElfLoader { )?; } } else { - // kdebug!("total size = 0"); + // debug!("total size = 0"); map_addr = user_vm_guard .map_anonymous(addr_to_map, map_size, tmp_prot, *map_flags, false, true)? .virt_address(); - // kdebug!( + // debug!( // "map ok: addr_to_map={:?}, map_addr={map_addr:?},beginning_page_offset={beginning_page_offset:?}", // addr_to_map // ); @@ -309,7 +309,7 @@ impl ElfLoader { )?; } } - // kdebug!("load_elf_segment OK: map_addr={:?}", map_addr); + // debug!("load_elf_segment OK: map_addr={:?}", map_addr); return Ok((map_addr, true)); } @@ -342,7 +342,7 @@ impl ElfLoader { while remain > 0 { let read_size = min(remain, buf_size); file.read(read_size, &mut buf[..read_size])?; - // kdebug!("copy_to_user: vaddr={:?}, read_size = {read_size}", vaddr); + // debug!("copy_to_user: vaddr={:?}, read_size = {read_size}", vaddr); unsafe { copy_to_user(vaddr, &buf[..read_size]).map_err(|_| SystemError::EFAULT)?; } @@ -528,14 +528,14 @@ impl BinaryLoader for ElfLoader { // https://code.dragonos.org.cn/xref/linux-5.19.10/fs/binfmt_elf.c?r=&mo=22652&fi=824#1034 let elf_type = ElfType::from(ehdr.e_type); - // kdebug!("ehdr = {:?}", ehdr); + // debug!("ehdr = {:?}", ehdr); let binding = param.vm().clone(); let mut user_vm = binding.write(); // todo: 增加对user stack上的内存是否具有可执行权限的处理(方法:寻找phdr里面的PT_GNU_STACK段) - // kdebug!("to parse segments"); + // debug!("to parse segments"); // 加载ELF文件并映射到用户空间 let mut phdr_buf = Vec::new(); let phdr_table = Self::parse_segments(param, &ehdr, &mut phdr_buf) @@ -627,9 +627,9 @@ impl BinaryLoader for ElfLoader { .into_iter() .filter(|seg| seg.p_type == elf::abi::PT_LOAD); for seg_to_load in loadable_sections { - // kdebug!("seg_to_load = {:?}", seg_to_load); + // debug!("seg_to_load = {:?}", seg_to_load); if unlikely(elf_brk > elf_bss) { - // kdebug!( + // debug!( // "to set brk, elf_brk = {:?}, elf_bss = {:?}", // elf_brk, // elf_bss @@ -692,7 +692,7 @@ impl BinaryLoader for ElfLoader { } // 加载这个段到用户空间 - // kdebug!("to load elf segment"); + // debug!("to load elf segment"); let e = self .load_elf_segment( &mut user_vm, @@ -704,7 +704,7 @@ impl BinaryLoader for ElfLoader { total_size, ) .map_err(|e| { - kerror!("load_elf_segment failed: {:?}", e); + error!("load_elf_segment failed: {:?}", e); match e { SystemError::EFAULT => ExecError::BadAddress(None), SystemError::ENOMEM => ExecError::OutOfMemory, @@ -732,9 +732,9 @@ impl BinaryLoader for ElfLoader { } } - // kdebug!("seg_to_load.p_offset={}", seg_to_load.p_offset); - // kdebug!("e_phoff={}", ehdr.e_phoff); - // kdebug!("seg_to_load.p_filesz={}", seg_to_load.p_filesz); + // debug!("seg_to_load.p_offset={}", seg_to_load.p_offset); + // debug!("e_phoff={}", ehdr.e_phoff); + // debug!("seg_to_load.p_filesz={}", seg_to_load.p_filesz); // Figure out which segment in the file contains the Program Header Table, // and map to the associated virtual address. if (seg_to_load.p_offset <= ehdr.e_phoff) @@ -764,7 +764,7 @@ impl BinaryLoader for ElfLoader { || self.elf_page_align_up(p_vaddr + seg_to_load.p_memsz as usize) >= MMArch::USER_END_VADDR { - // kdebug!("ERR: p_vaddr={p_vaddr:?}"); + // debug!("ERR: p_vaddr={p_vaddr:?}"); return Err(ExecError::InvalidParemeter); } @@ -797,7 +797,7 @@ impl BinaryLoader for ElfLoader { elf_brk = seg_end_vaddr; } } - // kdebug!("elf load: phdr_vaddr={phdr_vaddr:?}"); + // debug!("elf load: phdr_vaddr={phdr_vaddr:?}"); let program_entrypoint = VirtAddr::new(ehdr.e_entry as usize + load_bias); let phdr_vaddr = phdr_vaddr.map(|phdr_vaddr| phdr_vaddr + load_bias); @@ -808,7 +808,7 @@ impl BinaryLoader for ElfLoader { start_data = start_data.map(|v| v + load_bias); end_data = end_data.map(|v| v + load_bias); - // kdebug!( + // debug!( // "to set brk: elf_bss: {:?}, elf_brk: {:?}, bss_prot_flags: {:?}", // elf_bss, // elf_brk, @@ -817,25 +817,25 @@ impl BinaryLoader for ElfLoader { self.set_elf_brk(&mut user_vm, elf_bss, elf_brk, bss_prot_flags)?; if likely(elf_bss != elf_brk) && unlikely(self.pad_zero(elf_bss).is_err()) { - // kdebug!("elf_bss = {elf_bss:?}, elf_brk = {elf_brk:?}"); + // debug!("elf_bss = {elf_bss:?}, elf_brk = {elf_brk:?}"); return Err(ExecError::BadAddress(Some(elf_bss))); } if interpreter.is_some() { // TODO 添加对动态加载器的处理 // 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/fs/binfmt_elf.c#1249 } - // kdebug!("to create auxv"); + // debug!("to create auxv"); self.create_auxv(param, program_entrypoint, phdr_vaddr, &ehdr)?; - // kdebug!("auxv create ok"); + // debug!("auxv create ok"); user_vm.start_code = start_code.unwrap_or(VirtAddr::new(0)); user_vm.end_code = end_code.unwrap_or(VirtAddr::new(0)); user_vm.start_data = start_data.unwrap_or(VirtAddr::new(0)); user_vm.end_data = end_data.unwrap_or(VirtAddr::new(0)); let result = BinaryLoaderResult::new(program_entrypoint); - // kdebug!("elf load OK!!!"); + // debug!("elf load OK!!!"); return Ok(result); } } diff --git a/kernel/src/libs/futex/futex.rs b/kernel/src/libs/futex/futex.rs index c1897f96..a3a26d7d 100644 --- a/kernel/src/libs/futex/futex.rs +++ b/kernel/src/libs/futex/futex.rs @@ -8,6 +8,7 @@ use core::{ mem, sync::atomic::AtomicU64, }; +use log::warn; use hashbrown::HashMap; use system_error::SystemError; @@ -288,7 +289,7 @@ impl Futex { let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() }; // 满足条件则将当前进程在该bucket上挂起 bucket_mut.sleep_no_sched(futex_q.clone()).map_err(|e| { - kwarn!("error:{e:?}"); + warn!("error:{e:?}"); e })?; drop(futex_map_guard); @@ -558,7 +559,7 @@ impl Futex { let cmparg = sign_extend32(encoded_op & 0x00000fff, 11); if (encoded_op & (FutexOP::FUTEX_OP_OPARG_SHIFT.bits() << 28) != 0) && oparg > 31 { - kwarn!( + warn!( "futex_wake_op: pid:{} tries to shift op by {}; fix this program", ProcessManager::current_pcb().pid().data(), oparg diff --git a/kernel/src/libs/keyboard_parser.rs b/kernel/src/libs/keyboard_parser.rs index 90271d81..4cbe3e00 100644 --- a/kernel/src/libs/keyboard_parser.rs +++ b/kernel/src/libs/keyboard_parser.rs @@ -64,7 +64,7 @@ pub enum TypeOneFSMState { impl TypeOneFSMState { /// @brief 状态机总控程序 fn parse(&self, scancode: u8, scancode_status: &mut ScanCodeStatus) -> TypeOneFSMState { - // kdebug!("the code is {:#x}\n", scancode); + // debug!("the code is {:#x}\n", scancode); match self { TypeOneFSMState::Start => { return self.handle_start(scancode, scancode_status); @@ -87,7 +87,7 @@ impl TypeOneFSMState { /// @brief 处理起始状态 fn handle_start(&self, scancode: u8, scancode_status: &mut ScanCodeStatus) -> TypeOneFSMState { - //kdebug!("in handle_start the code is {:#x}\n",scancode); + //debug!("in handle_start the code is {:#x}\n",scancode); match scancode { 0xe1 => { return TypeOneFSMState::PauseBreak(1); @@ -96,7 +96,7 @@ impl TypeOneFSMState { return TypeOneFSMState::Func0; } _ => { - //kdebug!("in _d the code is {:#x}\n",scancode); + //debug!("in _d the code is {:#x}\n",scancode); return TypeOneFSMState::Type3.handle_type3(scancode, scancode_status); } } @@ -274,7 +274,7 @@ impl TypeOneFSMState { let mut col: bool = false; let index = scancode & 0x7f; - //kdebug!("in type3 ch is {:#x}\n",ch); + //debug!("in type3 ch is {:#x}\n",ch); let mut key = KeyFlag::OtherKey; // 可视字符 match index { @@ -306,7 +306,7 @@ impl TypeOneFSMState { } _ => { if !flag_make { - // kdebug!("in type3 ch is {:#x}\n",ch); + // debug!("in type3 ch is {:#x}\n",ch); key = KeyFlag::NoneFlag; } } @@ -327,7 +327,7 @@ impl TypeOneFSMState { let mut ch = TYPE1_KEY_CODE_MAPTABLE[col as usize + 2 * index as usize]; if key != KeyFlag::NoneFlag { - // kdebug!("EMIT: ch is '{}', keyflag is {:?}\n", ch as char, key); + // debug!("EMIT: ch is '{}', keyflag is {:?}\n", ch as char, key); if scancode_status.ctrl_l || scancode_status.ctrl_r { ch = Self::to_ctrl(ch); } diff --git a/kernel/src/libs/lib_ui/textui.rs b/kernel/src/libs/lib_ui/textui.rs index 59747b15..546e558b 100644 --- a/kernel/src/libs/lib_ui/textui.rs +++ b/kernel/src/libs/lib_ui/textui.rs @@ -4,7 +4,6 @@ use crate::{ tty::{tty_port::tty_port, virtual_terminal::virtual_console::CURRENT_VCNUM}, video::video_refresh_manager, }, - kdebug, kinfo, libs::{ lib_ui::font::FONT_8x16, rwlock::RwLock, @@ -20,6 +19,7 @@ use core::{ ptr::copy_nonoverlapping, sync::atomic::{AtomicBool, AtomicI32, AtomicU32, Ordering}, }; +use log::{debug, info}; use system_error::SystemError; use super::{ @@ -73,9 +73,9 @@ pub fn textui_framework() -> Arc { /// 初始化TEXTUI_FRAMEWORK fn textui_framwork_init() { if unsafe { __TEXTUI_FRAMEWORK.is_none() } { - kinfo!("textuiframework init"); + info!("textuiframework init"); let metadata = ScmUiFrameworkMetadata::new("TextUI".to_string(), ScmFramworkType::Text); - kdebug!("textui metadata: {:?}", metadata); + debug!("textui metadata: {:?}", metadata); // 为textui框架生成第一个窗口 let vlines_num = (metadata.buf_info().height() / TEXTUI_CHAR_HEIGHT) as usize; @@ -106,7 +106,7 @@ fn textui_framwork_init() { }; scm_register(textui_framework()).expect("register textui framework failed"); - kdebug!("textui framework init success"); + debug!("textui framework init success"); send_to_default_serial8250_port("\ntext ui initialized\n\0".as_bytes()); unsafe { TEXTUI_IS_INIT = true }; @@ -989,8 +989,8 @@ impl ScmUiFramework for TextUiFramework { let mut new_buf = textui_framework().metadata.read().buf_info(); new_buf.copy_from_nonoverlapping(&old_buf); - kdebug!("textui change buf_info: old: {:?}", old_buf); - kdebug!("textui change buf_info: new: {:?}", new_buf); + debug!("textui change buf_info: old: {:?}", old_buf); + debug!("textui change buf_info: new: {:?}", new_buf); return Ok(0); } diff --git a/kernel/src/libs/notifier.rs b/kernel/src/libs/notifier.rs index ea4dcdc7..ee470d17 100644 --- a/kernel/src/libs/notifier.rs +++ b/kernel/src/libs/notifier.rs @@ -1,11 +1,9 @@ #![allow(dead_code)] use core::fmt::Debug; -use crate::{ - kwarn, - libs::{rwlock::RwLock, spinlock::SpinLock}, -}; +use crate::libs::{rwlock::RwLock, spinlock::SpinLock}; use alloc::{sync::Arc, vec::Vec}; +use log::warn; use system_error::SystemError; /// @brief 通知链节点 @@ -39,7 +37,7 @@ impl NotifierChain { for b in self.0.iter() { // 判断之前是否已经注册过该节点 if Arc::ptr_eq(&block, b) { - kwarn!( + warn!( "notifier callback {:?} already registered", Arc::as_ptr(&block) ); diff --git a/kernel/src/libs/printk.rs b/kernel/src/libs/printk.rs index 29ed9c16..01ae4854 100644 --- a/kernel/src/libs/printk.rs +++ b/kernel/src/libs/printk.rs @@ -4,7 +4,7 @@ use core::{ }; use alloc::string::ToString; -use log::{info, Log}; +use log::{info, Level, Log}; use super::lib_ui::textui::{textui_putstr, FontColor}; @@ -33,49 +33,6 @@ macro_rules! println { ($($arg:tt)*) => ($crate::print!("{}\n", format_args!($($arg)*))); } -#[macro_export] -macro_rules! kdebug { - ($($arg:tt)*) => { - $crate::libs::printk::Logger.log(7,format_args!("({}:{})\t {}\n", file!(), line!(),format_args!($($arg)*))); - $crate::libs::printk::PrintkWriter.__write_fmt(format_args!("[ DEBUG ] ({}:{})\t {}\n", file!(), line!(),format_args!($($arg)*))) - } -} - -#[macro_export] -macro_rules! kinfo { - ($($arg:tt)*) => { - $crate::libs::printk::Logger.log(6,format_args!("({}:{})\t {}\n", file!(), line!(),format_args!($($arg)*))); - $crate::libs::printk::PrintkWriter.__write_fmt(format_args!("[ INFO ] ({}:{})\t {}\n", file!(), line!(),format_args!($($arg)*))) - } -} - -#[macro_export] -macro_rules! kwarn { - ($($arg:tt)*) => { - $crate::libs::printk::Logger.log(4,format_args!("({}:{})\t {}\n", file!(), line!(),format_args!($($arg)*))); - $crate::libs::printk::PrintkWriter.__write_fmt(format_args!("\x1B[1;33m[ WARN ] \x1B[0m")); - $crate::libs::printk::PrintkWriter.__write_fmt(format_args!("({}:{})\t {}\n", file!(), line!(),format_args!($($arg)*))); - } -} - -#[macro_export] -macro_rules! kerror { - ($($arg:tt)*) => { - $crate::libs::printk::Logger.log(3,format_args!("({}:{})\t {}\n", file!(), line!(),format_args!($($arg)*))); - $crate::libs::printk::PrintkWriter.__write_fmt(format_args!("\x1B[41m[ ERROR ] \x1B[0m")); - $crate::libs::printk::PrintkWriter.__write_fmt(format_args!("({}:{})\t {}\n", file!(), line!(),format_args!($($arg)*))); - } -} - -#[macro_export] -macro_rules! kBUG { - ($($arg:tt)*) => { - $crate::libs::printk::Logger.log(1,format_args!("({}:{})\t {}\n", file!(), line!(),format_args!($($arg)*))); - $crate::libs::printk::PrintkWriter.__write_fmt(format_args!("\x1B[41m[ BUG ] \x1B[0m")); - $crate::libs::printk::PrintkWriter.__write_fmt(format_args!("({}:{})\t {}\n", file!(), line!(),format_args!($($arg)*))); - } -} - pub struct PrintkWriter; impl PrintkWriter { @@ -145,17 +102,8 @@ impl Log for CustomLogger { fn log(&self, record: &log::Record) { if self.enabled(record.metadata()) { // todo: 接入kmsg - - writeln!( - PrintkWriter, - "[ {} ] {} ({}:{}) {}", - record.level(), - record.target(), - record.file().unwrap_or(""), - record.line().unwrap_or(0), - record.args() - ) - .unwrap(); + Self::kernel_log(record); + Self::iodisplay(record) } } @@ -164,6 +112,78 @@ impl Log for CustomLogger { } } +impl CustomLogger { + fn iodisplay(record: &log::Record) { + match record.level() { + Level::Debug | Level::Info => { + write!(PrintkWriter, "[ {} ] ", record.level(),) + } + Level::Error => { + write!(PrintkWriter, "\x1B[41m[ ERROR ] \x1B[0m",) + } + Level::Warn => { + write!(PrintkWriter, "\x1B[1;33m[ WARN ] \x1B[0m",) + } + Level::Trace => { + todo!() + } + } + .unwrap(); + writeln!( + PrintkWriter, + "({}:{})\t {}", + record.file().unwrap_or(""), + record.line().unwrap_or(0), + record.args() + ) + .unwrap(); + } + + fn kernel_log(record: &log::Record) { + match record.level() { + Level::Debug => Logger.log( + 7, + format_args!( + "({}:{})\t {}\n", + record.file().unwrap_or(""), + record.line().unwrap_or(0), + record.args() + ), + ), + Level::Error => Logger.log( + 3, + format_args!( + "({}:{})\t {}\n", + record.file().unwrap_or(""), + record.line().unwrap_or(0), + record.args() + ), + ), + Level::Info => Logger.log( + 6, + format_args!( + "({}:{})\t {}\n", + record.file().unwrap_or(""), + record.line().unwrap_or(0), + record.args() + ), + ), + Level::Warn => Logger.log( + 4, + format_args!( + "({}:{})\t {}\n", + record.file().unwrap_or(""), + record.line().unwrap_or(0), + record.args() + ), + ), + Level::Trace => { + todo!() + } + } + } +} + pub fn early_init_logging() { log::set_logger(&CustomLogger).unwrap(); log::set_max_level(log::LevelFilter::Debug); diff --git a/kernel/src/libs/rbtree.rs b/kernel/src/libs/rbtree.rs index aed58744..f1fed00f 100644 --- a/kernel/src/libs/rbtree.rs +++ b/kernel/src/libs/rbtree.rs @@ -22,8 +22,7 @@ use core::ops::Index; use core::ptr; use alloc::boxed::Box; - -use crate::kdebug; +use log::debug; #[derive(Debug, Copy, Clone, PartialEq, Eq)] enum Color { @@ -303,7 +302,7 @@ impl NodePtr { /// /// // check for a specific one. /// if !book_reviews.contains_key(&"Les Misérables") { -/// kdebug!( +/// debug!( /// "We've got {} reviews, but Les Misérables ain't one.", /// book_reviews.len() /// ); @@ -316,14 +315,14 @@ impl NodePtr { /// let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"]; /// for book in &to_find { /// match book_reviews.get(book) { -/// Some(review) => kdebug!("{}: {}", book, review), -/// None => kdebug!("{} is unreviewed.", book), +/// Some(review) => debug!("{}: {}", book, review), +/// None => debug!("{} is unreviewed.", book), /// } /// } /// /// // iterate over everything. /// for (book, review) in book_reviews.iter() { -/// kdebug!("{}: \"{}\"", book, review); +/// debug!("{}: \"{}\"", book, review); /// } /// /// book_reviews.print_tree(); @@ -386,12 +385,12 @@ impl RBTree { } if direction == 0 { unsafe { - kdebug!("'{:?}' is root node", (*node.0)); + debug!("'{:?}' is root node", (*node.0)); } } else { let direct = if direction == -1 { "left" } else { "right" }; unsafe { - kdebug!( + debug!( "{:?} is {:?}'s {:?} child ", (*node.0), *node.parent().0, @@ -405,12 +404,12 @@ impl RBTree { pub fn print_tree(&self) { if self.root.is_null() { - kdebug!("This is a empty tree"); + debug!("This is a empty tree"); return; } - kdebug!("This tree size = {:?}, begin:-------------", self.len()); + debug!("This tree size = {:?}, begin:-------------", self.len()); self.tree_print(self.root, 0); - kdebug!("end--------------------------"); + debug!("end--------------------------"); } } @@ -720,7 +719,7 @@ impl<'a, K: Ord + Debug + 'a, V: Debug + 'a> Iterator for Iter<'a, K, V> { impl<'a, K: Ord + Debug + 'a, V: Debug + 'a> DoubleEndedIterator for Iter<'a, K, V> { #[inline] fn next_back(&mut self) -> Option<(&'a K, &'a V)> { - // kdebug!("len = {:?}", self.len); + // debug!("len = {:?}", self.len); if self.len == 0 { return None; } diff --git a/kernel/src/libs/semaphore.rs b/kernel/src/libs/semaphore.rs index 163c6dc4..5cf600d3 100644 --- a/kernel/src/libs/semaphore.rs +++ b/kernel/src/libs/semaphore.rs @@ -1,8 +1,9 @@ use core::sync::atomic::{AtomicI32, Ordering}; +use log::debug; use system_error::SystemError; -use crate::{kdebug, process::ProcessManager}; +use crate::process::ProcessManager; use super::wait_queue::WaitQueue; @@ -51,7 +52,7 @@ impl Semaphore { //尝试唤醒 if !self.wait_queue.wakeup(None) { //如果唤醒失败,打印错误信息 - kdebug!( + debug!( "Semaphore wakeup failed: current pid= {}, semaphore={:?}", ProcessManager::current_pcb().pid().into(), self diff --git a/kernel/src/libs/wait_queue.rs b/kernel/src/libs/wait_queue.rs index 25e985b9..f8c488b4 100644 --- a/kernel/src/libs/wait_queue.rs +++ b/kernel/src/libs/wait_queue.rs @@ -2,11 +2,11 @@ use core::intrinsics::unlikely; use alloc::{collections::LinkedList, sync::Arc, vec::Vec}; +use log::{error, warn}; use crate::{ arch::CurrentIrqArch, exception::InterruptArch, - kerror, process::{ProcessControlBlock, ProcessManager, ProcessState}, sched::{schedule, SchedMode}, }; @@ -237,7 +237,7 @@ impl WaitQueue { if wake { ProcessManager::wakeup(&to_wakeup).unwrap_or_else(|e| { - kerror!("wakeup pid: {:?} error: {:?}", to_wakeup.pid(), e); + error!("wakeup pid: {:?} error: {:?}", to_wakeup.pid(), e); }); continue; } else { @@ -265,7 +265,7 @@ impl InnerWaitQueue { fn before_sleep_check(max_preempt: usize) { let pcb = ProcessManager::current_pcb(); if unlikely(pcb.preempt_count() > max_preempt) { - kwarn!( + warn!( "Process {:?}: Try to sleep when preempt count is {}", pcb.pid().data(), pcb.preempt_count() diff --git a/kernel/src/misc/ksysfs.rs b/kernel/src/misc/ksysfs.rs index f4f45248..5041c650 100644 --- a/kernel/src/misc/ksysfs.rs +++ b/kernel/src/misc/ksysfs.rs @@ -7,6 +7,7 @@ use crate::{ init::initcall::INITCALL_CORE, }; use alloc::{string::ToString, sync::Arc}; +use log::error; use system_error::SystemError; use unified_init::macros::unified_init; @@ -29,7 +30,7 @@ fn ksysfs_init() -> Result<(), SystemError> { sysfs_instance() .create_groups(&kernel_kset.as_kobject(), &[&KernelAttrGroup]) .map_err(|e| { - kerror!("Failed to create sysfs groups for kernel kset: {:?}", e); + error!("Failed to create sysfs groups for kernel kset: {:?}", e); kernel_kset.unregister(); SystemError::ENOMEM })?; diff --git a/kernel/src/mm/allocator/buddy.rs b/kernel/src/mm/allocator/buddy.rs index deff4066..50ee1a3b 100644 --- a/kernel/src/mm/allocator/buddy.rs +++ b/kernel/src/mm/allocator/buddy.rs @@ -1,3 +1,5 @@ +use log::{debug, warn}; + /// @Author: longjin@dragonos.org /// @Author: kongweichao@dragonos.org /// @Date: 2023-03-28 16:03:47 @@ -7,7 +9,7 @@ use crate::arch::MMArch; use crate::mm::allocator::bump::BumpAllocator; use crate::mm::allocator::page_frame::{FrameAllocator, PageFrameCount, PageFrameUsage}; use crate::mm::{MemoryManagementArch, PhysAddr, PhysMemoryArea, VirtAddr}; -use crate::{kdebug, kwarn}; + use core::cmp::min; use core::fmt::Debug; use core::intrinsics::{likely, unlikely}; @@ -78,8 +80,8 @@ impl BuddyAllocator { pub unsafe fn new(mut bump_allocator: BumpAllocator) -> Option { let initial_free_pages = bump_allocator.usage().free(); let total_memory = bump_allocator.usage().total(); - kdebug!("Free pages before init buddy: {:?}", initial_free_pages); - kdebug!("Buddy entries: {}", Self::BUDDY_ENTRIES); + debug!("Free pages before init buddy: {:?}", initial_free_pages); + debug!("Buddy entries: {}", Self::BUDDY_ENTRIES); let mut free_area: [PhysAddr; MAX_ORDER - MIN_ORDER] = [PhysAddr::new(0); MAX_ORDER - MIN_ORDER]; @@ -118,7 +120,7 @@ impl BuddyAllocator { if remain_pages.data() == 0 { continue; } - kdebug!("area: {area:?}, paddr: {paddr:#x}, remain_pages: {remain_pages:?}"); + debug!("area: {area:?}, paddr: {paddr:#x}, remain_pages: {remain_pages:?}"); total_pages_to_buddy += remain_pages; @@ -128,7 +130,7 @@ impl BuddyAllocator { // 先从低阶开始,尽可能地填满空闲链表 for i in MIN_ORDER..MAX_ORDER { - // kdebug!("i {i}, remain pages={}", remain_pages.data()); + // debug!("i {i}, remain pages={}", remain_pages.data()); if remain_pages.data() < (1 << (i - MIN_ORDER)) { break; } @@ -175,7 +177,7 @@ impl BuddyAllocator { assert!(remain_bytes == 0); } - kdebug!("Total pages to buddy: {:?}", total_pages_to_buddy); + debug!("Total pages to buddy: {:?}", total_pages_to_buddy); allocator.total = total_memory; Some(allocator) @@ -238,7 +240,7 @@ impl BuddyAllocator { if !next_page_list_addr.is_null() { // 此时page_list已经没有空闲伙伴块了,又因为非唯一页,需要删除该page_list self.free_area[Self::order2index(spec_order)] = next_page_list_addr; - // kdebug!("FREE: page_list_addr={:b}", page_list_addr.data()); + // debug!("FREE: page_list_addr={:b}", page_list_addr.data()); unsafe { self.buddy_free(page_list_addr, MMArch::PAGE_SHIFT as u8); } @@ -273,7 +275,7 @@ impl BuddyAllocator { page_list.entry_num - 1 ); } - // kdebug!("entry={entry:?}"); + // debug!("entry={entry:?}"); // 更新page_list的entry_num page_list.entry_num -= 1; @@ -302,7 +304,7 @@ impl BuddyAllocator { return None; }; let result: Option = alloc_in_specific_order(order); - // kdebug!("result={:?}", result); + // debug!("result={:?}", result); if result.is_some() { return result; } @@ -312,14 +314,14 @@ impl BuddyAllocator { let mut x: Option = None; while current_order < MAX_ORDER { x = alloc_in_specific_order(current_order as u8); - // kdebug!("current_order={:?}", current_order); + // debug!("current_order={:?}", current_order); if x.is_some() { break; } current_order += 1; } - // kdebug!("x={:?}", x); + // debug!("x={:?}", x); // 如果找到一个大的块,就进行分裂 if x.is_some() { // 分裂到order阶 @@ -328,8 +330,8 @@ impl BuddyAllocator { // 把后面那半块放回空闲链表 let buddy = *x.as_ref().unwrap() + (1 << current_order); - // kdebug!("x={:?}, buddy={:?}", x, buddy); - // kdebug!("current_order={:?}, buddy={:?}", current_order, buddy); + // debug!("x={:?}, buddy={:?}", x, buddy); + // debug!("current_order={:?}, buddy={:?}", current_order, buddy); unsafe { self.buddy_free(buddy, current_order as u8) }; } return x; @@ -359,10 +361,10 @@ impl BuddyAllocator { return None; } - // kdebug!("buddy_alloc: order = {}", order); + // debug!("buddy_alloc: order = {}", order); // 获取该阶数的一个空闲页面 let free_addr = self.pop_front(order); - // kdebug!( + // debug!( // "buddy_alloc: order = {}, free_addr = {:?}", // order, // free_addr @@ -378,7 +380,7 @@ impl BuddyAllocator { /// - `base` - 块的起始地址 /// - `order` - 块的阶数 unsafe fn buddy_free(&mut self, mut base: PhysAddr, order: u8) { - // kdebug!("buddy_free: base = {:?}, order = {}", base, order); + // debug!("buddy_free: base = {:?}, order = {}", base, order); let mut order = order as usize; while order < MAX_ORDER { @@ -557,7 +559,7 @@ impl BuddyAllocator { (first_page_list_paddr, first_page_list) }; - // kdebug!("to write entry, page_list_base={paddr:?}, page_list.entry_num={}, value={base:?}", page_list.entry_num); + // debug!("to write entry, page_list_base={paddr:?}, page_list.entry_num={}, value={base:?}", page_list.entry_num); assert!(page_list.entry_num < Self::BUDDY_ENTRIES); // 把要归还的块,写入到链表项中 unsafe { A::write(Self::entry_virt_addr(paddr, page_list.entry_num), base) } @@ -591,14 +593,14 @@ impl FrameAllocator for BuddyAllocator { unsafe fn free(&mut self, base: PhysAddr, count: PageFrameCount) { // 要求count是2的幂 if unlikely(!count.data().is_power_of_two()) { - kwarn!("buddy free: count is not power of two"); + warn!("buddy free: count is not power of two"); } let mut order = log2(count.data()); if count.data() & ((1 << order) - 1) != 0 { order += 1; } let order = (order + MIN_ORDER) as u8; - // kdebug!("free: base={:?}, count={:?}", base, count); + // debug!("free: base={:?}, count={:?}", base, count); self.buddy_free(base, order); } diff --git a/kernel/src/mm/allocator/slab.rs b/kernel/src/mm/allocator/slab.rs index a21d4ca9..710f9b7b 100644 --- a/kernel/src/mm/allocator/slab.rs +++ b/kernel/src/mm/allocator/slab.rs @@ -1,6 +1,7 @@ use core::{alloc::Layout, ptr::NonNull, sync::atomic::AtomicBool}; use alloc::boxed::Box; +use log::debug; use slabmalloc::*; // 全局slab分配器 @@ -18,7 +19,7 @@ pub(crate) struct SlabAllocator { impl SlabAllocator { /// 创建slab分配器 pub fn new() -> SlabAllocator { - kdebug!("trying to new a slab_allocator"); + debug!("trying to new a slab_allocator"); SlabAllocator { zone: ZoneAllocator::new(), } @@ -62,7 +63,7 @@ impl SlabAllocator { /// 初始化slab分配器 pub unsafe fn slab_init() { - kdebug!("trying to init a slab_allocator"); + debug!("trying to init a slab_allocator"); SLABALLOCATOR = Some(SlabAllocator::new()); SLABINITSTATE = true.into(); } diff --git a/kernel/src/mm/c_adapter.rs b/kernel/src/mm/c_adapter.rs index 35ac24de..bd949fa5 100644 --- a/kernel/src/mm/c_adapter.rs +++ b/kernel/src/mm/c_adapter.rs @@ -4,11 +4,11 @@ use core::intrinsics::unlikely; use alloc::vec::Vec; use hashbrown::HashMap; +use log::error; use system_error::SystemError; use crate::{ include::bindings::bindings::{gfp_t, PAGE_U_S}, - kerror, libs::{align::page_align_up, spinlock::SpinLock}, mm::MMArch, }; @@ -38,7 +38,7 @@ pub unsafe extern "C" fn rs_map_phys(vaddr: usize, paddr: usize, size: usize, fl let mut vaddr = VirtAddr::new(vaddr); let mut paddr = PhysAddr::new(paddr); let count = PageFrameCount::new(page_align_up(size) / MMArch::PAGE_SIZE); - // kdebug!("rs_map_phys: vaddr: {vaddr:?}, paddr: {paddr:?}, count: {count:?}, flags: {flags:?}"); + // debug!("rs_map_phys: vaddr: {vaddr:?}, paddr: {paddr:?}, count: {count:?}, flags: {flags:?}"); let mut page_flags: PageFlags = PageFlags::new().set_execute(true).set_write(true); if flags & PAGE_U_S as usize != 0 { @@ -64,13 +64,13 @@ pub unsafe extern "C" fn rs_map_phys(vaddr: usize, paddr: usize, size: usize, fl #[no_mangle] pub unsafe extern "C" fn kzalloc(size: usize, _gfp: gfp_t) -> usize { - // kdebug!("kzalloc: size: {size}"); + // debug!("kzalloc: size: {size}"); return do_kmalloc(size, true); } #[no_mangle] pub unsafe extern "C" fn kmalloc(size: usize, _gfp: gfp_t) -> usize { - // kdebug!("kmalloc: size: {size}"); + // debug!("kmalloc: size: {size}"); // 由于C代码不规范,因此都全部清空 return do_kmalloc(size, true); } @@ -109,7 +109,7 @@ pub unsafe extern "C" fn kfree(vaddr: usize) -> usize { drop(guard); if p.is_none() { - kerror!("kfree: vaddr {:?} not found in C Allocation Map", vaddr); + error!("kfree: vaddr {:?} not found in C Allocation Map", vaddr); return SystemError::EINVAL.to_posix_errno() as i64 as usize; } let (vaddr, len, cap) = p.unwrap(); @@ -135,7 +135,7 @@ unsafe extern "C" fn rs_mmio_create( res_vaddr: *mut u64, res_length: *mut u64, ) -> i32 { - // kdebug!("mmio_create"); + // debug!("mmio_create"); let r = mmio_pool().create_mmio(size as usize); if let Err(e) = r { return e.to_posix_errno(); diff --git a/kernel/src/mm/early_ioremap.rs b/kernel/src/mm/early_ioremap.rs index 225002b9..0daec616 100644 --- a/kernel/src/mm/early_ioremap.rs +++ b/kernel/src/mm/early_ioremap.rs @@ -45,7 +45,7 @@ impl EarlyIoRemap { mut size: usize, read_only: bool, ) -> Result { - // kdebug!("map not aligned phys:{phys:?}, size:{size:?}, read_only:{read_only:?}"); + // debug!("map not aligned phys:{phys:?}, size:{size:?}, read_only:{read_only:?}"); let offset = phys.data() - page_align_down(phys.data()); size += offset; @@ -82,7 +82,7 @@ impl EarlyIoRemap { return Err(SystemError::EINVAL); } - // kdebug!("Early io remap:{phys:?}, size:{size}"); + // debug!("Early io remap:{phys:?}, size:{size}"); let mut slot_guard = SLOTS.lock(); @@ -111,7 +111,7 @@ impl EarlyIoRemap { let start_slot = start_slot.ok_or(SystemError::ENOMEM)?; let vaddr = Self::idx_to_virt(start_slot); - // kdebug!("start_slot:{start_slot}, vaddr: {vaddr:?}, slot_count: {slot_count:?}"); + // debug!("start_slot:{start_slot}, vaddr: {vaddr:?}, slot_count: {slot_count:?}"); let page_count = PageFrameCount::new(slot_count); // 执行映射 if read_only { @@ -120,7 +120,7 @@ impl EarlyIoRemap { unsafe { pseudo_map_phys(vaddr, phys, page_count) } } - // kdebug!("map ok"); + // debug!("map ok"); // 更新slot信息 let map_size = slot_count * MMArch::PAGE_SIZE; diff --git a/kernel/src/mm/init.rs b/kernel/src/mm/init.rs index 0c8549b0..0f44ef7c 100644 --- a/kernel/src/mm/init.rs +++ b/kernel/src/mm/init.rs @@ -1,5 +1,7 @@ use core::{fmt::Write, sync::atomic::Ordering}; +use log::info; + use crate::{ arch::MMArch, driver::serial::serial8250::send_to_default_serial8250_port, @@ -65,7 +67,7 @@ pub unsafe fn mm_init() { ) .unwrap(); MMArch::arch_post_init(); - kinfo!("mm init done."); + info!("mm init done."); } /// 获取内存管理的初始化状态 diff --git a/kernel/src/mm/kernel_mapper.rs b/kernel/src/mm/kernel_mapper.rs index 02436189..682fad60 100644 --- a/kernel/src/mm/kernel_mapper.rs +++ b/kernel/src/mm/kernel_mapper.rs @@ -112,7 +112,7 @@ impl KernelMapper { } let count = PageFrameCount::new(page_align_up(size) / MMArch::PAGE_SIZE); - // kdebug!("kernel mapper: map_phys: vaddr: {vaddr:?}, paddr: {paddr:?}, count: {count:?}, flags: {flags:?}"); + // debug!("kernel mapper: map_phys: vaddr: {vaddr:?}, paddr: {paddr:?}, count: {count:?}, flags: {flags:?}"); for _ in 0..count.data() { let flusher = self.mapper.map_phys(vaddr, paddr, flags).unwrap(); diff --git a/kernel/src/mm/memblock.rs b/kernel/src/mm/memblock.rs index 4ecbee52..d17bd343 100644 --- a/kernel/src/mm/memblock.rs +++ b/kernel/src/mm/memblock.rs @@ -1,5 +1,6 @@ use core::intrinsics::unlikely; +use log::error; use system_error::SystemError; use crate::libs::{ @@ -88,7 +89,7 @@ impl MemBlockManager { .expect("Failed to count blocks to add!"); if inner.initial_memory_regions_num + blocks_to_add > INITIAL_MEMORY_REGIONS_NUM { - kerror!("Too many memory regions!"); + error!("Too many memory regions!"); return Err(SystemError::ENOMEM); } @@ -203,7 +204,7 @@ impl MemBlockManager { if this.base + this.size != next_base || this.flags != next_flags { if unlikely(this.base + this.size > next_base) { - kBUG!("this->base + this->size > next->base"); + panic!("this->base + this->size > next->base"); } i += 1; continue; diff --git a/kernel/src/mm/mmio_buddy.rs b/kernel/src/mm/mmio_buddy.rs index 0c500572..99e845d3 100644 --- a/kernel/src/mm/mmio_buddy.rs +++ b/kernel/src/mm/mmio_buddy.rs @@ -2,16 +2,14 @@ use crate::libs::align::{page_align_down, page_align_up}; use crate::libs::spinlock::{SpinLock, SpinLockGuard}; use crate::mm::kernel_mapper::KernelMapper; use crate::mm::page::{PAGE_1G_SHIFT, PAGE_4K_SHIFT}; +use crate::mm::{MMArch, MemoryManagementArch}; use crate::process::ProcessManager; -use crate::{ - kdebug, - mm::{MMArch, MemoryManagementArch}, -}; -use crate::{kerror, kinfo, kwarn}; + use alloc::{collections::LinkedList, vec::Vec}; use core::mem; use core::mem::MaybeUninit; use core::sync::atomic::{AtomicBool, Ordering}; +use log::{debug, error, info, warn}; use system_error::SystemError; use super::page::{PageFlags, PAGE_4K_SIZE}; @@ -69,11 +67,11 @@ impl MmioBuddyMemPool { }; assert!(pool.pool_start_addr.data() % PAGE_1G_SIZE == 0); - kdebug!("MMIO buddy pool init: created"); + debug!("MMIO buddy pool init: created"); let mut vaddr_base = MMArch::MMIO_BASE; let mut remain_size = MMArch::MMIO_SIZE; - kdebug!( + debug!( "BASE: {:?}, TOP: {:?}, size: {:?}", MMArch::MMIO_BASE, MMArch::MMIO_TOP, @@ -92,7 +90,7 @@ impl MmioBuddyMemPool { } } - kdebug!("MMIO buddy pool init success"); + debug!("MMIO buddy pool init success"); return pool; } @@ -102,11 +100,11 @@ impl MmioBuddyMemPool { /// /// @return 创建好的地址区域结构体 fn create_region(&self, vaddr: VirtAddr) -> MmioBuddyAddrRegion { - // kdebug!("create_region for vaddr: {vaddr:?}"); + // debug!("create_region for vaddr: {vaddr:?}"); let region: MmioBuddyAddrRegion = MmioBuddyAddrRegion::new(vaddr); - // kdebug!("create_region for vaddr: {vaddr:?} OK!!!"); + // debug!("create_region for vaddr: {vaddr:?} OK!!!"); return region; } @@ -172,7 +170,7 @@ impl MmioBuddyMemPool { ) -> Result { // 申请范围错误 if !(MMIO_BUDDY_MIN_EXP..=MMIO_BUDDY_MAX_EXP).contains(&exp) { - kdebug!("query_addr_region: exp wrong"); + debug!("query_addr_region: exp wrong"); return Err(MmioResult::WRONGEXP); } // 没有恰好符合要求的内存块 @@ -203,7 +201,7 @@ impl MmioBuddyMemPool { } } Err(err) => { - kdebug!("buddy_pop_region get wrong"); + debug!("buddy_pop_region get wrong"); return Err(err); } } @@ -222,7 +220,7 @@ impl MmioBuddyMemPool { } } Err(err) => { - kdebug!("buddy_pop_region get wrong"); + debug!("buddy_pop_region get wrong"); return Err(err); } } @@ -262,7 +260,7 @@ impl MmioBuddyMemPool { ) { Ok(_) => continue, Err(err) => { - kdebug!("merge_all_exp get wrong"); + debug!("merge_all_exp get wrong"); return Err(err); } } @@ -274,7 +272,7 @@ impl MmioBuddyMemPool { ) { Ok(_) => continue, Err(err) => { - kdebug!("merge_all_exp get wrong"); + debug!("merge_all_exp get wrong"); return Err(err); } } @@ -309,7 +307,7 @@ impl MmioBuddyMemPool { match self.query_addr_region(exp, &mut list_guard) { Ok(ret) => return Ok(ret), Err(err) => { - kdebug!("mmio_buddy_query_addr_region failed"); + debug!("mmio_buddy_query_addr_region failed"); return Err(err); } } @@ -433,7 +431,7 @@ impl MmioBuddyMemPool { Err(err) => { // 如果合并失败了要将取出来的元素放回去 self.push_block(copy_region, list_guard); - kdebug!("merge_all_exp: merge_blocks failed"); + debug!("merge_all_exp: merge_blocks failed"); return Err(err); } Ok(_) => continue, @@ -489,7 +487,7 @@ impl MmioBuddyMemPool { // 计算前导0 #[cfg(any(target_arch = "x86_64", target_arch = "riscv64"))] let mut size_exp: u32 = 63 - size.leading_zeros(); - // kdebug!("create_mmio: size_exp: {}", size_exp); + // debug!("create_mmio: size_exp: {}", size_exp); // 记录最终申请的空间大小 let mut new_size = size; // 对齐要申请的空间大小 @@ -509,7 +507,7 @@ impl MmioBuddyMemPool { return Ok(space_guard); } Err(_) => { - kerror!( + error!( "failed to create mmio. pid = {:?}", ProcessManager::current_pcb().pid() ); @@ -543,7 +541,7 @@ impl MmioBuddyMemPool { let mut bindings = KernelMapper::lock(); let mut kernel_mapper = bindings.as_mut(); if kernel_mapper.is_none() { - kwarn!("release_mmio: kernel_mapper is read only"); + warn!("release_mmio: kernel_mapper is read only"); return Err(SystemError::EAGAIN_OR_EWOULDBLOCK); } @@ -735,11 +733,11 @@ impl Drop for MMIOSpaceGuard { } pub fn mmio_init() { - kdebug!("Initializing MMIO buddy memory pool..."); + debug!("Initializing MMIO buddy memory pool..."); // 初始化mmio内存池 unsafe { __MMIO_POOL = Some(MmioBuddyMemPool::new()); } - kinfo!("MMIO buddy memory pool init done"); + info!("MMIO buddy memory pool init done"); } diff --git a/kernel/src/mm/page.rs b/kernel/src/mm/page.rs index 0bc5d5b5..eb75c3ee 100644 --- a/kernel/src/mm/page.rs +++ b/kernel/src/mm/page.rs @@ -8,12 +8,12 @@ use core::{ use alloc::sync::Arc; use hashbrown::{HashMap, HashSet}; +use log::{error, info}; use crate::{ arch::{interrupt::ipi::send_ipi, MMArch}, exception::ipi::{IpiKind, IpiTarget}, ipc::shm::ShmId, - kerror, libs::spinlock::{SpinLock, SpinLockGuard}, }; @@ -37,14 +37,14 @@ pub static mut PAGE_MANAGER: Option> = None; /// 初始化PAGE_MANAGER pub fn page_manager_init() { - kinfo!("page_manager_init"); + info!("page_manager_init"); let page_manager = SpinLock::new(PageManager::new()); compiler_fence(Ordering::SeqCst); unsafe { PAGE_MANAGER = Some(page_manager) }; compiler_fence(Ordering::SeqCst); - kinfo!("page_manager_init done"); + info!("page_manager_init done"); } pub fn page_manager_lock_irqsave() -> SpinLockGuard<'static, PageManager> { @@ -879,10 +879,9 @@ impl PageMapper { ) -> Option> { // 验证虚拟地址和物理地址是否对齐 if !(virt.check_aligned(Arch::PAGE_SIZE) && phys.check_aligned(Arch::PAGE_SIZE)) { - kerror!( + error!( "Try to map unaligned page: virt={:?}, phys={:?}", - virt, - phys + virt, phys ); return None; } @@ -908,7 +907,7 @@ impl PageMapper { let next_table = table.next_level_table(i); if let Some(next_table) = next_table { table = next_table; - // kdebug!("Mapping {:?} to next level table...", virt); + // debug!("Mapping {:?} to next level table...", virt); } else { // 分配下一级页表 let frame = self.frame_allocator.allocate_one()?; @@ -937,7 +936,7 @@ impl PageMapper { ) -> Option> { // 验证虚拟地址是否对齐 if !(virt.check_aligned(Arch::PAGE_SIZE)) { - kerror!("Try to map unaligned page: virt={:?}", virt); + error!("Try to map unaligned page: virt={:?}", virt); return None; } @@ -1184,7 +1183,7 @@ impl PageMapper { unmap_parents: bool, ) -> Option<(PhysAddr, PageFlags, PageFlush)> { if !virt.check_aligned(Arch::PAGE_SIZE) { - kerror!("Try to unmap unaligned page: virt={:?}", virt); + error!("Try to unmap unaligned page: virt={:?}", virt); return None; } diff --git a/kernel/src/mm/syscall.rs b/kernel/src/mm/syscall.rs index 99997ee5..16bca4d3 100644 --- a/kernel/src/mm/syscall.rs +++ b/kernel/src/mm/syscall.rs @@ -1,12 +1,12 @@ use core::intrinsics::unlikely; use alloc::sync::Arc; +use log::error; use system_error::SystemError; use crate::{ arch::MMArch, ipc::shm::ShmFlags, - kerror, libs::align::{check_aligned, page_align_up}, mm::MemoryManagementArch, syscall::Syscall, @@ -246,7 +246,7 @@ impl From for ProtFlags { impl Syscall { pub fn brk(new_addr: VirtAddr) -> Result { - // kdebug!("brk: new_addr={:?}", new_addr); + // debug!("brk: new_addr={:?}", new_addr); let address_space = AddressSpace::current()?; let mut address_space = address_space.write(); @@ -305,7 +305,7 @@ impl Syscall { if start_vaddr < VirtAddr::new(DEFAULT_MMAP_MIN_ADDR) && map_flags.contains(MapFlags::MAP_FIXED) { - kerror!( + error!( "mmap: MAP_FIXED is not supported for address below {}", DEFAULT_MMAP_MIN_ADDR ); @@ -313,13 +313,13 @@ impl Syscall { } // 暂时不支持除匿名页以外的映射 if !map_flags.contains(MapFlags::MAP_ANONYMOUS) { - kerror!("mmap: not support file mapping"); + error!("mmap: not support file mapping"); return Err(SystemError::ENOSYS); } // 暂时不支持巨页映射 if map_flags.contains(MapFlags::MAP_HUGETLB) { - kerror!("mmap: not support huge page mapping"); + error!("mmap: not support huge page mapping"); return Err(SystemError::ENOSYS); } let current_address_space = AddressSpace::current()?; @@ -394,7 +394,7 @@ impl Syscall { // 暂时不支持巨页映射 if vm_flags.contains(VmFlags::VM_HUGETLB) { - kerror!("mmap: not support huge page mapping"); + error!("mmap: not support huge page mapping"); return Err(SystemError::ENOSYS); } diff --git a/kernel/src/mm/ucontext.rs b/kernel/src/mm/ucontext.rs index 8d030e2b..1919ddee 100644 --- a/kernel/src/mm/ucontext.rs +++ b/kernel/src/mm/ucontext.rs @@ -143,7 +143,7 @@ impl InnerAddressSpace { end_data: VirtAddr(0), }; if create_stack { - // kdebug!("to create user stack."); + // debug!("to create user stack."); result.new_user_stack(UserStack::DEFAULT_USER_STACK_SIZE)?; } @@ -183,7 +183,7 @@ impl InnerAddressSpace { // 仅拷贝VMA信息并添加反向映射,因为UserMapper克隆时已经分配了新的物理页 let new_vma = LockedVMA::new(vma_guard.clone_info_only()); new_guard.mappings.vmas.insert(new_vma.clone()); - // kdebug!("new vma: {:x?}", new_vma); + // debug!("new vma: {:x?}", new_vma); let new_vma_guard = new_vma.lock(); let new_mapper = &new_guard.user_mapper.utable; let mut anon_vma_guard = page_manager_lock_irqsave(); @@ -209,7 +209,7 @@ impl InnerAddressSpace { /// - `bytes`: 拓展大小 #[allow(dead_code)] pub fn extend_stack(&mut self, mut bytes: usize) -> Result<(), SystemError> { - // kdebug!("extend user stack"); + // debug!("extend user stack"); let prot_flags = ProtFlags::PROT_READ | ProtFlags::PROT_WRITE | ProtFlags::PROT_EXEC; let map_flags = MapFlags::MAP_PRIVATE | MapFlags::MAP_ANONYMOUS | MapFlags::MAP_GROWSDOWN; let stack = self.user_stack.as_mut().unwrap(); @@ -259,7 +259,7 @@ impl InnerAddressSpace { let round_hint_to_min = |hint: VirtAddr| { // 先把hint向下对齐到页边界 let addr = hint.data() & (!MMArch::PAGE_OFFSET_MASK); - // kdebug!("map_anonymous: hint = {:?}, addr = {addr:#x}", hint); + // debug!("map_anonymous: hint = {:?}, addr = {addr:#x}", hint); // 如果hint不是0,且hint小于DEFAULT_MMAP_MIN_ADDR,则对齐到DEFAULT_MMAP_MIN_ADDR if (addr != 0) && round_to_min && (addr < DEFAULT_MMAP_MIN_ADDR) { Some(VirtAddr::new(page_align_up(DEFAULT_MMAP_MIN_ADDR))) @@ -269,8 +269,8 @@ impl InnerAddressSpace { Some(VirtAddr::new(addr)) } }; - // kdebug!("map_anonymous: start_vaddr = {:?}", start_vaddr); - // kdebug!("map_anonymous: len(no align) = {}", len); + // debug!("map_anonymous: start_vaddr = {:?}", start_vaddr); + // debug!("map_anonymous: len(no align) = {}", len); let len = page_align_up(len); @@ -280,7 +280,7 @@ impl InnerAddressSpace { | VmFlags::VM_MAYWRITE | VmFlags::VM_MAYEXEC; - // kdebug!("map_anonymous: len = {}", len); + // debug!("map_anonymous: len = {}", len); let start_page: VirtPageFrame = if allocate_at_once { self.mmap( @@ -348,7 +348,7 @@ impl InnerAddressSpace { if page_count == PageFrameCount::new(0) { return Err(SystemError::EINVAL); } - // kdebug!("mmap: addr: {addr:?}, page_count: {page_count:?}, prot_flags: {prot_flags:?}, map_flags: {map_flags:?}"); + // debug!("mmap: addr: {addr:?}, page_count: {page_count:?}, prot_flags: {prot_flags:?}, map_flags: {map_flags:?}"); // 找到未使用的区域 let region = match addr { @@ -364,7 +364,7 @@ impl InnerAddressSpace { let page = VirtPageFrame::new(region.start()); - // kdebug!("mmap: page: {:?}, region={region:?}", page.virt_address()); + // debug!("mmap: page: {:?}, region={region:?}", page.virt_address()); compiler_fence(Ordering::SeqCst); let (mut active, mut inactive); @@ -510,7 +510,7 @@ impl InnerAddressSpace { page_count: PageFrameCount, prot_flags: ProtFlags, ) -> Result<(), SystemError> { - // kdebug!( + // debug!( // "mprotect: start_page: {:?}, page_count: {:?}, prot_flags:{prot_flags:?}", // start_page, // page_count @@ -526,13 +526,13 @@ impl InnerAddressSpace { let mapper = &mut self.user_mapper.utable; let region = VirtRegion::new(start_page.virt_address(), page_count.bytes()); - // kdebug!("mprotect: region: {:?}", region); + // debug!("mprotect: region: {:?}", region); let regions = self.mappings.conflicts(region).collect::>(); - // kdebug!("mprotect: regions: {:?}", regions); + // debug!("mprotect: regions: {:?}", regions); for r in regions { - // kdebug!("mprotect: r: {:?}", r); + // debug!("mprotect: r: {:?}", r); let r = *r.lock().region(); let r = self.mappings.remove_vma(&r).unwrap(); @@ -1340,7 +1340,7 @@ impl VMA { mut flusher: impl Flusher, ) -> Result<(), SystemError> { for page in self.region.pages() { - // kdebug!("remap page {:?}", page.virt_address()); + // debug!("remap page {:?}", page.virt_address()); if mapper.translate(page.virt_address()).is_some() { let r = unsafe { mapper @@ -1349,8 +1349,8 @@ impl VMA { }; flusher.consume(r); } - // kdebug!("consume page {:?}", page.virt_address()); - // kdebug!("remap page {:?} done", page.virt_address()); + // debug!("consume page {:?}", page.virt_address()); + // debug!("remap page {:?} done", page.virt_address()); } self.flags = flags; return Ok(()); @@ -1451,12 +1451,12 @@ impl VMA { mut flusher: impl Flusher, ) -> Result, SystemError> { let mut cur_dest: VirtPageFrame = destination; - // kdebug!( + // debug!( // "VMA::zeroed: page_count = {:?}, destination={destination:?}", // page_count // ); for _ in 0..page_count.data() { - // kdebug!( + // debug!( // "VMA::zeroed: cur_dest={cur_dest:?}, vaddr = {:?}", // cur_dest.virt_address() // ); @@ -1478,7 +1478,7 @@ impl VMA { true, )); drop(flusher); - // kdebug!("VMA::zeroed: flusher dropped"); + // debug!("VMA::zeroed: flusher dropped"); // 清空这些内存并将VMA加入到anon_vma中 let mut page_manager_guard = page_manager_lock_irqsave(); @@ -1497,7 +1497,7 @@ impl VMA { MMArch::write_bytes(vaddr, 0, MMArch::PAGE_SIZE); } } - // kdebug!("VMA::zeroed: done"); + // debug!("VMA::zeroed: done"); return Ok(r); } } @@ -1565,7 +1565,7 @@ impl UserStack { | MapFlags::MAP_ANONYMOUS | MapFlags::MAP_FIXED_NOREPLACE | MapFlags::MAP_GROWSDOWN; - // kdebug!( + // debug!( // "map anonymous stack: {:?} {}", // actual_stack_bottom, // guard_size @@ -1581,7 +1581,7 @@ impl UserStack { // test_buddy(); // 设置保护页只读 prot_flags.remove(ProtFlags::PROT_WRITE); - // kdebug!( + // debug!( // "to mprotect stack guard pages: {:?} {}", // actual_stack_bottom, // guard_size @@ -1592,7 +1592,7 @@ impl UserStack { prot_flags, )?; - // kdebug!( + // debug!( // "mprotect stack guard pages done: {:?} {}", // actual_stack_bottom, // guard_size @@ -1604,10 +1604,10 @@ impl UserStack { current_sp: actual_stack_bottom - guard_size, }; - // kdebug!("extend user stack: {:?} {}", stack_bottom, stack_size); + // debug!("extend user stack: {:?} {}", stack_bottom, stack_size); // 分配用户栈 user_stack.initial_extend(vm, stack_size)?; - // kdebug!("user stack created: {:?} {}", stack_bottom, stack_size); + // debug!("user stack created: {:?} {}", stack_bottom, stack_size); return Ok(user_stack); } diff --git a/kernel/src/net/event_poll/mod.rs b/kernel/src/net/event_poll/mod.rs index 0691278b..de80368e 100644 --- a/kernel/src/net/event_poll/mod.rs +++ b/kernel/src/net/event_poll/mod.rs @@ -566,7 +566,7 @@ impl EventPoll { // 记数加一 res += 1; - // crate::kdebug!("ep send {event:?}"); + // crate::debug!("ep send {event:?}"); if ep_events.contains(EPollEventType::EPOLLONESHOT) { let mut event_writer = epitem.event.write(); diff --git a/kernel/src/net/net_core.rs b/kernel/src/net/net_core.rs index b555a098..7a36e3fe 100644 --- a/kernel/src/net/net_core.rs +++ b/kernel/src/net/net_core.rs @@ -1,10 +1,10 @@ use alloc::{boxed::Box, collections::BTreeMap, sync::Arc}; +use log::{debug, info, warn}; use smoltcp::{socket::dhcpv4, wire}; use system_error::SystemError; use crate::{ driver::net::NetDevice, - kdebug, kinfo, kwarn, libs::rwlock::RwLockReadGuard, net::{socket::SocketPollMethod, NET_DEVICES}, time::timer::{next_n_ms_timer_jiffies, Timer, TimerFunction}, @@ -60,7 +60,7 @@ fn dhcp_query() -> Result<(), SystemError> { const DHCP_TRY_ROUND: u8 = 10; for i in 0..DHCP_TRY_ROUND { - kdebug!("DHCP try round: {}", i); + debug!("DHCP try round: {}", i); net_face.poll(&mut SOCKET_SET.lock_irqsave()).ok(); let mut binding = SOCKET_SET.lock_irqsave(); let event = binding.get_mut::(dhcp_handle).poll(); @@ -69,9 +69,9 @@ fn dhcp_query() -> Result<(), SystemError> { None => {} Some(dhcpv4::Event::Configured(config)) => { - // kdebug!("Find Config!! {config:?}"); - // kdebug!("Find ip address: {}", config.address); - // kdebug!("iface.ip_addrs={:?}", net_face.inner_iface.ip_addrs()); + // debug!("Find Config!! {config:?}"); + // debug!("Find ip address: {}", config.address); + // debug!("iface.ip_addrs={:?}", net_face.inner_iface.ip_addrs()); net_face .update_ip_addrs(&[wire::IpCidr::Ipv4(config.address)]) @@ -86,7 +86,7 @@ fn dhcp_query() -> Result<(), SystemError> { .unwrap(); let cidr = net_face.inner_iface().lock().ip_addrs().first().cloned(); if let Some(cidr) = cidr { - kinfo!("Successfully allocated ip by Dhcpv4! Ip:{}", cidr); + info!("Successfully allocated ip by Dhcpv4! Ip:{}", cidr); return Ok(()); } } else { @@ -99,7 +99,7 @@ fn dhcp_query() -> Result<(), SystemError> { } Some(dhcpv4::Event::Deconfigured) => { - kdebug!("Dhcp v4 deconfigured"); + debug!("Dhcp v4 deconfigured"); net_face .update_ip_addrs(&[smoltcp::wire::IpCidr::Ipv4(wire::Ipv4Cidr::new( wire::Ipv4Address::UNSPECIFIED, @@ -121,7 +121,7 @@ fn dhcp_query() -> Result<(), SystemError> { pub fn poll_ifaces() { let guard: RwLockReadGuard>> = NET_DEVICES.read_irqsave(); if guard.len() == 0 { - kwarn!("poll_ifaces: No net driver found!"); + warn!("poll_ifaces: No net driver found!"); return; } let mut sockets = SOCKET_SET.lock_irqsave(); @@ -142,7 +142,7 @@ pub fn poll_ifaces_try_lock(times: u16) -> Result<(), SystemError> { let guard: RwLockReadGuard>> = NET_DEVICES.read_irqsave(); if guard.len() == 0 { - kwarn!("poll_ifaces: No net driver found!"); + warn!("poll_ifaces: No net driver found!"); // 没有网卡,返回错误 return Err(SystemError::ENODEV); } @@ -172,7 +172,7 @@ pub fn poll_ifaces_try_lock(times: u16) -> Result<(), SystemError> { pub fn poll_ifaces_try_lock_onetime() -> Result<(), SystemError> { let guard: RwLockReadGuard>> = NET_DEVICES.read_irqsave(); if guard.len() == 0 { - kwarn!("poll_ifaces: No net driver found!"); + warn!("poll_ifaces: No net driver found!"); // 没有网卡,返回错误 return Err(SystemError::ENODEV); } @@ -234,7 +234,7 @@ fn send_event(sockets: &smoltcp::iface::SocketSet) -> Result<(), SystemError> { EPollEventType::from_bits_truncate(events as u32), )?; drop(handle_guard); - // crate::kdebug!( + // crate::debug!( // "{} send_event {:?}", // handle, // EPollEventType::from_bits_truncate(events as u32) diff --git a/kernel/src/net/socket/inet.rs b/kernel/src/net/socket/inet.rs index 09ceea96..114fb54d 100644 --- a/kernel/src/net/socket/inet.rs +++ b/kernel/src/net/socket/inet.rs @@ -1,4 +1,5 @@ use alloc::{boxed::Box, sync::Arc, vec::Vec}; +use log::{error, warn}; use smoltcp::{ socket::{raw, tcp, udp}, wire, @@ -7,7 +8,6 @@ use system_error::SystemError; use crate::{ driver::net::NetDevice, - kerror, kwarn, libs::rwlock::RwLock, net::{ event_poll::EPollEventType, net_core::poll_ifaces, Endpoint, Protocol, ShutdownType, @@ -197,7 +197,7 @@ impl Socket for RawSocket { drop(socket_set_guard); return Ok(len); } else { - kwarn!("Unsupport Ip protocol type!"); + warn!("Unsupport Ip protocol type!"); return Err(SystemError::EINVAL); } } else { @@ -325,13 +325,13 @@ impl Socket for UdpSocket { /// @brief 在read函数执行之前,请先bind到本地的指定端口 fn read(&self, buf: &mut [u8]) -> (Result, Endpoint) { loop { - // kdebug!("Wait22 to Read"); + // debug!("Wait22 to Read"); poll_ifaces(); let mut socket_set_guard = SOCKET_SET.lock_irqsave(); let socket = socket_set_guard.get_mut::(self.handle.smoltcp_handle().unwrap()); - // kdebug!("Wait to Read"); + // debug!("Wait to Read"); if socket.can_recv() { if let Ok((size, metadata)) = socket.recv_slice(buf) { @@ -353,7 +353,7 @@ impl Socket for UdpSocket { } fn write(&self, buf: &[u8], to: Option) -> Result { - // kdebug!("udp to send: {:?}, len={}", to, buf.len()); + // debug!("udp to send: {:?}, len={}", to, buf.len()); let remote_endpoint: &wire::IpEndpoint = { if let Some(Endpoint::Ip(Some(ref endpoint))) = to { endpoint @@ -363,28 +363,28 @@ impl Socket for UdpSocket { return Err(SystemError::ENOTCONN); } }; - // kdebug!("udp write: remote = {:?}", remote_endpoint); + // debug!("udp write: remote = {:?}", remote_endpoint); let mut socket_set_guard = SOCKET_SET.lock_irqsave(); let socket = socket_set_guard.get_mut::(self.handle.smoltcp_handle().unwrap()); - // kdebug!("is open()={}", socket.is_open()); - // kdebug!("socket endpoint={:?}", socket.endpoint()); + // debug!("is open()={}", socket.is_open()); + // debug!("socket endpoint={:?}", socket.endpoint()); if socket.can_send() { - // kdebug!("udp write: can send"); + // debug!("udp write: can send"); match socket.send_slice(buf, *remote_endpoint) { Ok(()) => { - // kdebug!("udp write: send ok"); + // debug!("udp write: send ok"); drop(socket_set_guard); poll_ifaces(); return Ok(buf.len()); } Err(_) => { - // kdebug!("udp write: send err"); + // debug!("udp write: send err"); return Err(SystemError::ENOBUFS); } } } else { - // kdebug!("udp write: can not send"); + // debug!("udp write: can not send"); return Err(SystemError::ENOBUFS); }; } @@ -392,7 +392,7 @@ impl Socket for UdpSocket { fn bind(&mut self, endpoint: Endpoint) -> Result<(), SystemError> { let mut sockets = SOCKET_SET.lock_irqsave(); let socket = sockets.get_mut::(self.handle.smoltcp_handle().unwrap()); - // kdebug!("UDP Bind to {:?}", endpoint); + // debug!("UDP Bind to {:?}", endpoint); return self.do_bind(socket, endpoint); } @@ -516,7 +516,7 @@ impl TcpSocket { Self::DEFAULT_METADATA_BUF_SIZE, options, ); - // kdebug!("when there's a new tcp socket,its'len: {}",handles.len()); + // debug!("when there's a new tcp socket,its'len: {}",handles.len()); return Self { handles, @@ -532,15 +532,15 @@ impl TcpSocket { local_endpoint: wire::IpEndpoint, ) -> Result<(), SystemError> { let listen_result = if local_endpoint.addr.is_unspecified() { - // kdebug!("Tcp Socket Listen on port {}", local_endpoint.port); + // debug!("Tcp Socket Listen on port {}", local_endpoint.port); socket.listen(local_endpoint.port) } else { - // kdebug!("Tcp Socket Listen on {local_endpoint}"); + // debug!("Tcp Socket Listen on {local_endpoint}"); socket.listen(local_endpoint) }; return match listen_result { Ok(()) => { - // kdebug!( + // debug!( // "Tcp Socket Listen on {local_endpoint}, open?:{}", // socket.is_open() // ); @@ -578,7 +578,7 @@ impl Socket for TcpSocket { SOCKET_SET .lock_irqsave() .remove(handle.smoltcp_handle().unwrap()); - // kdebug!("[Socket] [TCP] Close: {:?}", handle); + // debug!("[Socket] [TCP] Close: {:?}", handle); } } @@ -592,8 +592,8 @@ impl Socket for TcpSocket { { return (Err(SystemError::ENOTCONN), Endpoint::Ip(None)); } - // kdebug!("tcp socket: read, buf len={}", buf.len()); - // kdebug!("tcp socket:read, socket'len={}",self.handle.len()); + // debug!("tcp socket: read, buf len={}", buf.len()); + // debug!("tcp socket:read, socket'len={}",self.handle.len()); loop { poll_ifaces(); let mut socket_set_guard = SOCKET_SET.lock_irqsave(); @@ -603,7 +603,7 @@ impl Socket for TcpSocket { // 如果socket已经关闭,返回错误 if !socket.is_active() { - // kdebug!("Tcp Socket Read Error, socket is closed"); + // debug!("Tcp Socket Read Error, socket is closed"); return (Err(SystemError::ENOTCONN), Endpoint::Ip(None)); } @@ -623,7 +623,7 @@ impl Socket for TcpSocket { } } Err(tcp::RecvError::InvalidState) => { - kwarn!("Tcp Socket Read Error, InvalidState"); + warn!("Tcp Socket Read Error, InvalidState"); return (Err(SystemError::ENOTCONN), Endpoint::Ip(None)); } Err(tcp::RecvError::Finished) => { @@ -659,7 +659,7 @@ impl Socket for TcpSocket { { return Err(SystemError::ENOTCONN); } - // kdebug!("tcp socket:write, socket'len={}",self.handle.len()); + // debug!("tcp socket:write, socket'len={}",self.handle.len()); let mut socket_set_guard = SOCKET_SET.lock_irqsave(); @@ -675,7 +675,7 @@ impl Socket for TcpSocket { return Ok(size); } Err(e) => { - kerror!("Tcp Socket Write Error {e:?}"); + error!("Tcp Socket Write Error {e:?}"); return Err(SystemError::ENOBUFS); } } @@ -689,7 +689,7 @@ impl Socket for TcpSocket { fn poll(&self) -> EPollEventType { let mut socket_set_guard = SOCKET_SET.lock_irqsave(); - // kdebug!("tcp socket:poll, socket'len={}",self.handle.len()); + // debug!("tcp socket:poll, socket'len={}",self.handle.len()); let socket = socket_set_guard .get_mut::(self.handles.get(0).unwrap().smoltcp_handle().unwrap()); @@ -705,7 +705,7 @@ impl Socket for TcpSocket { fn connect(&mut self, endpoint: Endpoint) -> Result<(), SystemError> { let mut sockets = SOCKET_SET.lock_irqsave(); - // kdebug!("tcp socket:connect, socket'len={}",self.handle.len()); + // debug!("tcp socket:connect, socket'len={}",self.handle.len()); let socket = sockets.get_mut::(self.handles.get(0).unwrap().smoltcp_handle().unwrap()); @@ -715,10 +715,10 @@ impl Socket for TcpSocket { // 检测端口是否被占用 PORT_MANAGER.bind_port(self.metadata.socket_type, temp_port)?; - // kdebug!("temp_port: {}", temp_port); + // debug!("temp_port: {}", temp_port); let iface: Arc = NET_DEVICES.write_irqsave().get(&0).unwrap().clone(); let mut inner_iface = iface.inner_iface().lock(); - // kdebug!("to connect: {ip:?}"); + // debug!("to connect: {ip:?}"); match socket.connect(inner_iface.context(), ip, temp_port) { Ok(()) => { @@ -752,7 +752,7 @@ impl Socket for TcpSocket { } } Err(e) => { - // kerror!("Tcp Socket Connect Error {e:?}"); + // error!("Tcp Socket Connect Error {e:?}"); match e { tcp::ConnectError::InvalidState => return Err(SystemError::EISCONN), tcp::ConnectError::Unaddressable => return Err(SystemError::EADDRNOTAVAIL), @@ -779,7 +779,7 @@ impl Socket for TcpSocket { let backlog = handlen.max(backlog); // 添加剩余需要构建的socket - // kdebug!("tcp socket:before listen, socket'len={}", self.handle_list.len()); + // debug!("tcp socket:before listen, socket'len={}", self.handle_list.len()); let mut handle_guard = HANDLE_MAP.write_irqsave(); let wait_queue = Arc::clone(&handle_guard.get(&self.socket_handle()).unwrap().wait_queue); @@ -790,8 +790,8 @@ impl Socket for TcpSocket { handle_guard.insert(handle, handle_item); handle })); - // kdebug!("tcp socket:listen, socket'len={}",self.handle.len()); - // kdebug!("tcp socket:listen, backlog={backlog}"); + // debug!("tcp socket:listen, socket'len={}",self.handle.len()); + // debug!("tcp socket:listen, backlog={backlog}"); // 监听所有的socket for i in 0..backlog { @@ -800,10 +800,10 @@ impl Socket for TcpSocket { let socket = sockets.get_mut::(handle.smoltcp_handle().unwrap()); if !socket.is_listening() { - // kdebug!("Tcp Socket is already listening on {local_endpoint}"); + // debug!("Tcp Socket is already listening on {local_endpoint}"); self.do_listen(socket, local_endpoint)?; } - // kdebug!("Tcp Socket before listen, open={}", socket.is_open()); + // debug!("Tcp Socket before listen, open={}", socket.is_open()); } return Ok(()); } @@ -816,7 +816,7 @@ impl Socket for TcpSocket { // 检测端口是否已被占用 PORT_MANAGER.bind_port(self.metadata.socket_type, ip.port)?; - // kdebug!("tcp socket:bind, socket'len={}",self.handle.len()); + // debug!("tcp socket:bind, socket'len={}",self.handle.len()); self.local_endpoint = Some(ip); self.is_listening = false; @@ -841,9 +841,9 @@ impl Socket for TcpSocket { } let endpoint = self.local_endpoint.ok_or(SystemError::EINVAL)?; loop { - // kdebug!("tcp accept: poll_ifaces()"); + // debug!("tcp accept: poll_ifaces()"); poll_ifaces(); - // kdebug!("tcp socket:accept, socket'len={}", self.handle_list.len()); + // debug!("tcp socket:accept, socket'len={}", self.handle_list.len()); let mut sockset = SOCKET_SET.lock_irqsave(); // Get the corresponding activated handler @@ -856,7 +856,7 @@ impl Socket for TcpSocket { let con_smol_sock = sockset .get::(self.handles[handle_index].smoltcp_handle().unwrap()); - // kdebug!("[Socket] [TCP] Accept: {:?}", handle); + // debug!("[Socket] [TCP] Accept: {:?}", handle); // handle is connected socket's handle let remote_ep = con_smol_sock .remote_endpoint() @@ -902,13 +902,13 @@ impl Socket for TcpSocket { drop(sockset); - // kdebug!("[TCP] [Accept] sleeping socket with handle: {:?}", self.handles.get(0).unwrap().smoltcp_handle().unwrap()); + // debug!("[TCP] [Accept] sleeping socket with handle: {:?}", self.handles.get(0).unwrap().smoltcp_handle().unwrap()); SocketHandleItem::sleep( self.socket_handle(), // NOTICE Self::CAN_ACCPET, HANDLE_MAP.read_irqsave(), ); - // kdebug!("tcp socket:after sleep, handle_guard'len={}",HANDLE_MAP.write_irqsave().len()); + // debug!("tcp socket:after sleep, handle_guard'len={}",HANDLE_MAP.write_irqsave().len()); } } @@ -917,7 +917,7 @@ impl Socket for TcpSocket { if result.is_none() { let sockets = SOCKET_SET.lock_irqsave(); - // kdebug!("tcp socket:endpoint, socket'len={}",self.handle.len()); + // debug!("tcp socket:endpoint, socket'len={}",self.handle.len()); let socket = sockets.get::(self.handles.get(0).unwrap().smoltcp_handle().unwrap()); @@ -930,7 +930,7 @@ impl Socket for TcpSocket { fn peer_endpoint(&self) -> Option { let sockets = SOCKET_SET.lock_irqsave(); - // kdebug!("tcp socket:peer_endpoint, socket'len={}",self.handle.len()); + // debug!("tcp socket:peer_endpoint, socket'len={}",self.handle.len()); let socket = sockets.get::(self.handles.get(0).unwrap().smoltcp_handle().unwrap()); @@ -946,7 +946,7 @@ impl Socket for TcpSocket { } fn socket_handle(&self) -> GlobalSocketHandle { - // kdebug!("tcp socket:socket_handle, socket'len={}",self.handle.len()); + // debug!("tcp socket:socket_handle, socket'len={}",self.handle.len()); *self.handles.get(0).unwrap() } diff --git a/kernel/src/net/socket/mod.rs b/kernel/src/net/socket/mod.rs index c9864273..7591c7f6 100644 --- a/kernel/src/net/socket/mod.rs +++ b/kernel/src/net/socket/mod.rs @@ -8,6 +8,7 @@ use alloc::{ vec::Vec, }; use hashbrown::HashMap; +use log::warn; use smoltcp::{ iface::SocketSet, socket::{self, raw, tcp, udp}, @@ -227,7 +228,7 @@ pub trait Socket: Sync + Send + Debug + Any { _optname: usize, _optval: &[u8], ) -> Result<(), SystemError> { - kwarn!("setsockopt is not implemented"); + warn!("setsockopt is not implemented"); Ok(()) } @@ -850,7 +851,7 @@ impl SocketPollMethod { } pub fn raw_poll(socket: &raw::Socket, shutdown: ShutdownType) -> EPollEventType { - //kdebug!("enter raw_poll!"); + //debug!("enter raw_poll!"); let mut event = EPollEventType::empty(); if shutdown.contains(ShutdownType::RCV_SHUTDOWN) { @@ -863,21 +864,21 @@ impl SocketPollMethod { } if socket.can_recv() { - //kdebug!("poll can recv!"); + //debug!("poll can recv!"); event.insert(EPollEventType::EPOLLIN | EPollEventType::EPOLLRDNORM); } else { - //kdebug!("poll can not recv!"); + //debug!("poll can not recv!"); } if socket.can_send() { - //kdebug!("poll can send!"); + //debug!("poll can send!"); event.insert( EPollEventType::EPOLLOUT | EPollEventType::EPOLLWRNORM | EPollEventType::EPOLLWRBAND, ); } else { - //kdebug!("poll can not send!"); + //debug!("poll can not send!"); // TODO: 缓冲区空间不够,需要使用信号处理 todo!() } diff --git a/kernel/src/net/syscall.rs b/kernel/src/net/syscall.rs index cc9bf569..6f3fd88a 100644 --- a/kernel/src/net/syscall.rs +++ b/kernel/src/net/syscall.rs @@ -404,13 +404,13 @@ impl Syscall { let socket: Arc = ProcessManager::current_pcb() .get_socket(fd as i32) .ok_or(SystemError::EBADF)?; - // kdebug!("accept: socket={:?}", socket); + // debug!("accept: socket={:?}", socket); let mut socket = unsafe { socket.inner_no_preempt() }; // 从socket中接收连接 let (new_socket, remote_endpoint) = socket.accept()?; drop(socket); - // kdebug!("accept: new_socket={:?}", new_socket); + // debug!("accept: new_socket={:?}", new_socket); // Insert the new socket into the file descriptor vector let new_socket: Arc = SocketInode::new(new_socket); @@ -426,9 +426,9 @@ impl Syscall { .fd_table() .write() .alloc_fd(File::new(new_socket, file_mode)?, None)?; - // kdebug!("accept: new_fd={}", new_fd); + // debug!("accept: new_fd={}", new_fd); if !addr.is_null() { - // kdebug!("accept: write remote_endpoint to user"); + // debug!("accept: write remote_endpoint to user"); // 将对端地址写入用户空间 let sockaddr_in = SockAddr::from(remote_endpoint); unsafe { diff --git a/kernel/src/process/exec.rs b/kernel/src/process/exec.rs index 91b7ac27..7be01374 100644 --- a/kernel/src/process/exec.rs +++ b/kernel/src/process/exec.rs @@ -165,7 +165,7 @@ pub fn load_binary_file(param: &mut ExecParam) -> Result Result Result { schedule(SchedMode::SM_NONE); } else { // todo: 对于pgid的处理 - kwarn!("kernel_wait4: currently not support {:?}", kwo.pid_type); + warn!("kernel_wait4: currently not support {:?}", kwo.pid_type); return Err(SystemError::EINVAL); } } @@ -225,7 +226,7 @@ fn do_waitpid( } ProcessState::Exited(status) => { let pid = child_pcb.pid(); - // kdebug!("wait4: child exited, pid: {:?}, status: {status}\n", pid); + // debug!("wait4: child exited, pid: {:?}, status: {status}\n", pid); if likely(!kwo.options.contains(WaitOption::WEXITED)) { return None; @@ -244,7 +245,7 @@ fn do_waitpid( kwo.ret_status = status as i32; drop(child_pcb); - // kdebug!("wait4: to release {pid:?}"); + // debug!("wait4: to release {pid:?}"); unsafe { ProcessManager::release(pid) }; return Some(Ok(pid.into())); } diff --git a/kernel/src/process/fork.rs b/kernel/src/process/fork.rs index ee0c3e61..6380f5e1 100644 --- a/kernel/src/process/fork.rs +++ b/kernel/src/process/fork.rs @@ -1,6 +1,7 @@ use core::{intrinsics::unlikely, sync::atomic::Ordering}; use alloc::{string::ToString, sync::Arc}; +use log::error; use system_error::SystemError; use crate::{ @@ -168,7 +169,7 @@ impl ProcessManager { args.flags = clone_flags; args.exit_signal = Signal::SIGCHLD; Self::copy_process(¤t_pcb, &pcb, args, current_trapframe).map_err(|e| { - kerror!( + error!( "fork: Failed to copy process, current pid: [{:?}], new pid: [{:?}]. Error: {:?}", current_pcb.pid(), pcb.pid(), diff --git a/kernel/src/process/kthread.rs b/kernel/src/process/kthread.rs index aa6c9171..70889678 100644 --- a/kernel/src/process/kthread.rs +++ b/kernel/src/process/kthread.rs @@ -10,13 +10,13 @@ use alloc::{ sync::{Arc, Weak}, }; use atomic_enum::atomic_enum; +use log::info; use system_error::SystemError; use crate::{ arch::CurrentIrqArch, exception::{irqdesc::IrqAction, InterruptArch}, init::initial_kthread::initial_kernel_thread, - kinfo, libs::{once::Once, spinlock::SpinLock}, process::{ProcessManager, ProcessState}, sched::{schedule, SchedMode}, @@ -258,7 +258,7 @@ pub struct KernelThreadMechanism; impl KernelThreadMechanism { pub fn init_stage1() { assert!(ProcessManager::current_pcb().pid() == Pid::new(0)); - kinfo!("Initializing kernel thread mechanism stage1..."); + info!("Initializing kernel thread mechanism stage1..."); // 初始化第一个内核线程 @@ -290,7 +290,7 @@ impl KernelThreadMechanism { .remove(ProcessFlags::KTHREAD); drop(irq_guard); - kinfo!("Initializing kernel thread mechanism stage1 complete"); + info!("Initializing kernel thread mechanism stage1 complete"); } pub fn init_stage2() { @@ -299,7 +299,7 @@ impl KernelThreadMechanism { .contains(ProcessFlags::KTHREAD)); static INIT: Once = Once::new(); INIT.call_once(|| { - kinfo!("Initializing kernel thread mechanism stage2..."); + info!("Initializing kernel thread mechanism stage2..."); // 初始化kthreadd let closure = KernelThreadClosure::EmptyClosure((Box::new(Self::kthread_daemon), ())); let info = KernelThreadCreateInfo::new(closure, "kthreadd".to_string()); @@ -315,7 +315,7 @@ impl KernelThreadMechanism { unsafe { KTHREAD_DAEMON_PCB.replace(pcb); } - kinfo!("Initialize kernel thread mechanism stage2 complete"); + info!("Initialize kernel thread mechanism stage2 complete"); }); } diff --git a/kernel/src/process/mod.rs b/kernel/src/process/mod.rs index 0db62b22..4e0b9397 100644 --- a/kernel/src/process/mod.rs +++ b/kernel/src/process/mod.rs @@ -12,6 +12,7 @@ use alloc::{ vec::Vec, }; use hashbrown::HashMap; +use log::{debug, error, info, warn}; use system_error::SystemError; use crate::{ @@ -28,7 +29,6 @@ use crate::{ vfs::{file::FileDescriptorVec, FileType}, }, ipc::signal_types::{SigInfo, SigPending, SignalStruct}, - kdebug, kinfo, libs::{ align::AlignedBox, casting::DowncastArc, @@ -116,24 +116,24 @@ impl ProcessManager { unsafe { compiler_fence(Ordering::SeqCst); - kdebug!("To create address space for INIT process."); + debug!("To create address space for INIT process."); // test_buddy(); set_IDLE_PROCESS_ADDRESS_SPACE( AddressSpace::new(true).expect("Failed to create address space for INIT process."), ); - kdebug!("INIT process address space created."); + debug!("INIT process address space created."); compiler_fence(Ordering::SeqCst); }; ALL_PROCESS.lock_irqsave().replace(HashMap::new()); Self::init_switch_result(); Self::arch_init(); - kdebug!("process arch init done."); + debug!("process arch init done."); Self::init_idle(); - kdebug!("process idle init done."); + debug!("process idle init done."); unsafe { __PROCESS_MANAGEMENT_INIT_DONE = true }; - kinfo!("Process Manager initialized."); + info!("Process Manager initialized."); } fn init_switch_result() { @@ -155,7 +155,7 @@ impl ProcessManager { /// 获取当前进程的pcb pub fn current_pcb() -> Arc { if unlikely(unsafe { !__PROCESS_MANAGEMENT_INIT_DONE }) { - kerror!("unsafe__PROCESS_MANAGEMENT_INIT_DONE == false"); + error!("unsafe__PROCESS_MANAGEMENT_INIT_DONE == false"); loop { spin_loop(); } @@ -362,7 +362,7 @@ impl ProcessManager { let parent_pcb = r.unwrap(); let r = Syscall::kill(parent_pcb.pid(), Signal::SIGCHLD as i32); if r.is_err() { - kwarn!( + warn!( "failed to send kill signal to {:?}'s parent pcb {:?}", current.pid(), parent_pcb.pid() @@ -422,7 +422,7 @@ impl ProcessManager { ProcessManager::exit_notify(); // unsafe { CurrentIrqArch::interrupt_enable() }; __schedule(SchedMode::SM_NONE); - kerror!("pid {pid:?} exited but sched again!"); + error!("pid {pid:?} exited but sched again!"); #[allow(clippy::empty_loop)] loop { spin_loop(); @@ -442,7 +442,7 @@ impl ProcessManager { // } else { // // 如果不为1就panic // let msg = format!("pcb '{:?}' is still referenced, strong count={}",pcb.pid(), Arc::strong_count(&pcb)); - // kerror!("{}", msg); + // error!("{}", msg); // panic!() // } @@ -452,7 +452,7 @@ impl ProcessManager { /// 上下文切换完成后的钩子函数 unsafe fn switch_finish_hook() { - // kdebug!("switch_finish_hook"); + // debug!("switch_finish_hook"); let prev_pcb = PROCESS_SWITCH_RESULT .as_mut() .unwrap() @@ -1368,7 +1368,7 @@ impl KernelStack { // 如果内核栈的最低地址处已经有了一个pcb,那么,这里就不再设置,直接返回错误 if unlikely(unsafe { !(*stack_bottom_ptr).is_null() }) { - kerror!("kernel stack bottom is not null: {:p}", *stack_bottom_ptr); + error!("kernel stack bottom is not null: {:p}", *stack_bottom_ptr); return Err(SystemError::EPERM); } // 将pcb的地址放到内核栈的最低地址处 diff --git a/kernel/src/process/syscall.rs b/kernel/src/process/syscall.rs index 61dfea10..16f0e2e4 100644 --- a/kernel/src/process/syscall.rs +++ b/kernel/src/process/syscall.rs @@ -98,13 +98,13 @@ impl Syscall { envp: *const *const u8, frame: &mut TrapFrame, ) -> Result<(), SystemError> { - // kdebug!( + // debug!( // "execve path: {:?}, argv: {:?}, envp: {:?}\n", // path, // argv, // envp // ); - // kdebug!( + // debug!( // "before execve: strong count: {}", // Arc::strong_count(&ProcessManager::current_pcb()) // ); @@ -133,7 +133,7 @@ impl Syscall { // 关闭设置了O_CLOEXEC的文件描述符 let fd_table = ProcessManager::current_pcb().fd_table(); fd_table.write().close_on_exec(); - // kdebug!( + // debug!( // "after execve: strong count: {}", // Arc::strong_count(&ProcessManager::current_pcb()) // ); diff --git a/kernel/src/process/timer.rs b/kernel/src/process/timer.rs index 7099d074..d206fbd2 100644 --- a/kernel/src/process/timer.rs +++ b/kernel/src/process/timer.rs @@ -84,7 +84,7 @@ impl AlarmTimer { >::from(Duration::from_secs(self.expired_second)) .timer_jiffies(); let remain_second = Duration::from(Jiffies::new(end_jiffies - now_jiffies)); - // kdebug!( + // debug!( // "end: {} - now: {} = remain: {}", // end_jiffies, // now_jiffies, diff --git a/kernel/src/sched/fair.rs b/kernel/src/sched/fair.rs index 0428b1b9..54dd5cdb 100644 --- a/kernel/src/sched/fair.rs +++ b/kernel/src/sched/fair.rs @@ -567,7 +567,7 @@ impl CfsRunQueue { fence(Ordering::SeqCst); if unlikely(now <= curr.exec_start) { - // kwarn!( + // warn!( // "update_current return now <= curr.exec_start now {now} execstart {}", // curr.exec_start // ); @@ -596,11 +596,11 @@ impl CfsRunQueue { fn account_cfs_rq_runtime(&mut self, delta_exec: u64) { if likely(self.runtime_remaining > delta_exec) { self.runtime_remaining -= delta_exec; - // kerror!("runtime_remaining {}", self.runtime_remaining); + // error!("runtime_remaining {}", self.runtime_remaining); return; } - // kwarn!( + // warn!( // "runtime_remaining {} delta exec {delta_exec} nr_running {}", // self.runtime_remaining, // self.nr_running @@ -609,14 +609,14 @@ impl CfsRunQueue { self.runtime_remaining = 5000 * NSEC_PER_MSEC as u64; if likely(self.current().is_some()) && self.nr_running > 1 { - // kerror!("account_cfs_rq_runtime"); + // error!("account_cfs_rq_runtime"); self.rq().resched_current(); } } /// 计算deadline,如果vruntime到期会重调度 pub fn update_deadline(&mut self, se: &Arc) { - // kerror!("vruntime {} deadline {}", se.vruntime, se.deadline); + // error!("vruntime {} deadline {}", se.vruntime, se.deadline); if se.vruntime < se.deadline { return; } @@ -1131,7 +1131,7 @@ impl CfsRunQueue { self.avg_vruntime_add(se); se.force_mut().min_deadline = se.deadline; self.entities.insert(se.vruntime, se.clone()); - // kwarn!( + // warn!( // "enqueue pcb {:?} cfsrq {:?}", // se.pcb().pid(), // self.entities @@ -1153,7 +1153,7 @@ impl CfsRunQueue { } fn inner_dequeue_entity(&mut self, se: &Arc) { - // kwarn!( + // warn!( // "before dequeue pcb {:?} cfsrq {:?}", // se.pcb().pid(), // self.entities @@ -1196,7 +1196,7 @@ impl CfsRunQueue { // ) // .as_bytes(), // ); - // kwarn!( + // warn!( // "after dequeue pcb {:?}(real: {:?}) cfsrq {:?}", // se.pcb().pid(), // remove.pcb().pid(), diff --git a/kernel/src/sched/mod.rs b/kernel/src/sched/mod.rs index c50782e8..dbe262ec 100644 --- a/kernel/src/sched/mod.rs +++ b/kernel/src/sched/mod.rs @@ -510,7 +510,7 @@ impl CpuRunQueue { let delta = clock - self.clock; self.clock += delta; - // kerror!("clock {}", self.clock); + // error!("clock {}", self.clock); self.update_rq_clock_task(delta); } @@ -518,7 +518,7 @@ impl CpuRunQueue { pub fn update_rq_clock_task(&mut self, mut delta: u64) { let mut irq_delta = irq_time_read(self.cpu) - self.prev_irq_time; // if self.cpu == 0 { - // kerror!( + // error!( // "cpu 0 delta {delta} irq_delta {} irq_time_read(self.cpu) {} self.prev_irq_time {}", // irq_delta, // irq_time_read(self.cpu), @@ -542,7 +542,7 @@ impl CpuRunQueue { self.clock_task += delta; compiler_fence(Ordering::SeqCst); // if self.cpu == 0 { - // kerror!("cpu {} clock_task {}", self.cpu, self.clock_task); + // error!("cpu {} clock_task {}", self.cpu, self.clock_task); // } // todo: pelt? } @@ -656,7 +656,7 @@ impl CpuRunQueue { if let Some(pcb) = p.as_ref() { return pcb.clone(); } else { - // kerror!( + // error!( // "pick idle cfs rq {:?}", // self.cfs_rq() // .entities @@ -849,7 +849,7 @@ pub fn __schedule(sched_mod: SchedMode) { // .map(|x| { x.1.vruntime }) // .collect::>(), // ); - // kwarn!( + // warn!( // "before cfs rq {:?} prev {:?}", // rq.cfs // .entities @@ -859,12 +859,12 @@ pub fn __schedule(sched_mod: SchedMode) { // prev.pid() // ); - // kerror!("prev pid {:?} {:?}", prev.pid(), prev.sched_info().policy()); + // error!("prev pid {:?} {:?}", prev.pid(), prev.sched_info().policy()); if !sched_mod.contains(SchedMode::SM_MASK_PREEMPT) && prev.sched_info().policy() != SchedPolicy::IDLE && prev.sched_info().inner_lock_read_irqsave().is_mark_sleep() { - // kwarn!("deactivate_task prev {:?}", prev.pid()); + // warn!("deactivate_task prev {:?}", prev.pid()); // TODO: 这里需要处理信号 // https://code.dragonos.org.cn/xref/linux-6.6.21/kernel/sched/core.c?r=&mo=172979&fi=6578#6630 rq.deactivate_task( @@ -889,13 +889,13 @@ pub fn __schedule(sched_mod: SchedMode) { // .collect::>(), // ); - // kerror!("next {:?}", next.pid()); + // error!("next {:?}", next.pid()); prev.flags().remove(ProcessFlags::NEED_SCHEDULE); fence(Ordering::SeqCst); if likely(!Arc::ptr_eq(&prev, &next)) { rq.set_current(Arc::downgrade(&next)); - // kwarn!( + // warn!( // "switch_process prev {:?} next {:?} sched_mode {sched_mod:?}", // prev.pid(), // next.pid() diff --git a/kernel/src/smp/cpu/mod.rs b/kernel/src/smp/cpu/mod.rs index 62c0b4d1..186184ef 100644 --- a/kernel/src/smp/cpu/mod.rs +++ b/kernel/src/smp/cpu/mod.rs @@ -1,6 +1,7 @@ use core::sync::atomic::AtomicU32; use alloc::{sync::Arc, vec::Vec}; +use log::{debug, error, info}; use system_error::SystemError; use crate::{ @@ -202,14 +203,14 @@ impl SmpCpuManager { continue; } - kdebug!("Bring up CPU {}", cpu_id.data()); + debug!("Bring up CPU {}", cpu_id.data()); if let Err(e) = self.cpu_up(cpu_id, CpuHpState::Online) { - kerror!("Failed to bring up CPU {}: {:?}", cpu_id.data(), e); + error!("Failed to bring up CPU {}: {:?}", cpu_id.data(), e); } } - kinfo!("All non-boot CPUs have been brought up"); + info!("All non-boot CPUs have been brought up"); } fn cpu_up(&self, cpu_id: ProcessorId, target_state: CpuHpState) -> Result<(), SystemError> { @@ -218,7 +219,7 @@ impl SmpCpuManager { } let cpu_state = self.cpuhp_state(cpu_id).state; - kdebug!( + debug!( "cpu_up: cpu_id: {}, cpu_state: {:?}, target_state: {:?}", cpu_id.data(), cpu_state, diff --git a/kernel/src/smp/init.rs b/kernel/src/smp/init.rs index 68911612..27d62209 100644 --- a/kernel/src/smp/init.rs +++ b/kernel/src/smp/init.rs @@ -1,3 +1,5 @@ +use log::info; + use crate::{ arch::{syscall::arch_syscall_init, CurrentIrqArch, CurrentSchedArch}, exception::InterruptArch, @@ -22,6 +24,6 @@ pub fn smp_ap_start_stage2() -> ! { #[inline(never)] fn do_ap_start_stage2() { - kinfo!("Successfully started AP {}", smp_get_processor_id().data()); + info!("Successfully started AP {}", smp_get_processor_id().data()); arch_syscall_init().expect("AP core failed to initialize syscall"); } diff --git a/kernel/src/syscall/misc.rs b/kernel/src/syscall/misc.rs index 7398e85a..f7802929 100644 --- a/kernel/src/syscall/misc.rs +++ b/kernel/src/syscall/misc.rs @@ -5,6 +5,7 @@ use crate::{ }; use alloc::vec::Vec; use core::cmp; +use log::warn; use system_error::SystemError; use super::{user_access::UserBufferWriter, Syscall}; @@ -59,7 +60,7 @@ impl Syscall { } pub fn umask(_mask: u32) -> Result { - kwarn!("SYS_UMASK has not yet been implemented\n"); + warn!("SYS_UMASK has not yet been implemented\n"); return Ok(0o777); } diff --git a/kernel/src/syscall/mod.rs b/kernel/src/syscall/mod.rs index e6d03a67..497e5084 100644 --- a/kernel/src/syscall/mod.rs +++ b/kernel/src/syscall/mod.rs @@ -20,6 +20,7 @@ use crate::{ syscall::user_access::check_and_clone_cstr, }; +use log::{info, warn}; use num_traits::FromPrimitive; use system_error::SystemError; @@ -31,7 +32,6 @@ use crate::{ syscall::{ModeType, PosixKstat}, MAX_PATHLEN, }, - kinfo, libs::align::page_align_up, mm::{verify_area, MemoryManagementArch, VirtAddr}, net::syscall::SockAddr, @@ -69,9 +69,9 @@ impl Syscall { if prev { panic!("Cannot initialize syscall more than once!"); } - kinfo!("Initializing syscall..."); + info!("Initializing syscall..."); let r = crate::arch::syscall::arch_syscall_init(); - kinfo!("Syscall init successfully!"); + info!("Syscall init successfully!"); return r; } @@ -369,7 +369,7 @@ impl Syscall { SYS_KILL => { let pid = Pid::new(args[0]); let sig = args[1] as c_int; - // kdebug!("KILL SYSCALL RECEIVED"); + // debug!("KILL SYSCALL RECEIVED"); Self::kill(pid, sig) } @@ -383,7 +383,7 @@ impl Syscall { SYS_GETPID => Self::getpid().map(|pid| pid.into()), SYS_SCHED => { - kwarn!("syscall sched"); + warn!("syscall sched"); schedule(SchedMode::SM_NONE); Ok(0) } @@ -650,7 +650,7 @@ impl Syscall { Err(SystemError::EINVAL) }; - // kdebug!("FCNTL: fd: {}, cmd: {:?}, arg: {}, res: {:?}", fd, cmd, arg, res); + // debug!("FCNTL: fd: {}, cmd: {:?}, arg: {}, res: {:?}", fd, cmd, arg, res); res } @@ -658,7 +658,7 @@ impl Syscall { let fd = args[0] as i32; let len = args[1]; let res = Self::ftruncate(fd, len); - // kdebug!("FTRUNCATE: fd: {}, len: {}, res: {:?}", fd, len, res); + // debug!("FTRUNCATE: fd: {}, len: {}, res: {:?}", fd, len, res); res } @@ -835,32 +835,32 @@ impl Syscall { #[cfg(target_arch = "x86_64")] SYS_POLL => { - kwarn!("SYS_POLL has not yet been implemented"); + warn!("SYS_POLL has not yet been implemented"); Ok(0) } SYS_SETPGID => { - kwarn!("SYS_SETPGID has not yet been implemented"); + warn!("SYS_SETPGID has not yet been implemented"); Ok(0) } SYS_RT_SIGPROCMASK => { - kwarn!("SYS_RT_SIGPROCMASK has not yet been implemented"); + warn!("SYS_RT_SIGPROCMASK has not yet been implemented"); Ok(0) } SYS_TKILL => { - kwarn!("SYS_TKILL has not yet been implemented"); + warn!("SYS_TKILL has not yet been implemented"); Ok(0) } SYS_SIGALTSTACK => { - kwarn!("SYS_SIGALTSTACK has not yet been implemented"); + warn!("SYS_SIGALTSTACK has not yet been implemented"); Ok(0) } SYS_EXIT_GROUP => { - kwarn!("SYS_EXIT_GROUP has not yet been implemented"); + warn!("SYS_EXIT_GROUP has not yet been implemented"); Ok(0) } @@ -891,15 +891,15 @@ impl Syscall { SYS_GETGID => Self::getgid(), SYS_SETUID => { - kwarn!("SYS_SETUID has not yet been implemented"); + warn!("SYS_SETUID has not yet been implemented"); Ok(0) } SYS_SETGID => { - kwarn!("SYS_SETGID has not yet been implemented"); + warn!("SYS_SETGID has not yet been implemented"); Ok(0) } SYS_SETSID => { - kwarn!("SYS_SETSID has not yet been implemented"); + warn!("SYS_SETSID has not yet been implemented"); Ok(0) } SYS_GETEUID => Self::geteuid(), @@ -975,17 +975,17 @@ impl Syscall { } SYS_FCHOWN => { - kwarn!("SYS_FCHOWN has not yet been implemented"); + warn!("SYS_FCHOWN has not yet been implemented"); Ok(0) } SYS_FSYNC => { - kwarn!("SYS_FSYNC has not yet been implemented"); + warn!("SYS_FSYNC has not yet been implemented"); Ok(0) } SYS_RSEQ => { - kwarn!("SYS_RSEQ has not yet been implemented"); + warn!("SYS_RSEQ has not yet been implemented"); Ok(0) } diff --git a/kernel/src/syscall/user_access.rs b/kernel/src/syscall/user_access.rs index 66493156..c55f7567 100644 --- a/kernel/src/syscall/user_access.rs +++ b/kernel/src/syscall/user_access.rs @@ -116,7 +116,7 @@ pub fn check_and_clone_cstr_array(user: *const *const u8) -> Result, if user.is_null() { Ok(Vec::new()) } else { - // kdebug!("check_and_clone_cstr_array: {:p}\n", user); + // debug!("check_and_clone_cstr_array: {:p}\n", user); let mut buffer = Vec::new(); for i in 0.. { let addr = unsafe { user.add(i) }; @@ -129,7 +129,7 @@ pub fn check_and_clone_cstr_array(user: *const *const u8) -> Result, let dst = core::mem::transmute::<[u8; size_of::()], [usize; 1]>(dst); str_ptr = dst[0] as *const u8; - // kdebug!("str_ptr: {:p}, addr:{addr:?}\n", str_ptr); + // debug!("str_ptr: {:p}, addr:{addr:?}\n", str_ptr); } if str_ptr.is_null() { diff --git a/kernel/src/time/clocksource.rs b/kernel/src/time/clocksource.rs index 772a2041..2781bd75 100644 --- a/kernel/src/time/clocksource.rs +++ b/kernel/src/time/clocksource.rs @@ -11,6 +11,7 @@ use alloc::{ vec::Vec, }; use lazy_static::__Deref; +use log::{debug, info}; use system_error::SystemError; use unified_init::macros::unified_init; @@ -18,7 +19,6 @@ use crate::{ arch::CurrentIrqArch, exception::InterruptArch, init::initcall::INITCALL_LATE, - kdebug, kinfo, libs::spinlock::SpinLock, process::{ kthread::{KernelThreadClosure, KernelThreadMechanism}, @@ -378,7 +378,7 @@ impl dyn Clocksource { .expect("register: failed to enqueue watchdog list"); // 选择一个最好的时钟源 clocksource_select(); - kdebug!("clocksource_register successfully"); + debug!("clocksource_register successfully"); return Ok(()); } @@ -398,7 +398,7 @@ impl dyn Clocksource { let cs = self.clocksource(); list_guard.push_back(cs); list_guard.append(&mut temp_list); - // kdebug!( + // debug!( // "CLOCKSOURCE_LIST len = {:?},clocksource_enqueue sccessfully", // list_guard.len() // ); @@ -473,10 +473,9 @@ impl dyn Clocksource { pub fn set_unstable(&self, delta: i64) -> Result { let mut cs_data = self.clocksource_data(); // 打印出unstable的时钟源信息 - kdebug!( + debug!( "clocksource :{:?} is unstable, its delta is {:?}", - cs_data.name, - delta + cs_data.name, delta ); cs_data.flags.remove( ClocksourceFlags::CLOCK_SOURCE_VALID_FOR_HRES | ClocksourceFlags::CLOCK_SOURCE_WATCHDOG, @@ -740,7 +739,7 @@ pub fn clocksource_resume() { match ele.resume() { Ok(_) => continue, Err(_) => { - kdebug!("clocksource {:?} resume failed", data.name); + debug!("clocksource {:?} resume failed", data.name); } } } @@ -756,7 +755,7 @@ pub fn clocksource_suspend() { match ele.suspend() { Ok(_) => continue, Err(_) => { - kdebug!("clocksource {:?} suspend failed", data.name); + debug!("clocksource {:?} suspend failed", data.name); } } } @@ -770,11 +769,11 @@ pub fn clocksource_suspend() { /// * `Err(SystemError)` - 错误码 pub fn clocksource_watchdog() -> Result<(), SystemError> { let mut cs_watchdog = CLOCKSOUCE_WATCHDOG.lock_irqsave(); - // kdebug!("clocksource_watchdog start"); + // debug!("clocksource_watchdog start"); // watchdog没有在运行的话直接退出 if !cs_watchdog.is_running || cs_watchdog.watchdog.is_none() { - // kdebug!("is_running = {:?},watchdog = {:?}", cs_watchdog.is_running, cs_watchdog.watchdog); + // debug!("is_running = {:?},watchdog = {:?}", cs_watchdog.is_running, cs_watchdog.watchdog); return Ok(()); } let cur_watchdog = cs_watchdog.watchdog.as_ref().unwrap().clone(); @@ -797,7 +796,7 @@ pub fn clocksource_watchdog() -> Result<(), SystemError> { .flags .contains(ClocksourceFlags::CLOCK_SOURCE_UNSTABLE) { - // kdebug!("clocksource_watchdog unstable"); + // debug!("clocksource_watchdog unstable"); // 启动watchdog_kthread run_watchdog_kthread(); continue; @@ -810,7 +809,7 @@ pub fn clocksource_watchdog() -> Result<(), SystemError> { .flags .contains(ClocksourceFlags::CLOCK_SOURCE_WATCHDOG) { - // kdebug!("clocksource_watchdog start watch"); + // debug!("clocksource_watchdog start watch"); cs_data .flags .insert(ClocksourceFlags::CLOCK_SOURCE_WATCHDOG); @@ -819,7 +818,7 @@ pub fn clocksource_watchdog() -> Result<(), SystemError> { cs.update_clocksource_data(cs_data.clone())?; continue; } - // kdebug!("cs_data.watchdog_last = {:?},cs_now_clock = {:?}", cs_data.watchdog_last, cs_now_clock); + // debug!("cs_data.watchdog_last = {:?},cs_now_clock = {:?}", cs_data.watchdog_last, cs_now_clock); // 计算时钟源的误差 let cs_dev_nsec = clocksource_cyc2ns( CycleNum(cs_now_clock.div(cs_data.watchdog_last).data() & cs_data.mask.bits), @@ -830,14 +829,14 @@ pub fn clocksource_watchdog() -> Result<(), SystemError> { cs_data.watchdog_last = cs_now_clock; cs.update_clocksource_data(cs_data.clone())?; if cs_dev_nsec.abs_diff(wd_dev_nsec) > WATCHDOG_THRESHOLD.into() { - // kdebug!("set_unstable"); + // debug!("set_unstable"); // 误差过大,标记为unstable - kinfo!("cs_dev_nsec = {}", cs_dev_nsec); - kinfo!("wd_dev_nsec = {}", wd_dev_nsec); + info!("cs_dev_nsec = {}", cs_dev_nsec); + info!("wd_dev_nsec = {}", wd_dev_nsec); cs.set_unstable((cs_dev_nsec - wd_dev_nsec).try_into().unwrap())?; continue; } - // kdebug!("clocksource_watchdog aaa"); + // debug!("clocksource_watchdog aaa"); // 判断是否要切换为高精度模式 if !cs_data @@ -900,7 +899,7 @@ fn __clocksource_watchdog_kthread() { clock.clocksource_change_rating(0); let mut data = clock.clocksource_data(); data.watchdog_last = clock.read(); - kdebug!("kthread: watchdog_last = {:?}", data.watchdog_last); + debug!("kthread: watchdog_last = {:?}", data.watchdog_last); data.flags.remove(ClocksourceFlags::CLOCK_SOURCE_UNSTABLE); clock .update_clocksource_data(data) @@ -917,7 +916,7 @@ fn __clocksource_watchdog_kthread() { pub fn clocksource_watchdog_kthread() -> i32 { // return 0; loop { - // kdebug!("clocksource_watchdog_kthread start"); + // debug!("clocksource_watchdog_kthread start"); __clocksource_watchdog_kthread(); if KernelThreadMechanism::should_stop(&ProcessManager::current_pcb()) { break; @@ -969,7 +968,7 @@ pub fn clocksource_select() { let cur_clocksource = CUR_CLOCKSOURCE.lock().as_ref().unwrap().clone(); let best_name = &best.clocksource_data().name; if cur_clocksource.clocksource_data().name.ne(best_name) { - kinfo!("Switching to the clocksource {:?}\n", best_name); + info!("Switching to the clocksource {:?}\n", best_name); drop(cur_clocksource); CUR_CLOCKSOURCE.lock().replace(best.clone()); // TODO 通知timerkeeping 切换了时间源 @@ -978,7 +977,7 @@ pub fn clocksource_select() { // 当前时钟源为空 CUR_CLOCKSOURCE.lock().replace(best.clone()); } - kdebug!("clocksource_select finish, CUR_CLOCKSOURCE = {best:?}"); + debug!("clocksource_select finish, CUR_CLOCKSOURCE = {best:?}"); } /// # clocksource模块加载完成 @@ -988,7 +987,7 @@ pub fn clocksource_boot_finish() { FINISHED_BOOTING.store(true, Ordering::Relaxed); // 清除不稳定的时钟源 __clocksource_watchdog_kthread(); - kdebug!("clocksource_boot_finish"); + debug!("clocksource_boot_finish"); } fn run_watchdog_kthread() { diff --git a/kernel/src/time/jiffies.rs b/kernel/src/time/jiffies.rs index e01451fa..cde4ebd7 100644 --- a/kernel/src/time/jiffies.rs +++ b/kernel/src/time/jiffies.rs @@ -2,9 +2,10 @@ use alloc::{ string::ToString, sync::{Arc, Weak}, }; +use log::{error, info}; use system_error::SystemError; -use crate::{arch::time::CLOCK_TICK_RATE, kerror, kinfo, libs::spinlock::SpinLock}; +use crate::{arch::time::CLOCK_TICK_RATE, libs::spinlock::SpinLock}; use super::{ clocksource::{Clocksource, ClocksourceData, ClocksourceFlags, ClocksourceMask, CycleNum, HZ}, @@ -96,10 +97,10 @@ pub fn jiffies_init() { let jiffies = clocksource_default_clock() as Arc; match jiffies.register(1, 0) { Ok(_) => { - kinfo!("jiffies_init sccessfully"); + info!("jiffies_init sccessfully"); } Err(_) => { - kerror!("jiffies_init failed, no default clock running"); + error!("jiffies_init failed, no default clock running"); } }; } diff --git a/kernel/src/time/syscall.rs b/kernel/src/time/syscall.rs index 77fd1334..76f9349e 100644 --- a/kernel/src/time/syscall.rs +++ b/kernel/src/time/syscall.rs @@ -3,6 +3,7 @@ use core::{ time::Duration, }; +use log::warn; use num_traits::FromPrimitive; use system_error::SystemError; @@ -138,7 +139,7 @@ impl Syscall { pub fn clock_gettime(clock_id: c_int, tp: *mut PosixTimeSpec) -> Result { let clock_id = PosixClockID::try_from(clock_id)?; if clock_id != PosixClockID::Realtime { - kwarn!("clock_gettime: currently only support Realtime clock, but got {:?}. Defaultly return realtime!!!\n", clock_id); + warn!("clock_gettime: currently only support Realtime clock, but got {:?}. Defaultly return realtime!!!\n", clock_id); } if tp.is_null() { return Err(SystemError::EFAULT); diff --git a/kernel/src/time/timekeeping.rs b/kernel/src/time/timekeeping.rs index 13680575..dff0cb91 100644 --- a/kernel/src/time/timekeeping.rs +++ b/kernel/src/time/timekeeping.rs @@ -1,11 +1,11 @@ use alloc::sync::Arc; use core::sync::atomic::{compiler_fence, AtomicBool, AtomicI64, AtomicUsize, Ordering}; +use log::{debug, info}; use system_error::SystemError; use crate::{ arch::{CurrentIrqArch, CurrentTimeArch}, exception::InterruptArch, - kdebug, kinfo, libs::rwlock::{RwLock, RwLockReadGuard}, time::{ jiffies::{clocksource_default_clock, jiffies_init}, @@ -120,7 +120,7 @@ impl Timekeeper { let mut clock_data = clock.clocksource_data(); clock_data.watchdog_last = clock.read(); if clock.update_clocksource_data(clock_data).is_err() { - kdebug!("timekeeper_setup_internals:update_clocksource_data run failed"); + debug!("timekeeper_setup_internals:update_clocksource_data run failed"); } timekeeper.clock.replace(clock.clone()); @@ -193,7 +193,7 @@ pub fn timekeeper_init() { /// /// * 'TimeSpec' - 时间戳 pub fn getnstimeofday() -> PosixTimeSpec { - // kdebug!("enter getnstimeofday"); + // debug!("enter getnstimeofday"); let nsecs; let mut xtime: PosixTimeSpec; @@ -218,7 +218,7 @@ pub fn getnstimeofday() -> PosixTimeSpec { xtime.tv_nsec += nsecs as i64; xtime.tv_sec += xtime.tv_nsec / NSEC_PER_SEC as i64; xtime.tv_nsec %= NSEC_PER_SEC as i64; - // kdebug!("getnstimeofday: xtime = {:?}, nsecs = {:}", xtime, nsecs); + // debug!("getnstimeofday: xtime = {:?}, nsecs = {:}", xtime, nsecs); // TODO 将xtime和当前时间源的时间相加 @@ -248,7 +248,7 @@ pub fn do_settimeofday64(time: PosixTimeSpec) -> Result<(), SystemError> { /// # 初始化timekeeping模块 #[inline(never)] pub fn timekeeping_init() { - kinfo!("Initializing timekeeping module..."); + info!("Initializing timekeeping module..."); let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() }; timekeeper_init(); @@ -274,12 +274,12 @@ pub fn timekeeping_init() { drop(irq_guard); drop(timekeeper); jiffies_init(); - kinfo!("timekeeping_init successfully"); + info!("timekeeping_init successfully"); } /// # 使用当前时钟源增加wall time pub fn update_wall_time(delta_us: i64) { - // kdebug!("enter update_wall_time, stack_use = {:}",stack_use); + // debug!("enter update_wall_time, stack_use = {:}",stack_use); compiler_fence(Ordering::SeqCst); let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() }; // 如果在休眠那就不更新 diff --git a/kernel/src/time/timer.rs b/kernel/src/time/timer.rs index 1dce3bb2..270140ec 100644 --- a/kernel/src/time/timer.rs +++ b/kernel/src/time/timer.rs @@ -10,6 +10,7 @@ use alloc::{ sync::{Arc, Weak}, vec::Vec, }; +use log::{error, info, warn}; use system_error::SystemError; use crate::{ @@ -18,7 +19,6 @@ use crate::{ softirq::{softirq_vectors, SoftirqNumber, SoftirqVec}, InterruptArch, }, - kerror, kinfo, libs::spinlock::{SpinLock, SpinLockGuard}, process::{ProcessControlBlock, ProcessManager}, sched::{schedule, SchedMode}, @@ -160,7 +160,7 @@ impl Timer { let mut split_pos: usize = 0; for (pos, elt) in timer_list.iter().enumerate() { if Arc::ptr_eq(&self_arc, &elt.1) { - kwarn!("Timer already in list"); + warn!("Timer already in list"); } if elt.0 > expire_jiffies { split_pos = pos; @@ -180,7 +180,7 @@ impl Timer { drop(timer); let r = func.map(|mut f| f.run()).unwrap_or(Ok(())); if unlikely(r.is_err()) { - kerror!( + error!( "Failed to run timer function: {self:?} {:?}", r.as_ref().err().unwrap() ); @@ -246,7 +246,7 @@ impl SoftirqVec for DoTimerSoftirq { } // 最多只处理TIMER_RUN_CYCLE_THRESHOLD个计时器 for _ in 0..TIMER_RUN_CYCLE_THRESHOLD { - // kdebug!("DoTimerSoftirq run"); + // debug!("DoTimerSoftirq run"); let timer_list = TIMER_LIST.try_lock_irqsave(); if timer_list.is_err() { continue; @@ -258,7 +258,7 @@ impl SoftirqVec for DoTimerSoftirq { } let (front_jiffies, timer_list_front) = timer_list.first().unwrap().clone(); - // kdebug!("to lock timer_list_front"); + // debug!("to lock timer_list_front"); if front_jiffies >= TIMER_JIFFIES.load(Ordering::SeqCst) { break; @@ -280,7 +280,7 @@ pub fn timer_init() { softirq_vectors() .register_softirq(SoftirqNumber::TIMER, do_timer_softirq) .expect("Failed to register timer softirq"); - kinfo!("timer initialized successfully"); + info!("timer initialized successfully"); } /// 计算接下来n毫秒对应的定时器时间片 @@ -300,7 +300,7 @@ pub fn next_n_us_timer_jiffies(expire_us: u64) -> u64 { /// /// @return Err(SystemError) 错误码 pub fn schedule_timeout(mut timeout: i64) -> Result { - // kdebug!("schedule_timeout"); + // debug!("schedule_timeout"); if timeout == MAX_TIMEOUT { let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() }; ProcessManager::mark_sleep(true).ok(); @@ -308,7 +308,7 @@ pub fn schedule_timeout(mut timeout: i64) -> Result { schedule(SchedMode::SM_NONE); return Ok(MAX_TIMEOUT); } else if timeout < 0 { - kerror!("timeout can't less than 0"); + error!("timeout can't less than 0"); return Err(SystemError::EINVAL); } else { // 禁用中断,防止在这段期间发生调度,造成死锁 @@ -337,16 +337,16 @@ pub fn schedule_timeout(mut timeout: i64) -> Result { pub fn timer_get_first_expire() -> Result { // FIXME - // kdebug!("rs_timer_get_first_expire,timer_jif = {:?}", TIMER_JIFFIES); + // debug!("rs_timer_get_first_expire,timer_jif = {:?}", TIMER_JIFFIES); for _ in 0..10 { match TIMER_LIST.try_lock_irqsave() { Ok(timer_list) => { - // kdebug!("rs_timer_get_first_expire TIMER_LIST lock successfully"); + // debug!("rs_timer_get_first_expire TIMER_LIST lock successfully"); if timer_list.is_empty() { - // kdebug!("timer_list is empty"); + // debug!("timer_list is empty"); return Ok(0); } else { - // kdebug!("timer_list not empty"); + // debug!("timer_list not empty"); return Ok(timer_list.first().unwrap().0); } } diff --git a/kernel/src/virt/kvm/host_mem.rs b/kernel/src/virt/kvm/host_mem.rs index 75780f0a..f34a1e83 100644 --- a/kernel/src/virt/kvm/host_mem.rs +++ b/kernel/src/virt/kvm/host_mem.rs @@ -1,10 +1,8 @@ +use log::debug; use system_error::SystemError; use super::{vcpu::Vcpu, vm}; -use crate::{ - kdebug, - mm::{kernel_mapper::KernelMapper, page::PageFlags, VirtAddr}, -}; +use crate::mm::{kernel_mapper::KernelMapper, page::PageFlags, VirtAddr}; /* * Address types: @@ -87,7 +85,7 @@ pub fn kvm_vcpu_memslots(_vcpu: &mut dyn Vcpu) -> KvmMemorySlots { } fn __gfn_to_memslot(slots: KvmMemorySlots, gfn: u64) -> Option { - kdebug!("__gfn_to_memslot"); + debug!("__gfn_to_memslot"); // TODO: 使用二分查找的方式优化 for i in 0..slots.used_slots { let memslot = slots.memslots[i as usize]; @@ -107,7 +105,7 @@ fn __gfn_to_hva_many( nr_pages: Option<&mut u64>, write: bool, ) -> Result { - kdebug!("__gfn_to_hva_many"); + debug!("__gfn_to_hva_many"); if slot.is_none() { return Err(SystemError::KVM_HVA_ERR_BAD); } @@ -141,10 +139,10 @@ fn __gfn_to_hva_many( // host端虚拟地址到物理地址的转换,有两种方式,hva_to_pfn_fast、hva_to_pfn_slow // 正确性待验证 fn hva_to_pfn(addr: u64, _atomic: bool, _writable: &mut bool) -> Result { - kdebug!("hva_to_pfn"); + debug!("hva_to_pfn"); unsafe { let raw = addr as *const i32; - kdebug!("raw={:x}", *raw); + debug!("raw={:x}", *raw); } // let hpa = MMArch::virt_2_phys(VirtAddr::new(addr)).unwrap().data() as u64; let hva = VirtAddr::new(addr as usize); @@ -167,11 +165,11 @@ pub fn __gfn_to_pfn( write: bool, writable: &mut bool, ) -> Result { - kdebug!("__gfn_to_pfn"); + debug!("__gfn_to_pfn"); let mut nr_pages = 0; let addr = __gfn_to_hva_many(slot, gfn, Some(&mut nr_pages), write)?; let pfn = hva_to_pfn(addr, atomic, writable)?; - kdebug!("hva={}, pfn={}", addr, pfn); + debug!("hva={}, pfn={}", addr, pfn); return Ok(pfn); } diff --git a/kernel/src/virt/kvm/kvm_dev.rs b/kernel/src/virt/kvm/kvm_dev.rs index 3a900f6a..065c8539 100644 --- a/kernel/src/virt/kvm/kvm_dev.rs +++ b/kernel/src/virt/kvm/kvm_dev.rs @@ -1,4 +1,5 @@ use crate::driver::base::device::device_number::DeviceNumber; +use crate::filesystem; use crate::filesystem::devfs::{DevFS, DeviceINode}; use crate::filesystem::vfs::{ core::generate_inode_id, @@ -8,7 +9,6 @@ use crate::filesystem::vfs::{ use crate::libs::spinlock::SpinLockGuard; use crate::process::ProcessManager; use crate::{arch::KVMArch, libs::spinlock::SpinLock, time::PosixTimeSpec}; -use crate::{filesystem, kdebug}; // use crate::virt::kvm::{host_stack}; use super::push_vm; use crate::virt::kvm::vm_dev::LockedVmInode; @@ -17,6 +17,7 @@ use alloc::{ sync::{Arc, Weak}, vec::Vec, }; +use log::debug; use system_error::SystemError; pub const KVM_API_VERSION: u32 = 12; @@ -94,7 +95,7 @@ impl IndexNode for LockedKvmInode { _data: SpinLockGuard, _mode: &FileMode, ) -> Result<(), SystemError> { - kdebug!("file private data:{:?}", _data); + debug!("file private data:{:?}", _data); return Ok(()); } @@ -141,12 +142,12 @@ impl IndexNode for LockedKvmInode { ) -> Result { match cmd { 0xdeadbeef => { - kdebug!("kvm ioctl"); + debug!("kvm ioctl"); Ok(0) } KVM_GET_API_VERSION => Ok(KVM_API_VERSION as usize), KVM_CREATE_VM => { - kdebug!("kvm KVM_CREATE_VM"); + debug!("kvm KVM_CREATE_VM"); kvm_dev_ioctl_create_vm(data) } KVM_CHECK_EXTENSION diff --git a/kernel/src/virt/kvm/mod.rs b/kernel/src/virt/kvm/mod.rs index deb4b2fe..123984cb 100644 --- a/kernel/src/virt/kvm/mod.rs +++ b/kernel/src/virt/kvm/mod.rs @@ -1,9 +1,10 @@ use self::kvm_dev::LockedKvmInode; use crate::arch::KVMArch; use crate::filesystem::devfs::devfs_register; -use crate::kdebug; + use crate::libs::mutex::Mutex; use alloc::vec::Vec; +use log::debug; use vm::Vm; pub mod host_mem; @@ -23,7 +24,7 @@ pub static VM_LIST: Mutex> = Mutex::new(Vec::new()); pub fn push_vm(id: usize) -> Result<(), ()> { let mut vm_list = VM_LIST.lock(); if vm_list.iter().any(|x| x.id == id) { - kdebug!("push_vm: vm {} already exists", id); + debug!("push_vm: vm {} already exists", id); Err(()) } else { vm_list.push(Vm::new(id).unwrap()); @@ -54,14 +55,14 @@ pub fn vm(id: usize) -> Option { #[inline(never)] pub fn kvm_init() { - kdebug!("kvm init"); + debug!("kvm init"); match KVMArch::kvm_arch_cpu_supports_vm() { Ok(_) => { - kdebug!("[+] CPU supports Intel VMX"); + debug!("[+] CPU supports Intel VMX"); } Err(e) => { - kdebug!("[-] CPU does not support Intel VMX: {:?}", e); + debug!("[-] CPU does not support Intel VMX: {:?}", e); } }; @@ -76,9 +77,9 @@ pub fn kvm_init() { // let host_stack = vec![0xCC; HOST_STACK_SIZE]; // let guest_rsp = guest_stack.as_ptr() as u64 + GUEST_STACK_SIZE as u64; // let host_rsp = (host_stack.as_ptr() as u64) + HOST_STACK_SIZE as u64; - // kdebug!("guest rsp: {:x}", guest_rsp); - // kdebug!("guest rip: {:x}", guest_code as *const () as u64); - // kdebug!("host rsp: {:x}", host_rsp); + // debug!("guest rsp: {:x}", guest_rsp); + // debug!("guest rip: {:x}", guest_code as *const () as u64); + // debug!("host rsp: {:x}", host_rsp); // let hypervisor = Hypervisor::new(1, host_rsp, 0).expect("Cannot create hypervisor"); // let vcpu = VmxVcpu::new(1, Arc::new(Mutex::new(hypervisor)), host_rsp, guest_rsp, guest_code as *const () as u64).expect("Cannot create VcpuData"); // vcpu.virtualize_cpu().expect("Cannot virtualize cpu"); diff --git a/kernel/src/virt/kvm/vcpu_dev.rs b/kernel/src/virt/kvm/vcpu_dev.rs index 53e56e8c..ee8719e1 100644 --- a/kernel/src/virt/kvm/vcpu_dev.rs +++ b/kernel/src/virt/kvm/vcpu_dev.rs @@ -1,6 +1,7 @@ use crate::arch::kvm::vmx::vcpu::VcpuContextFrame; use crate::arch::KVMArch; use crate::driver::base::device::device_number::DeviceNumber; +use crate::filesystem; use crate::filesystem::devfs::DevFS; use crate::filesystem::vfs::{ core::generate_inode_id, file::FileMode, FilePrivateData, FileSystem, FileType, IndexNode, @@ -11,13 +12,13 @@ use crate::mm::VirtAddr; use crate::syscall::user_access::copy_from_user; use crate::virt::kvm::vcpu::Vcpu; use crate::virt::kvm::vm; -use crate::{filesystem, kdebug}; use crate::{libs::spinlock::SpinLock, time::PosixTimeSpec}; use alloc::{ string::String, sync::{Arc, Weak}, vec::Vec, }; +use log::debug; use system_error::SystemError; // pub const KVM_API_VERSION:u32 = 12; @@ -102,7 +103,7 @@ impl IndexNode for LockedVcpuInode { _data: SpinLockGuard, _mode: &FileMode, ) -> Result<(), SystemError> { - kdebug!("file private data:{:?}", _data); + debug!("file private data:{:?}", _data); return Ok(()); } @@ -149,11 +150,11 @@ impl IndexNode for LockedVcpuInode { ) -> Result { match cmd { 0xdeadbeef => { - kdebug!("kvm_cpu ioctl"); + debug!("kvm_cpu ioctl"); Ok(0) } KVM_RUN => { - kdebug!("kvm_cpu ioctl"); + debug!("kvm_cpu ioctl"); // let guest_stack = vec![0xCC; GUEST_STACK_SIZE]; // let host_stack = vec![0xCC; HOST_STACK_SIZE]; // let guest_rsp = guest_stack.as_ptr() as u64 + GUEST_STACK_SIZE as u64; @@ -177,12 +178,9 @@ impl IndexNode for LockedVcpuInode { VirtAddr::new(data), )?; } - kdebug!( + debug!( "rip={:x}, rflags={:x}, rsp={:x}, rax={:x}", - kvm_regs.rip, - kvm_regs.rflags, - kvm_regs.regs[6], - kvm_regs.regs[0], + kvm_regs.rip, kvm_regs.rflags, kvm_regs.regs[6], kvm_regs.regs[0], ); let vcpu = vm(0).unwrap().vcpu[0].clone(); @@ -191,7 +189,7 @@ impl IndexNode for LockedVcpuInode { Ok(0) } _ => { - kdebug!("kvm_cpu ioctl"); + debug!("kvm_cpu ioctl"); Ok(usize::MAX) } } diff --git a/kernel/src/virt/kvm/vm.rs b/kernel/src/virt/kvm/vm.rs index 5b2bbb27..23166aa4 100644 --- a/kernel/src/virt/kvm/vm.rs +++ b/kernel/src/virt/kvm/vm.rs @@ -1,10 +1,11 @@ use crate::arch::kvm::vmx::vcpu::VmxVcpu; +use crate::arch::KVMArch; use crate::arch::MMArch; use crate::libs::mutex::Mutex; use crate::mm::MemoryManagementArch; -use crate::{arch::KVMArch, kdebug}; use alloc::sync::Arc; use alloc::vec::Vec; +use log::debug; use system_error::SystemError; // use super::HOST_STACK_SIZE; @@ -13,7 +14,6 @@ use super::host_mem::{ KVM_ADDRESS_SPACE_NUM, KVM_MEM_LOG_DIRTY_PAGES, KVM_MEM_MAX_NR_PAGES, KVM_MEM_READONLY, KVM_MEM_SLOTS_NUM, KVM_USER_MEM_SLOTS, PAGE_SHIFT, }; -// use crate::kdebug; #[derive(Debug, Clone)] pub struct Vm { @@ -48,10 +48,10 @@ impl Vm { &mut self, mem: &KvmUserspaceMemoryRegion, ) -> Result<(), SystemError> { - kdebug!("set_user_memory_region"); + debug!("set_user_memory_region"); let id: u16 = mem.slot as u16; // slot id let as_id = mem.slot >> 16; // address space id - kdebug!("id={}, as_id={}", id, as_id); + debug!("id={}, as_id={}", id, as_id); // 检查slot是否合法 if mem.slot as usize >= self.nr_mem_slots as usize { diff --git a/kernel/src/virt/kvm/vm_dev.rs b/kernel/src/virt/kvm/vm_dev.rs index 4b2f1fac..9e7fd26c 100644 --- a/kernel/src/virt/kvm/vm_dev.rs +++ b/kernel/src/virt/kvm/vm_dev.rs @@ -1,4 +1,5 @@ use crate::driver::base::device::device_number::DeviceNumber; +use crate::filesystem; use crate::filesystem::devfs::DevFS; use crate::filesystem::vfs::{ core::generate_inode_id, @@ -14,12 +15,12 @@ use crate::virt::kvm::update_vm; use crate::virt::kvm::vcpu_dev::LockedVcpuInode; use crate::virt::kvm::vm; use crate::{arch::KVMArch, libs::spinlock::SpinLock, time::PosixTimeSpec}; -use crate::{filesystem, kdebug}; use alloc::{ string::String, sync::{Arc, Weak}, vec::Vec, }; +use log::debug; use system_error::SystemError; // pub const KVM_API_VERSION:u32 = 12; @@ -100,7 +101,7 @@ impl IndexNode for LockedVmInode { _data: SpinLockGuard, _mode: &FileMode, ) -> Result<(), SystemError> { - kdebug!("file private data:{:?}", _data); + debug!("file private data:{:?}", _data); return Ok(()); } @@ -147,15 +148,15 @@ impl IndexNode for LockedVmInode { ) -> Result { match cmd { 0xdeadbeef => { - kdebug!("kvm_vm ioctl"); + debug!("kvm_vm ioctl"); Ok(0) } KVM_CREATE_VCPU => { - kdebug!("kvm_vcpu ioctl KVM_CREATE_VCPU"); + debug!("kvm_vcpu ioctl KVM_CREATE_VCPU"); kvm_vm_ioctl_create_vcpu(data as u32) } KVM_SET_USER_MEMORY_REGION => { - kdebug!("kvm_vcpu ioctl KVM_SET_USER_MEMORY_REGION data={:x}", data); + debug!("kvm_vcpu ioctl KVM_SET_USER_MEMORY_REGION data={:x}", data); let mut kvm_userspace_mem = KvmUserspaceMemoryRegion::default(); // = unsafe { (data as *const KvmUserspaceMemoryRegion).as_ref().unwrap() }; unsafe { copy_from_user( @@ -166,7 +167,7 @@ impl IndexNode for LockedVmInode { VirtAddr::new(data), )?; } - kdebug!( + debug!( "slot={}, flag={}, memory_size={:x}, guest_phys_addr={}, userspace_addr={}", kvm_userspace_mem.slot, kvm_userspace_mem.flags, @@ -184,7 +185,7 @@ impl IndexNode for LockedVmInode { Err(SystemError::ENOSYS) } _ => { - kdebug!("kvm_vm ioctl"); + debug!("kvm_vm ioctl"); Ok(usize::MAX) } }